AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

408

Transcript of AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING L T P C 3 0 0 3

Objectives:

To develop an understanding of algorithmic problem solving. To develop Python programs with conditionals and loops. To define Python functions and call them. To use Python data structures - lists, tuples, dictionaries. To do input/output with files in Python.

UNIT I - ALGORITHMIC PROBLEM SOLVING 9 Introduction to computers - characteristics - basic organization of a computer - algorithms - building blocks of algorithms (instructions/statements, state, control flow, functions) - notation (pseudo code, flow chart, programming language) - algorithmic problem solving - simple strategies for developing algorithms (iteration, recursion). UNIT II - DATA, EXPRESSIONS, STATEMENTS AND CONTROL FLOW 9 Python interpreter and interactive mode - values and types - data types - variables - keywords - expressions and statements - python I/O - operators - precedence of operators – comments. Conditionals: conditional (if) - alternative (if-else) - chained conditional (if-elif-else) - nested conditional. Iteration: while - for - break - continue - pass. Illustrative programs: exchange the values of two variables - circulate the values of n variables - test for leap year. UNIT III - FUNCTIONS 9 Function calls - type conversion - math function - composition - definition and use - flow of execution - parameters and arguments. Fruitful functions: return values - parameters - scope: local and global - recursion. Strings: string slices - immutability - string functions and methods - string comparison. Illustrative programs: square root - GCD - exponentiation - sum the array of numbers - linear search - binary search. UNIT IV - COMPOUND DATA: LISTS, TUPLES AND DICTIONARIES 9 Lists - list operations - list slices - list methods - list loop - mutability - aliasing - cloning lists - list parameters. Tuples - immutable - tuple assignment - tuple as return value. Dictionaries: operations and methods - dictionaries and tuples - dictionaries and lists. Advanced list processing - list comprehension. Illustrative programs: Sorting. UNIT V - FILES, MODULES AND PACKAGES 9 Files and exception: file operation - text files - reading and writing files - format operator- command line arguments -errors and exceptions - handling exceptions - writing modules - packages. Illustrative programs: word count - copy file - case studies.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Outcomes:

Upon completion of the course, students will be able to: Develop algorithmic solutions to simple computational problems. Structure simple Python programs for solving problems. Decompose a Python program into functions. Represent compound data using Python lists, tuples and dictionaries. Read and write data from/to files in Python programs.

Text Books: 1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist’’, 2nd edition,

Updated for Python 3, Shroff/O’Reilly Publishers, 2016 (http://greenteapress.com/wp/think-python/)

References: 1. Anita Goel, Ajay Mittal, “Computer Fundamentals and programming in C”, Pearson India

Publisher, First edition, 2013. 2. John V Guttag, “Introduction to Computation and Programming Using Python’’, Revised and

expanded Edition, MIT Press, 2013 3. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in Python: An

Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016. 4. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd. 2015. 5. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning, 2012. 6. Charles Dierbach, “Introduction to Computer Science using Python: A Computational Problem-

Solving Focus, Wiley India Edition, 2013. 7. The Python Tutorial, https://docs.python.org/2.7/tutorial/

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

CHAPTER – 1 - INTRODUCTION TO COMPUTER 1.1 INTRODUCTION

The term computer is derived from the word compute. The word compute means to calculate. A computer is an electronic machine that accepts data from the user, processes the data by performing calculations and operations on it, and generates the desired output results. Computer performs both simple and complex operations, with speed and accuracy.

1.2 DIGITAL AND ANALOG COMPUTERS

A digital computer uses distinct values to represent the data internally. All information are represented using the digits Os and 1s. The computers that we use at our homes and offices are digital computers.

Analog computer is another kind of a computer that represents data as variable across a

continuous range of values. The earliest computers were analog computers. Analog computers are used for measuring of parameters that vary continuously in real time, such as temperature, pressure and voltage. Analog computers may be more flexible but generally less precise than digital computers. Slide rule is an example of an analog computer.

1.3 CHARACTERISTICS OF COMPUTER

Speed, accuracy, diligence, storage capability and versatility are some of the key characteristics of a computer.

Speed The computer can process data very fast, at the rate of millions of instructions per

second. Some calculations that would have taken hours and days to complete otherwise, can be completed in a few seconds using the computer. For example, calculation and generation of salary slips of thousands of employees of an organization, weather forecasting that requires analysis of a large amount of data related to temperature, pressure and humidity of various places, etc.

Accuracy Computer provides a high degree of accuracy. For example, the computer can

accurately give the result of division of any two numbers up to 10 decimal places. Diligence When used for a longer period of time, the computer does not get tired or

fatigued. It can perform long and complex calculations with the same speed and accuracy from the start till the end.

Storage Capability Large volumes of data and information can be stored in the computer and also retrieved whenever required. A limited amount of data can be stored, temporarily, in the primary memory. Secondary storage devices like floppy disk and compact disk can store a large amount of data permanently.

Versatility Computer is versatile in nature. It can perform different types of tasks with

the same ease. At one moment you can use the computer to prepare a letter document and in the next moment you may play music or print a document.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Computers have several limitations too. Computer can only perform tasks that it has been programmed to do. Computer cannot do any work without instructions from the user. It executes instructions as specified by the user and does not take its own decisions. 1.4 CLASSIFICATION OF COMPUTER

The digital computers that are available nowadays vary in their sizes and types. The computers are broadly classified into four categories (Figure 1.1) based on their size and type—(1) Microcomputers, (2) Minicomputers, (3) Mainframe computers, and (4) Supercomputer.

Figure 1.1 Classification of computers based on size and type 1.4.1 Microcomputers

Microcomputers are small, low-cost and single-user digital computer. They consist of CPU, input unit, output unit, storage unit and the software. Although microcomputers are stand-alone machines, they can be connected together to create a network of computers that can serve more than one user. IBM PC based on Pentium microprocessor and Apple Macintosh are some examples of microcomputers. Microcomputers include desktop computers, notebook computers or laptop, tablet computer, handheld computer, smart phones and netbook, as shown in Figure 1.2.

Desktop Computer or Personal Computer (PC) is the most common type of

microcomputer. It is a stand-alone machine that can be placed on the desk. Externally, it consists of three units—keyboard, monitor, and a system unit containing the CPU, memory, hard disk drive, etc. It is not very expensive and is suited to the needs of a single user at home, small business units, and organizations. Apple, Microsoft, HP, Dell and Lenovo are some of the PC manufacturers.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Figure 1.2 Microcomputers

Notebook Computers or Laptop resemble a notebook. They are portable and have all the features of a desktop computer. The advantage of the laptop is that it is small in size (can be put inside a briefcase), can be carried anywhere, has a battery backup and has all the functionality of the desktop. Laptops can be placed on the lap while working (hence the name). Laptops are costlier than the desktop machines.

Netbook These are smaller notebooks optimized for low weight and low cost, and are

designed for accessing web-based applications. Starting with the earliest netbook in late 2007, they have gained significant popularity now. Netbooks deliver the performance needed to enjoy popular activities like streaming videos or music, emailing, Web surfing or instant messaging. The word netbook was created as a blend of Internet and notebook.

Tablet Computer has features of the notebook computer but it can accept input from a stylus or a pen instead of the keyboard or mouse. It is a portable computer. Tablet computer are the new kind of PCs.

Handheld Computer or Personal Digital Assistant (PDA) is a small computer that can be held on the top of the palm. It is small in size. Instead of the keyboard, PDA uses a pen or a stylus for input. PDAs do not have a disk drive. They have a limited memory and are less powerful. PDAs can be connected to the Internet via a wireless connection. Casio and Apple are some of the manufacturers of PDA. Over the last few years, PDAs have merged into mobile phones to create smart phones.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Smart Phones are cellular phones that function both as a phone and as a small PC. They may use a stylus or a pen, or may have a small keyboard. They can be connected to the Internet wirelessly. They are used to access the electronic-mail, download music, play games, etc. Blackberry, Apple, HTC, Nokia and LG are some of the manufacturers of smart phones. 1.4.2 Minicomputers

Minicomputers (Figure 1.3) are digital computers, generally used in multi-user systems. They have high processing speed and high storage capacity than the microcomputers. Minicomputers can support 4–200 users simultaneously. The users can access the minicomputer through their PCs or terminal. They are used for real-time applications in industries, research centers, etc. PDP 11, IBM (8000 series) are some of the widely used minicomputers.

Figure 1.3 Minicomputer 1.4.3 Mainframe Computers

Mainframe computers (Figure 1.4) are multi-user, multi-programming and high performance computers. They operate at a very high speed, have very large storage capacity and can handle the workload of many users. Mainframe computers are large and powerful systems generally used in centralized databases. The user accesses the mainframe computer via a terminal that may be a dumb terminal, an intelligent terminal or a PC. A dumb terminal cannot store data or do processing of its own. It has the input and output device only. An intelligent terminal has the input and output device, can do processing, but, cannot store data of its own. The dumb and the intelligent terminal use the processing power and the storage facility of the mainframe computer. Mainframe computers are used in organizations like banks or companies, where many people require frequent access to the same data. Some examples of mainframes are CDC 6600 and IBM ES000 series.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Figure 1.4 Mainframe computer 1.4.4 Supercomputers

Supercomputers (Figure 1.5) are the fastest and the most expensive machines. They have high processing speed compared to other computers. The speed of a supercomputer is generally measured in FLOPS (FLoating point Operations Per Second). Some of the faster supercomputers can perform trillions of calculations per second. Supercomputers are built by interconnecting thousands of processors that can work in parallel.

Figure 1.5 Supercomputer

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Supercomputers are used for highly calculation-intensive tasks, such as, weather forecasting, climate research (global warming), molecular research, biological research, nuclear research and aircraft design. They are also used in major universities, military agencies and scientific research laboratories. Some examples of supercomputers are IBM Roadrunner, IBM Blue gene and Intel ASCI red. PARAM is a series of supercomputer assembled in India by C-DAC (Center for Development of Advanced Computing), in Pune. PARAM Padma is the latest machine in this series. The peak computing power of PARAM Padma is 1 Tera FLOP (TFLOP).

1.5 Components of Computer Hardware

The computer system hardware comprises of three main components: 1. Input/Output (I/O) Unit, 2. Central Processing Unit (CPU), and 3. Memory Unit.

The I/O unit consists of the input unit and the output unit. CPU performs calculations and

processing on the input data, to generate the output. The memory unit is used to store the data, the instructions and the output information. Figure 1.6 illustrates the typical interaction among the different components of the computer.

Figure 1.6 The computer system interaction

Input/Output Unit The user interacts with the computer via the I/O unit. The Input unit accepts data from the user and the Output unit provides the processed data i.e. the information to the user. The Input unit converts the data that it accepts from the user, into a form that is understandable by the computer. Similarly, the Output unit provides the output in a form that is understandable by the user. The input is provided to the computer using input devices like keyboard, trackball and mouse. Some of the commonly used output devices are monitor and printer.

Central Processing Unit CPU controls, coordinates and supervises the operations of the computer. It is responsible for processing of the input data. CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

ALU performs all the arithmetic and logic operations on the input data. CU controls the overall operations of the computer i.e. it checks the sequence of

execution of instructions, and, controls and coordinates the overall functioning of the units of computer.

Additionally, CPU also has a set of registers for temporary storage of data, instructions,

addresses and intermediate results of calculation. Memory Unit Memory unit stores the data, instructions, intermediate results and

output, temporarily, during the processing of data. This memory is also called the main memory or primary memory of the computer. The input data that is to be processed is brought into the main memory before processing. The instructions required for processing of data and any intermediate results are also stored in the main memory. The output is stored in memory before being transferred to the output device. CPU can work with the information stored in the main memory. Another kind of storage unit is also referred to as the secondary memory of the computer. The data, the programs and the output are stored permanently in the storage unit of the computer. Magnetic disks, optical disks and magnetic tapes are examples of secondary memory. 1.6 APPLICATION OF COMPUTERS

Computers have proliferated into various areas of our lives. For a user, computer is a tool that provides the desired information, whenever needed. You may use computer to get information about the reservation of tickets (railways, airplanes and cinema halls), books in a library, medical history of a person, a place in a map, or the dictionary meaning of a word. The information may be presented to you in the form of text, images, video clips, etc.

Figure 1.7 shows some of the applications of computer.

Figure 1.7 Applications of computer

Some of the application areas of the computer are listed below:

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Education Computers are extensively used, as a tool and as an aid, for imparting education. Educators use computers to prepare notes and presentations of their lectures. Computers are used to develop computer-based training packages, to provide distance education using the e-learning software, and to conduct online examinations. Researchers use computers to get easy access to conference and journal details and to get global access to the research material.

Entertainment Computers have had a major impact on the entertainment industry. The user can download and view movies, play games, chat, book tickets for cinema halls, use multimedia for making movies, incorporate visual and sound effects using computers, etc. The users can also listen to music, download and share music, create music using computers, etc.

Sports A computer can be used to watch a game, view the scores, improve the game, play games (like chess, etc.) and create games. They are also used for the purposes of training players.

Advertising Computer is a powerful advertising media. Advertisement can be displayed

on different websites, electronic-mails can be sent and reviews of a product by different customers can be posted. Computers are also used to create an advertisement using the visual and the sound effects. For the advertisers, computer is a medium via which the advertisements can be viewed globally. Web advertising has become a significant factor in the marketing plans of almost all companies. In fact, the business model of Google is mainly dependent on web advertising for generating revenues.

Medicine Medical researchers and practitioners use computers to access information

about the advances in medical research or to take opinion of doctors globally. The medical history of patients is stored in the computers. Computers are also an integral part of various kinds of sophisticated medical equipments like ultrasound machine, CAT scan machine, MRI scan machine, etc. Computers also provide assistance to the medical surgeons during critical surgery operations like laparoscopic operations, etc.

Science and Engineering Scientists and engineers use computers for performing complex scientific calculations, for designing and making drawings (CAD/CAM applications) and also for simulating and testing the designs. Computers are used for storing the complex data, performing complex calculations and for visualizing 3–dimensional objects. Complex scientific applications like the launch of the rockets, space exploration, etc., are not possible without the computers.

Government The government uses computers to manage its own operations and also for e-governance. The websites of the different government departments provide information to the users. Computers are used for the filing of income tax return, paying taxes, online submission of water and electricity bills, for the access of land record details, etc. The police department uses computers to search for criminals using fingerprint matching, etc.

Home Computers have now become an integral part of home equipment. At home, people use computers to play games, to maintain the home accounts, for communicating with friends and relatives via Internet, for paying bills, for education and learning, etc. Microprocessors are embedded in house hold utilities like, washing machines, TVs, food processors, home theatres, security devices, etc.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

The list of applications of computers is so long that it is not possible to discuss all of them here. In addition to the applications of the computers discussed above, computers have also proliferated into areas like banks, investments, stock trading, accounting, ticket reservation, military operations, meteorological predictions, social networking, business organizations, police department, video conferencing, telepresence, book publishing, web newspapers, and information sharing.

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

QUESTIONS 1. Define a computer. 2. Define an analog computer and a digital computer. 3. Give an example each of analog computer and digital computer. 4. List the main characteristics of the computer. 5. Describe the characteristics of the computer. 6. List three significant limitations of the computer. 7. Define microcomputer. 8. Give two examples of microcomputer. 9. List three categories of microcomputers. 10. Define minicomputers. 11. Give two examples of minicomputer. 12. Define mainframe computer. 13. Give two examples of mainframe computer. 14. Define a dumb terminal. 15. Define an intelligent terminal. 16. Define a supercomputer. 17. Give two examples of supercomputer. 18. The speed of supercomputer is generally measured in_____. 19. List two uses of the supercomputer. 20. Name the supercomputer assembled in India. 21. Highlight the differences between microcomputer, minicomputer, mainframe computer and

supercomputer. 22. List the components of computer hardware. 23. Explain in detail the components of computer hardware. 24. List some areas where the computers are used. 25. Explain briefly the use of computers in the following areas—(a) Education, (b) Advertising,

and (c) Government.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

CHAPTER - 2 - COMPUTER PROGRAMMING FUNDAMENTALS 2.1 PROGRAM DEVELOPMENT LIFE CYCLE

As stated earlier, a program is needed to instruct the computer about the way a task is to be performed. The instructions in a program have three essential parts:

1. Instructions to accept the input data that needs to be processed, 2. Instructions that will act upon the input data and process it, and 3. Instructions to provide the output to user

The instructions in a program are defined in a specific sequence. Writing a computer

program is not a straightforward task. A person who writes the program (computer programmer) has to follow the Program Development Life Cycle.

Let’s now discuss the steps that are followed by the programmer for writing a program: Problem Analysis - The programmer first understands the problem to be solved. The

programmer determines the various ways in which the problem can be solved, and decides upon a single solution which will be followed to solve the problem.

Program Design - The selected solution is represented in a form, so that it can be coded. This requires three steps:

An algorithm is written, which is an English-like explanation of the solution. A flowchart is drawn, which is a diagrammatic representation of the solution. The

solution is represented diagrammatically, for easy understanding and clarity.

A pseudo code is written for the selected solution. Pseudo code uses the structured programming constructs. The pseudo code becomes an input to the next phase.

Program Development

The computer programming languages are of different kinds—low-level languages, and high- level languages like C, C++ and Java. The pseudo code is coded using a suitable programming language.

The coded pseudo code or program is compiled for any syntax errors. Syntax errors arise due to the incorrect use of programming language or due to the grammatical errors with respect to the programming language used. During compilation, the syntax errors, if any, are removed.

The successfully compiled program is now ready for execution.

The executed program generates the output result, which may be correct or incorrect. The program is tested with various inputs, to see that it generates the desired results. If incorrect results are displayed, then the program has semantic error (logical error). The semantic errors are removed from the program to get the correct results.

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The successfully tested program is ready for use and is installed on the user’s machine.

Program Documentation and Maintenance - The program is properly documented, so that later on, anyone can use it and understand its working. Any changes made to the program, after installation, forms part of the maintenance of program. The program may require updating, fixing of errors etc. during the maintenance phase.

Table 2.1 summarises the steps of the program development cycle.

Program Analysis • Understand the problem • Have multiple solutions • Select a solution

Program Design • Write Algorithm • Write Flowchart •Write Pseudo code

Program Development • Choose a programming language • Write the program by converting the pseudo code, and then using the programming language. • Compile the program and remove syntax errors, if any • Execute the program. • Test the program. Check the output results with different inputs. If the output is incorrect, modify the program to get correct results. • Install the tested program on the user’s computer.

Program Documentation and maintenance

• Document the program, for later use. • Maintain the program for updating, removing errors, changing requirements etc.

Table 2.1 Program development life cycle

2.2 ALGORITHM

Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for

completing a task. Algorithm is an English-like representation of the logic which is used to solve the problem. It is a step- by-step procedure for solving a task or a problem. The steps must be ordered, unambiguous and finite in number.

For accomplishing a particular task, different algorithms can be written. The different

algorithms differ in their requirements of time and space. The programmer selects the best-suited algorithm for the given task to be solved.

Let’s now look at two simple algorithms to find the greatest among three numbers, as

follows:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

Algorithm to find the greatest among three numbers: ALGORITHM 1.

Step 1: Start Step 2: Read the three numbers A, B, C Step 3: Compare A and B. If A is greater perform step 4 else perform step 5. Step 4: Compare A and C. If A is greater, output “A is greatest” else output “C is greatest”. Perform step 6. Step 5: Compare B and C. If B is greater, output “B is greatest” else output “C is greatest”. Step 6: Stop

ALGORITHM 2.

Step 1: Start Step 2: Read the three numbers A, B, C Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX. Step 4: Compare MAX and C. If MAX is greater, output “MAX is greatest” else output “C is greatest”. Step 5: Stop

Both the algorithms accomplish the same goal, but in different ways. The programmer

selects the algorithm based on the advantages and disadvantages of each algorithm. For example, the first algorithm has more number of comparisons, whereas in the second algorithm an additional variable MAX is required. 2.3 CONTROL STRUCTURES

The logic of a program may not always be a linear sequence of statements to be executed

in that order. The logic of the program may require execution of a statement based on a decision. It may repetitively execute a set of statements unless some condition is met. Control structures specify the statements to be executed and the order of execution of statements.

Flowchart and Pseudo code use control structures for representation. There are three

kinds of control structures:

Sequential - instructions are executed in linear order

Selection (branch or conditional) - it asks a true/false question and then selects the next instruction based on the answer

Iterative (loop) - it repeats the execution of a block of instructions.

The flowchart and the pseudo code control structures are explained in their respective sections.

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2.4 FLOWCHART

A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is drawn using boxes of different shapes with lines connecting them to show the flow of control. The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form. There is a famous saying S“A photograph is equivalent to thousand wordsS”. The same can be said of flowchart. The logic of the program is communicated in a much better way using a flowchart. Since flowchart is a diagrammatic representation, it forms a common medium of communication. 2.4.1 Flowchart Symbols

A flowchart is drawn using different kinds of symbols. A symbol used in a flowchart is for a specific purpose. Figure 2.1 shows the different symbols of the flowchart along with their names. The flowchart symbols are available in most word processors including MS-WORD, facilitating the programmer to draw a flowchart on the computer using the word processor.

Figure 2.1 Flowchart symbols (available for use in MS-WORD)

A single line description of the flowchart symbols is given in Table 2.2.

Process—operation or action step Decision—decision or a branch Alternate Process—alternate to normal process Data—I/O to or from a process Document—a document Manual Input—Data entry from a form Multi document—more than one document Manual Operation—operation to be done manually Preparation—set-up process Connector—join flow lines Punched Tape—I/O from punched tape Off page connector—continue on another page Collate—organize in a format Summing Junction—Logical AND Merge—merge in a predefined order OR—Logical OR

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

Sort—sort in some order Sequential Access storage—stored on magnetic tape Display—display output Stored Data—general data storage Predefined process—process previously specified Magnetic Disk—I/O from magnetic disk Internal Storage—stored in memory Direct access storage—storing on hard disk Termination—start or stop point Flow lines—indicates direction of flow Delay—wait Extract—split process Card—I/O from a punched card

Table 2.2 Description of flowchart symbols

2.4.2 Preparing a Flowchart

A flowchart may be simple or complex. The most common symbols that are used to draw a flowchart are - Process, Decision, Data, Terminator, Connector and Flow lines. While drawing a flowchart, some rules need to be followed—(1) A flowchart should have a start and end, (2) The direction of flow in a flowchart must be from top to bottom and left to right, and (3) The relevant symbols must be used while drawing a flowchart. While preparing the flowchart, the sequence, selection or iterative structures may be used wherever required. Figure 2.2 shows the sequence, selection and iteration structures.

Figure 2.2 Control structures in flowchart

We see that in a sequence, the steps are executed in linear order one after the other. In a selection operation, the step to be executed next is based on a decision taken. If the condition is true (yes) a different path is followed than if the condition evaluates to false (no). In case of iterative operation, a condition is checked. Based upon the result of this conditional check, true or false, different paths are followed. Either the next step in the sequence is executed or the control goes back to one of the already executed steps to make a loop.

Here, we will illustrate the method to draw flowchart, by discussing three different examples. To draw the flowcharts, relevant boxes are used and are connected via flow lines. The flowchart for the examples is shown in Figure 2.3.

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Figure 2.3 Examples of flowchart

The first flowchart computes the product of any two numbers and gives the result. The flowchart is a simple sequence of steps to be performed in a sequential order.

The second flowchart compares three numbers and finds the maximum of the three numbers. This flowchart uses selection. In this flowchart, decision is taken based upon a condition, which decides the next path to be followed, i.e. If A is greater than B then the true (Yes) path is followed else the false (No) path is followed. Another decision is again made while comparing MAX with C.

The third flowchart finds the sum of first 100 integers. Here, iteration (loop) is performed so that some steps are executed repetitively until they fulfill some condition to exit from the repetition. In the decision box, the value of I is compared with 100. If it is false (No), a loop is created which breaks when the condition becomes true (Yes).

Flowcharts have their own benefits; however, they have some limitations too. A complex

and long flowchart may run into multiple pages, which becomes difficult to understand and follow. Moreover, updating a flowchart with the changing requirements is a challenging job. 2.5 PSEUDO CODE

Pseudo code consists of short, readable and formally-styled English language used for explaining an algorithm. Pseudo code does not include details like variable declarations, subroutines etc. Pseudo code is a short-hand way of describing a computer program. Using pseudo code, it is easier for a programmer or a non-programmer to understand the general working of the program, since it is not based on any programming language. It is used to give a sketch of the structure of the program, before the actual coding. It uses the structured constructs of the

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

programming language but is not machine-readable. Pseudo code cannot be compiled or executed. Thus, no standard for the syntax of pseudo code exists. For writing the pseudo code, the programmer is not required to know the programming language in which the pseudo code will be implemented later. 2.5.1 Preparing a Pseudo Code

Pseudo code is written using structured English.

In a pseudo code, some terms are commonly used to represent the various actions. For example, for inputting data the terms may be (INPUT, GET, READ), for outputting data (OUTPUT, PRINT, DISPLAY), for calculations (COMPUTE, CALCULATE), for incrementing (INCREMENT), in addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction, and initialization, respectively.

The control structures—sequence, selection, and iteration are also used while writing the pseudo code.

Figure 2.4 shows the different pseudo code structures. The sequence structure is simply a sequence of steps to be executed in linear order. There are two main selection constructs—if-statement and case statement. In the if-statement, if the condition is true then the THEN part is executed otherwise the ELSE part is executed. There can be variations of the if-statement also, like there may not be any ELSE part or there may be nested ifs. The case statement is used where there are a number of conditions to be checked. In a case statement, depending on the value of the expression, one of the conditions is true, for which the corresponding statements are executed. If no match for the expression occurs, then the OTHERS option which is also the default option, is executed.

Figure 2.4 Control structures for pseudo code

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

WHILE and DO-WHILE are the two iterative statements. The WHILE loop and the DO-WHILE loop, both execute while the condition is true. However, in a WHILE loop the condition is checked at the start of the loop, whereas, in a DO-WHILE loop the condition is checked at the end of the loop. So the DO-WHILE loop executes at least once even if the condition is false when the loop is entered.

In Figure 2.5, the pseudo code is written for the same three tasks for which the flowchart

was shown in the previous section. The three tasks are—(i) compute the product of any two numbers, (ii) find the maximum of any three numbers, and (iii) find the sum of first 100 integers.

Figure 2.5 Examples of pseudo code

A pseudo code is easily translated into a programming language. But, as there are no defined standards for writing a pseudo code, programmers may use their own style for writing the pseudo code, which can be easily understood. Generally, programmers prefer to write pseudo code instead of flowcharts.

Difference between Algorithm, Flowchart, and Pseudo Code: An algorithm is a sequence of instructions used to solve a particular problem. Flowchart and Pseudo code are tools to document and represent the algorithm. In other words, an algorithm can be represented using a flowchart or a pseudo code. Flowchart is a graphical representation of the algorithm. Pseudo code is a readable, formally styled English like language representation of the algorithm. Both flowchart and pseudo code use structured constructs of the programming language for representation. The user does not require the knowledge of a programming language to write or understand a flowchart or a pseudo code.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

QUESTIONS 1. Define a program. 2. Explain the program development life cycle in detail. 3. What is the difference between syntax error and semantic error? 4. Define syntax error. 5. Define semantic error. 6. What is the purpose of program maintenance? 7. Define algorithm. 8. What are control structures? 9. Name the three kinds of control structures. 10. State the purpose of each of the control structures:

i. Sequence, ii. Selection, and

iii. Iteration. 11. Define flowchart. 12. Draw the flowchart symbol for the following—(i) Process, (ii) Decision, (iii) Document, (iv)

Connector, and (v) Magnetic Disk. 13. State the meaning of the following flowchart symbols—(i) Process, (ii) Decision, (iii)

Document, (iv) Connector, (v) Magnetic Disk, and (vi) Flow lines. 14. Draw the control structures (Sequence, Selection and Iteration) for the flowchart. 15. Define pseudo code. 16. Write the pseudo code control structures (sequence, selection, and iteration). 17. What is the difference between WHILE and DO- WHILE statements?

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISE Write the algorithm, draw a flowchart, and write pseudo code for the following: a. To find the sum of square root of any three numbers. b. To find the sum of first 100 integers. c. To find the sum of all even numbers till 100. d. To find the sum of all odd numbers till 100. e. To find the sum of any five integers. f. To find the factorial of a number n. Hint: n! = n(n−1)(n−2)….3.2.1 g. To find the first n numbers in a Fibonacci series. Hint: f(0) = 0, f(1) = 1, f(n) = f(n−1) + f(n−2) h. To find the sum of digits of a number. (For example, for number 345 find 3+4+5) i. To check whether a number is prime or not. j. To convert the temperature from Fahrenheit to Celsius. Hint: C= (5/9)*(F-32)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

UNIT – I

IMPORTANT QUESTIONS

PART - A 1. Define the term Computer. 2. Distinguish between Analog and Digital computer. (or) Differentiate analog and digital

computer. 3. State the characteristics of computers. (or) List out the characteristics of computer. (or) List

any two important characteristics of computers. 4. What are the factors needed to classify computers? (or) How will you classify computer

systems? (or) Classify the computers based on performance, size, cost and capacity. (or) Give the classification of computers. (or) What are the classifications of computer?

5. What are Mainframe computers? Give the name of any one Mainframe computer. 6. What is super computer? Give an example. 7. State the components of a computer. 8. Differentiate between hardware and software. (or) What are the differences between

software and hardware in computer? 9. Write down steps involved in writing a program to solve a problem. 10. What is an algorithm? 11. Enlist the advantages of algorithm. 12. What are the characteristics of algorithms in computer? 13. What is flow chart? (or) Define flow chart. Why is flow chart required? (or) What are

flowcharts and list down their advantages? 14. Draw a flow chart to find biggest of two numbers. 15. Draw a flowchart to find the maximum among the three numbers. 16. Draw a flow chart to calculate sum of ‘n’ numbers. 17. Define pseudo code. (or) What is pseudo code? What is the purpose of it? 18. What are the benefits of pseudo code? 19. Write two characteristics of pseudo code. 20. List any two characteristics and two advantages of pseudo code. 21. Differentiate between algorithm and pseudo code. 22. What is the difference between program and algorithm?

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PART - B 1. Explain different types of computers. 2. Explain the characteristics of computers. (or) List and discuss the characteristics of computers.

(or) Describe the characteristics of computers in detail. 3. Explain the various classifications of computers in detail. (or) What are the characteristics of a

computer? Discuss. (or) How computers can be classified? Explain. (or) Classify computers on the basis of size and capabilities and discuss the same. (or) Briefly discuss about the classification of computers with their features and limitations.

4. With suitable diagram, explain the basic organisation of computers. (or) With suitable diagram explain about computer organization. (or) Explain the basic organization of a computer with a neat diagram in detail. (or) Describe the basic computer organization with neat diagram. (or) Explain the different components of a computer system with block diagram. (or) Explain the basic organization of computer with suitable block diagram. (or) Write in detail about the basic organization of a computer. (or) Explain in detail with neat diagram about the digital computer organization and each of its unit. (or) Draw the block diagram to illustrate the basic organization of computer system and explain the functions of the various units. (or) Diagrammatically illustrate and discuss the basic computer organization. (or) Explain the functions of various components of a typical computer.

5. What are the applications of computer? Discuss in detail about classification of computer. 6. Describe the steps involved in computer programming. 7. What is an algorithm? Write an algorithm to print even numbers from 2 to 100. 8. Describe the characteristic of the algorithms. 9. Write an algorithm to print the Fibonacci series.

(0, 1, 1, 2, 3, 5, 8, 13, ....) 10. Write an algorithm for finding sum and average of n numbers. Also state the properties of a

good algorithm. 11. Write down the algorithm to find the largest number among three given numbers and outline

the steps in the algorithm with the inputs 5, 17, 3. 12. Write an algorithm for finding sum and average of n numbers. Also state the properties of a

good algorithm. 13. Write an algorithm to find the largest of three numbers. 14. Write an algorithm to print whether a given number A is even or odd. 15. Write an algorithm to print the factorial of a given number A (A > 1). 16. Write an algorithm to compute the factorial of a number n. 17. Write an algorithm to compute and print the quotient and remainder of two numbers A and B. 18. Explain with diagram symbols used in flowchart and the basic design structures in flow chart. 19. Explain guidelines for preparing flow charts, benefits and limitation of flowcharts. 20. What are the different symbols used in flow chart? Develop a flow chart to find the sum of first

50 odd numbers. 21. Draw a flow chart to find sum first 100 natural numbers. 22. Draw a flow chart to find factorial of a number. 23. Draw a flowchart to check whether the given number is zero, positive or negative. 24. Draw the flowchart to solve the quadratic equation. 25. Draw a flowchart to add two matrices. 26. Draw a flowchart to multiply two matrices. 27. Draw the flowchart for finding the roots of a quadratic equation. 28. Draw the flowchart and write an algorithm to sort a list of numbers in ascending order. 29. Draw a flowchart to find the highest marks in a set of n marks.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

30. Draw and explain the various symbols of flowchart and also draw the Flowchart to add an array of N elements.

31. Draw flowchart to compute the salary of an employee in a company. Assume that there are two types of employees in the company daily wages and regular. Salary is calculated as number of hours worked* wages per hour for daily wagers and basic pay +(% of DA * basic pay)/100 + HRA + medical allowance for regular employees. Sketch the flow of your design for a regular employee with basic pay = 5000, % of DA=75% and HRA=500.

32. Write an algorithm and flowchart to simulate the railway ticket booking process. 33. Explain about algorithm, pseudo code and flow chart with an example of finding the sum of ‘n’

numbers. 34. Write the uses of flowchart and algorithm with suitable examples. 35. What is pseudo code? Explain its guidelines and benefits. 36. What is pseudo code? Explain how it can be designed and its benefits and limitations. 37. What is pseudo code? Write a pseudo code for swapping two numbers without using

temporary storage. 38. What is pseudo code? How does it differ from flowchart? Write a pseudo code to add up all

the even numbers between 0 and 100 and print the result. 39. What is pseudo code? How does it differ from flowchart? Write a pseudo code to add up all

the even numbers between 0 and 100 and print the result. 40. What are the advantages and disadvantages of pseudo code? Write pseudo code to sort the

given N integer numbers in descending order. 41. Explain sequence logic, selection logic and iteration logic design structure in pseudocode. 42. Write the pseudo code to multiply two matrices. 43. Write a pseudo code for calculating compound interest. 44. Write the pseudocode to add two matrices. 45. Write the pseudo code and algorithm for find whether the given number is odd or even. 46. Discuss about algorithm, flow chart and pseudo code and elaborate their role while writing a

program. Write an algorithm, draw a flow chart and write pseudo code for the problem of generating triangular number sequence 1, 3, 6, 10, 15, 21, 28, 36, 45, . . . [Given value of the nth term = n * (n + 1) / 2].

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai – 602 105

Department of Computer Science and Engineering CAT - I - Part – A - Question Bank

GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING 1. The term computer is derived from the word compute. 2. A computer is an electronic machine that accepts data from the user, processes the data by

performing calculations and operations on it, and generates the desired output results. 3. Speed, accuracy, diligence, storage capability and versatility are some of the key characteristics

of a computer. 4. The computer can process data very fast, at the rate of millions of instructions per second. 5. The computer system hardware comprises of three main components Input/Output (I/O) Unit,

Central Processing Unit (CPU), and Memory Unit. 6. The I/O unit consists of the input unit and the output unit. 7. The user interacts with the computer via the I/O unit. 8. The Input unit accepts data from the user and the Output unit provides the processed data i.e.

the information to the user. 9. The Input unit converts the data that it accepts from the user, into a form that is

understandable by the computer. 10. The Output unit provides the output in a form that is understandable by the user. 11. The input is provided to the computer using input devices like keyboard, trackball and mouse. 12. The commonly used output devices are monitor and printer. 13. Central Processing Unit (CPU) controls, coordinates and supervises the operations of the

computer. 14. Central Processing Unit (CPU) consists of Arithmetic Logic Unit (ALU) and Control Unit (CU). 15. Arithmetic Logic Unit (ALU) performs all the arithmetic and logic operations on the input data. 16. Control unit (CU) controls the overall operations of the computer i.e. it checks the sequence of

execution of instructions, and, controls and coordinates the overall functioning of the units of computer.

17. Memory unit stores the data, instructions, intermediate results and output, temporarily, during the processing of data.

18. The main memory is also called as primary memory of the computer. 19. Magnetic disks, optical disks and magnetic tapes are examples of secondary memory. 20. Some of the application areas of the computer are Education, Entertainment, Sports,

Advertising, Medicine, Science and Engineering, Government, and Home. 21. The steps that are followed by the programmer for writing a program: Problem Analysis,

Program Design, Program Development, and Program Documentation and Maintenance. 22. Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for

completing a task. 23. Algorithm is an English-like representation of the logic which is used to solve the problem. 24. Algorithm is a step- by-step procedure for solving a task or a problem. 25. The steps in algorithm must be ordered, unambiguous and finite in number. 26. Control structures specify the statements to be executed and the order of execution of

statements. 27. Flowchart and Pseudo code use control structures for representation. 28. The three kinds of control structures are Sequential, Selection and Iterative. 29. Sequential - instructions are executed in linear order

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

30. Selection (branch or conditional) - it asks a true/false question and then selects the next instruction based on the answer

31. Iterative (loop) - it repeats the execution of a block of instructions. 32. A flowchart is a diagrammatic representation of the logic for solving a task. 33. A flowchart is drawn using boxes of different shapes with lines connecting them to show the

flow of control. 34. The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form. 35. The most common symbols that are used to draw a flowchart are - Process, Decision, Data,

Terminator, Connector and Flow lines. 36. Pseudo code consists of short, readable and formally-styled English language used for

explaining an algorithm. 37. Pseudo code is a short-hand way of describing a computer program. 38. For writing the pseudo code, the programmer is not required to know the programming

language in which it will be implemented later. 39. In a pseudo code, some terms are commonly used to represent the various actions. For

example, for inputting data the terms may be INPUT, GET, and READ. 40. In a pseudo code, some terms are commonly used to represent the various actions. For

example, for outputting data OUTPUT, PRINT, and DISPLAY. 41. In a pseudo code, some terms are commonly used to represent the various actions. For

example, for calculations COMPUTE, and CALCULATE. 42. In a pseudo code, some terms are commonly used to represent the various actions. For

example, for incrementing and decrementing INCREMENT and DECREMENT. 43. In a pseudo code, some terms are commonly used to represent the various actions. For

example, in addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction, and initialization, respectively.

44. There are two main selection constructs—if-statement and case statement. 45. WHILE and DO-WHILE are the two iterative statements. 46. Give full form of the abbreviation: CPU - Central Processing Unit 47. Give full form of the abbreviation: I/O - Input/Output 48. Give full form of the abbreviation: ALU - Arithmetic Logic Unit 49. Give full form of the abbreviation: CU – Control Unit 50. Give full form of the abbreviation: PC – Personal Computer

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai – 602 105

Department of Computer Science and Engineering Unit - I Part - C

Question Bank GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING

1. Describe the characteristics of computers in detail. CHARACTERISTICS OF COMPUTER

Speed, accuracy, diligence, storage capability and versatility are some of the key characteristics of a computer.

Speed The computer can process data very fast, at the rate of millions of instructions per

second. Some calculations that would have taken hours and days to complete otherwise, can be completed in a few seconds using the computer. For example, calculation and generation of salary slips of thousands of employees of an organization, weather forecasting that requires analysis of a large amount of data related to temperature, pressure and humidity of various places, etc.

Accuracy Computer provides a high degree of accuracy. For example, the computer can

accurately give the result of division of any two numbers up to 10 decimal places. Diligence When used for a longer period of time, the computer does not get tired or

fatigued. It can perform long and complex calculations with the same speed and accuracy from the start till the end.

Storage Capability Large volumes of data and information can be stored in the computer and also retrieved whenever required. A limited amount of data can be stored, temporarily, in the primary memory. Secondary storage devices like floppy disk and compact disk can store a large amount of data permanently.

Versatility Computer is versatile in nature. It can perform different types of tasks with

the same ease. At one moment you can use the computer to prepare a letter document and in the next moment you may play music or print a document.

Computers have several limitations too. Computer can only perform tasks that it has been

programmed to do. Computer cannot do any work without instructions from the user. It executes instructions as specified by the user and does not take its own decisions.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2. Explain the basic organization of computer with suitable block diagram. (or) Draw the block diagram to illustrate the basic organization of computer system and explain the functions of the various units.

COMPONENTS OF COMPUTER HARDWARE

The computer system hardware comprises of three main components: 1. Input/Output (I/O) Unit, 2. Central Processing Unit (CPU), and 3. Memory Unit.

The I/O unit consists of the input unit and the output unit. CPU performs calculations and

processing on the input data, to generate the output. The memory unit is used to store the data, the instructions and the output information. Figure illustrates the typical interaction among the different components of the computer.

Figure The computer system interaction

Input/Output Unit The user interacts with the computer via the I/O unit. The Input unit accepts data from the user and the Output unit provides the processed data i.e. the information to the user. The Input unit converts the data that it accepts from the user, into a form that is understandable by the computer. Similarly, the Output unit provides the output in a form that is understandable by the user. The input is provided to the computer using input devices like keyboard, trackball and mouse. Some of the commonly used output devices are monitor and printer.

Central Processing Unit CPU controls, coordinates and supervises the operations of the computer. It is responsible for processing of the input data. CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).

ALU performs all the arithmetic and logic operations on the input data. CU controls the overall operations of the computer i.e. it checks the sequence of

execution of instructions, and, controls and coordinates the overall functioning of the units of computer.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Additionally, CPU also has a set of registers for temporary storage of data, instructions, addresses and intermediate results of calculation.

Memory Unit Memory unit stores the data, instructions, intermediate results and

output, temporarily, during the processing of data. This memory is also called the main memory or primary memory of the computer. The input data that is to be processed is brought into the main memory before processing. The instructions required for processing of data and any intermediate results are also stored in the main memory. The output is stored in memory before being transferred to the output device. CPU can work with the information stored in the main memory. Another kind of storage unit is also referred to as the secondary memory of the computer. The data, the programs and the output are stored permanently in the storage unit of the computer. Magnetic disks, optical disks and magnetic tapes are examples of secondary memory. 3. Write an algorithm to print the Fibonacci series:

(0, 1, 1, 2, 3, 5, 8, 13, ...)

Step 1 : Start. Step 2 : Set A = -1, B = 1, C = 0. Step 3 : Read N. Step 4 : Set I =1. Step 5 : Repeat Step 6 to 9 while I <= N. Step 6 : Set C = A + B. Step 7 : Print C. Step 8 : Set A = B. Step 9 : Set B = C. Step 10: Stop.

4. Write an algorithm to find the simple interest.

Step 1 : Start. Step 2 : Read P, N and R. Step 3 : Set SI = (P * N * R) / 100. Step 4 : Print SI. Step 5 : Stop.

5. Write an algorithm to find the sum of the digits of a given number.

Step 1 : Start. Step 2 : Set S = 0. Step 3 : Read N. Step 4 : Repeat Step 5 to 7 while n > 0. Step 5 : Set R = N % 10. Step 6 : Set S = S + R. Step 7 : Set N = N / 10. Step 8 : Print S. Step 9 : Stop.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

6. Draw the flowchart to find the surface area and volume of a sphere.

7. Draw the flowchart to solve the quadratic equation.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

8. Draw the flowchart to convert centigrade value to its equivalent Fahrenheit value.

9. Draw flowchart to find the maximum among the three numbers.

10. Explain sequence logic, selection logic and iteration logic design structure in pseudocode.

The control structures—sequence, selection, and iteration are also used while writing the pseudo code.

Figure shows the different pseudo code structures. The sequence structure is simply a sequence of steps to be executed in linear order. There are two main selection constructs—if-statement and case statement. In the if-statement, if the condition is true then the THEN part is executed otherwise the ELSE part is executed. There can be variations of the if-statement also, like there may not be any ELSE part or there may be nested ifs. The case statement is used where there are a number of conditions to be checked. In a case statement, depending on the value of the expression, one of the conditions is true, for which the corresponding statements are executed. If no match for the expression occurs, then the OTHERS option which is also the default option, is executed.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Figure Control structures for pseudo code

WHILE and DO-WHILE are the two iterative statements. The WHILE loop and the

DO-WHILE loop, both execute while the condition is true. However, in a WHILE loop the condition is checked at the start of the loop, whereas, in a DO-WHILE loop the condition is checked at the end of the loop. So the DO-WHILE loop executes at least once even if the condition is false when the loop is entered.

In Figure, the pseudo code is written for the same three tasks for which the flowchart was

shown in the previous section. The three tasks are—(i) compute the product of any two numbers, (ii) find the maximum of any three numbers, and (iii) find the sum of first 100 integers.

Figure Examples of pseudo code

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

A pseudo code is easily translated into a programming language. But, as there are no defined standards for writing a pseudo code, programmers may use their own style for writing the pseudo code, which can be easily understood. Generally, programmers prefer to write pseudo code instead of flowcharts.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

CHAPTER 1 - THE WAY OF THE PROGRAM 1.1 THE PYTHON PROGRAMMING LANGUAGE

The programming language you will learn is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java.

There are also low-level languages, sometimes referred to as “machine languages” or “assembly languages.” Loosely speaking, computers can only run programs written in low-level languages. So programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages.

The advantages are enormous. First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another.

Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications.

Two kinds of programs process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. Figure 1-1 shows the structure of an interpreter.

Figure 1-1. An interpreter processes the program a little at a time, alternately reading lines and performing computations.

A compiler reads the program and translates it completely before the program starts

running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. Figure 1-2 shows the structure of a compiler.

Figure 1-2. A compiler translates source code into object code, which is run by a hardware executor.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Python is considered an interpreted language because Python programs are executed by an interpreter. There are two ways to use the interpreter: interactive mode and script mode. In interactive mode, you type Python programs and the interpreter displays the result:

>>> 1 + 1 2

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you

type 1 + 1, the interpreter replies 2.

Alternatively, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. By convention, Python scripts have names that end with .py.

To execute the script, you have to tell the interpreter the name of the file. If you have a script named dinsdale.py and you are working in a UNIX command window, you type python dinsdale.py. In other development environments, the details of executing scripts are different.

Working in interactive mode is convenient for testing small pieces of code because you can type and execute them immediately. But for anything more than a few lines, you should save your code as a script so you can modify and execute it in the future. 1.2 WHAT IS A PROGRAM?

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing an image or playing a video.

The details look different in different languages, but a few basic instructions appear in just

about every language: input:

Get data from the keyboard, a file, the network, or some other device. output:

Display data on the screen, save it in a file, send it over the network, etc. math:

Perform basic mathematical operations like addition and multiplication. conditional execution:

Check for certain conditions and run the appropriate code. repetition:

Perform some action repeatedly, usually with some variation. Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no

matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

1.3 WHAT IS DEBUGGING?

Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. 1.3.1 Syntax Errors

Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an error message. Syntax refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error. 1.3.2 Runtime Errors

The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. 1.3.3 Semantic Errors

The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. 1.4 ABOUT PYTHON

Python was created by Guido van Rossum. The idea of Python was conceived in December 1989. The name Python comes from the 70s comedy series “Monty Python’s Flying Circus” and has nothing to do with the reptilian. 1.5 FEATURES OF PYTHON

Python is a very simple language surrounded by large library of add-on functions (modules). It is a platform-independent, scripted and dynamic language, that allows more run-time flexibility that statically compiled languages.

Simple and easy to learn: Python is a simple programming language with few keywords,

simple structure, and a clearly defined syntax.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Portable: Python is an open source software. It can run on a wide variety of platforms (hardware and software) and has the same interface on all platforms such as Window, Linux and Macintosh.

Interactive Mode: Python has support for an interactive mode which allows interactive

testing and debugging of snippets of code. Broad standard library: Python's library is a portable and cross-platform compatible on

UNIX, Windows, and Macintosh. This helps in the support and development of wide range applications from simple text processing to browsers and complex games.

Extendable: Python is highly extendable, we can add low-level modules (functions) to the

Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.

Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to

many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.

Scalable: Python provides a better structure and support for large programs than shell

scripting. 1.6 RUNNING PYTHON

There are two versions of Python, called Python 2 and Python 3. They are very similar, so if you learn one, it is easy to switch to the other. In fact, there are only a few differences you will encounter as a beginner.

The Python interpreter is a program that reads and executes Python code. Depending on your environment, you might start the interpreter by clicking on an icon, or by typing python on a command line. When it starts, you should see output like this:

Python 3.4.0 (default, Jun 19 2015, 14:20:21) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> The first three lines contain information about the interpreter and the operating system it’s

running on, so it might be different for you. But you should check that the version number, which is 3.4.0 in this example, begins with 3, which indicates that you are running Python 3. If it begins with 2, you are running (you guessed it) Python 2.

The last line is a prompt that indicates that the interpreter is ready for you to enter code. If

you type a line of code and hit Enter, the interpreter displays the result: >>> 1 + 1 2

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Now you’re ready to get started. From here on, I assume that you know how to start the Python interpreter and run code. 1.7 THE FIRST PROGRAM

Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words “Hello, World!” In Python, it looks like this:

>>> print('Hello, World!')

This is an example of a print statement, although it doesn’t actually print anything on

paper. It displays a result on the screen. In this case, the result is the words

Hello, World!

The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.

The parentheses indicate that print is a function.

In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use parentheses.

>>> print 'Hello, World!'

1.8 ARITHMETIC OPERATORS

After “Hello, World”, the next step is arithmetic. Python provides operators, which are special symbols that represent computations like addition and multiplication.

The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:

>>> 40 + 2 42 >>> 43 - 1 42 >>> 6 * 7 42

The operator / performs division: >>> 84 / 2 42.0

You might wonder why the result is 42.0 instead of 42.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Finally, the operator ** performs exponentiation; that is, it raises a number to a power:

>>> 6**2 + 6 42

In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator

called XOR. If you are not familiar with bitwise operators, the result will surprise you: >>> 6 ^ 2 4

Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example + Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand.

a - b = -10 b - a = 10

* Multiplication Multiplies values on either side of the operator. a * b = 200

/ Division Divides left hand operand by right hand operand. a / b = 0.5 b / a = 2.0

% Modulus Divides left hand operand by right hand operand and returns remainder.

a % b = 10 b % a = 0

** Exponent Performs exponential (power) calculation on operators.

a**2 =100 b ** 3 = 8000

//

Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity).

a // b = 0 b // a = 2

1.9 VALUES AND TYPES

A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2, 42.0, and 'Hello, World!'

These values belong to different types: 2 is an integer, 42.0 is a floating-point number, and 'Hello, World!' is a string, so-called because the letters it contains are strung together.

If you are not sure what type a value has, the interpreter can tell you: >>> type(2) <class 'int'> >>> type(42.0) <class 'float'> >>> type('Hello, World!') <class 'str'>

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

In these results, the word “class” is used in the sense of a category; a type is a category of values.

Not surprisingly, integers belong to the type int, strings belong to str, and floating-point numbers belong to float.

What about values like '2' and '42.0'? They look like numbers, but they are in quotation marks like strings:

>>> type('2') <class 'str'> >>> type('42.0') <class 'str'>

They’re strings.

When you type a large integer, you might be tempted to use commas between groups of

digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

>>> 1,000,000 (1, 0, 0)

That’s not what we expected at all! Python interprets 1,000,000 as a comma-separated

sequence of integers.

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

REVIEW QUESTIONS 1. List some of the features of Python. 2. Is Python a case sensitive language? 3. How can you run Python? 4. Explain the purpose of ** operator with suitable examples. 5. List out the advantages of Python. 6. List out the disadvantages of Python.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

CHAPTER 2 - VARIABLES, EXPRESSIONS AND STATEMENTS

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. 2.1 ASSIGNMENT STATEMENTS

An assignment statement creates a new variable and gives it a value: >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.141592653589793

This example makes three assignments. The first assigns a string to a new variable

named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.

A common way to represent variables on paper is to write the name with an arrow pointing to its value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable’s state of mind). Figure 2-1 shows the result of the previous example.

Figure 2-1. State diagram. 2.2 VARIABLE NAMES

A variable is basically a name that represents (or refers to) some value. Variable are reserved memory locations to store values.

Programmers generally choose names for their variables that are meaningful - they

document what the variable is used for.

Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lowercase for variables names.

The underscore character, _, can appear in a name. It is often used in names with multiple words, such as your_name or airspeed_of_unladen_swallow.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade' SyntaxError: invalid syntax

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax

76trombones is illegal because it begins with a number. more@ is illegal because it

contains an illegal character, @. But what’s wrong with class?

It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. 2.3 KEYWORDS

Keywords are the reserved words in Python. We cannot use keywords as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive.

Python 3 has these keywords:

False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise

You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know. 2.4 EXPRESSIONS AND STATEMENTS

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:

>>> 42 42 >>> n 17 >>> n + 25 42

When you type an expression at the prompt, the interpreter evaluates it, which means

that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

A statement is a unit of code that has an effect, like creating a variable or displaying a value.

>>> n = 17 >>> print(n)

The first line is an assignment statement that gives a value to n. The second line is a print

statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does

whatever the statement says. In general, statements don’t have values. 2.5 SCRIPT MODE

So far we have run Python in interactive mode, which means that you interact directly with the interpreter. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy.

The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py.

Because Python provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing.

For example, if you are using Python as a calculator, you might type: >>> miles = 26.2 >>> miles * 1.61 42.182

The first line assigns a value to miles, but it has no visible effect. The second line is an

expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42 kilometers.

But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn’t display the value unless you tell it to:

miles = 26.2 print(miles * 1.61)

This behavior can be confusing at first.

A script usually contains a sequence of statements. If there is more than one statement,

the results appear one at a time as the statements execute.

For example, the script

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

print(1) x = 2 print(x)

produces the output

1 2

The assignment statement produces no output.

To check your understanding, type the following statements in the Python interpreter and

see what they do: 5 x = 5 x + 1

Now put the same statements in a script and run it. What is the output? Modify the script

by transforming each expression into a print statement and then run it again. 2.6 ORDER OF OPERATIONS

When an expression contains more than one operator, the order of evaluation depends on the order of operations.

Operator

Description

** Exponentiation (raise to the power) ~ + -

Complement, unary plus and minus

* / % //

Multiply, divide, modulo and floor division

+ -

Addition and subtraction

>> <<

Right and left bitwise shift

& Bitwise 'AND' ^ | Bitwise exclusive `OR' and regular `OR'

<= < >

>=

Comparison operators

== !=

Equality operators

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

= %= /= //= -= += *=

**=

Assignment operators

is is not

Identity operators

in not in

Membership operators

not or

and Logical operators

For mathematical operators, Python follows mathematical convention. The

acronym PEMDAS is a useful way to remember the rules: Parentheses have the highest precedence and can be used to force an expression to

evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is 18, not 36.

Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by , you can use parentheses or write degrees / 2 / pi.

2.7 STRING OPERATIONS

In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

'2'-'1' 'eggs'/'easy' 'third'*'a charm'

But there are two exceptions, + and *.

The + operator performs string concatenation, which means it joins the strings by linking

them end-to-end. For example:

>>> first = 'throat' >>> second = 'warbler' >>> first + second throatwarbler

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the values is a string, the other has to be an integer.

This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Spam'*3 to be the same as 'Spam'+'Spam'+'Spam', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. 2.8 COMMENTS

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the #symbol:

# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end

of a line: percentage = (minute * 100) / 60 # percentage of an hour

Everything from the # to the end of the line is ignored—it has no effect on the execution of

the program.

Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why.

This comment is redundant with the code and useless: v = 5 # assign 5 to v

This comment contains useful information that is not in the code: v = 5 # velocity in meters/second.

Good variable names can reduce the need for comments, but long names can make

complex expressions hard to read, so there is a trade-off.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

REVIEW QUESTIONS 1. Give the rules for naming an identifier in Python. 2. How can you give comments in Python? 3. What are multi-line statements? 4. List out the operator precedence in Python. 5. Explain the operator precedence with suitable example. 6. Differentiate interactive and script mode.

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python to add the two integers 10 and 20. 2. Develop a Python program to find the type of various values. 3. Develop a Pyton program to swap two numbers (using three variables). 4. Develop a Python program to swap two numbers (using two variables). 5. Develop a Python Program to read numerator and denominator and print their quotient and

remainder. 6. Develop a Python program to compute the simple interest. 7. Develop a Python program to find the area and circumference of a circle. 8. Develop a Python program to convert the °C to °F. 9. Develop a Python program to convert the °F to °C.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

CHAPTER 3 - CONDITIONALS

The main topic of this chapter is the if statement, which executes different code depending on the state of the program. 3.1 FLOOR DIVISION AND MODULUS

The floor division operator, //, divides two numbers and rounds down to an integer. For

example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:

>>> minutes = 105 >>> minutes / 60 1.75

But we don’t normally write hours with decimal points. Floor division returns the integer

number of hours, dropping the fraction part: >>> minutes = 105 >>> hours = minutes // 60 >>> hours 1

To get the remainder, you could subtract off one hour in minutes: >>> remainder = minutes - hours * 60 >>> remainder 45

An alternative is to use the modulus operator, %, which divides two numbers and returns

the remainder: >>> remainder = minutes % 60 >>> remainder 45

The modulus operator is more useful than it seems. For example, you can check whether

one number is divisible by another—if x % y is zero, then x is divisible by y.

Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

If you are using Python 2, division works differently. The division operator, /, performs floor division if both operands are integers, and floating-point division if either operand is a float.

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

3.2 BOOLEAN EXPRESSIONS

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

>>> 5 == 5 True >>> 5 == 6 False

True and False are special values that belong to the type bool; they are not strings: >>> type(True) <class 'bool'> >>> type(False) <class 'bool'>

The == operator is one of the relational operators; the others are: x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y

Assume variable a holds 10 and variable b holds 20.

Operator Description Example

== If the values of two operands are equal, then the condition becomes True. (a == b) is not True

!= If values of two operands are not equal, then condition becomes True. (a != b) is True

> If the value of left operand is greater than the value of right operand, then condition becomes True.

(a > b) is not True

< If the value of left operand is less than the value of right operand, then condition becomes True.

(a < b) is True

>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes True.

(a >= b) is not True

<= If the value of left operand is less than or equal to the value of right operand, then condition becomes True.

(a <= b) is True

Although these operations are probably familiar to you, the Python symbols are different

from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a relational operator. There is no such thing as =< or =>.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

3.3 LOGICAL OPERATORS

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.

n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y.

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True:

>>> 42 and True True This flexibility can be useful, but there are some subtleties to it that might be confusing.

You might want to avoid it (unless you know what you are doing).

Assume variable a holds 10 and variable b holds 20.

Operator Description Example

and Logical AND

If both the operands are True then condition becomes True. If any one of the operand is False, then the condition becomes False.

(a and b) is True

or Logical OR

If any of the two operands are non-zero then condition becomes True. If both the operands are False, then the condition becomes False.

(a or b) is True

not Logical NOT

It returns False when the condition is True and vice versa. Used to reverse the logical state of its operand.

Not(a and b) is False

3.4 CONDITIONAL EXECUTION (if STATEMENT)

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. Syntax

if(test-expression): statement-block(s)

statement-x

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Flowchart

The simplest form is the if statement: if x > 0: print('x is positive')

The boolean expression after if is called the condition. If it is true, the indented statement

runs. If not, nothing happens.

if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements. 3.5 ALTERNATIVE EXECUTION (if...else STATEMENT)

A second form of the if statement is “alternative execution”, in which there are two possibilities and the condition determines which one runs. Syntax

The syntax looks like this: if(test-expression):

true-block-statement(s) else:

false-block-statement(s) statement-x

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

Flowchart

For example: if x % 2 == 0: print('x is even') else: print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program

displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution. 3.6 CHAINED CONDITIONALS (if...elif...else STATEMENT)

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional. Syntax

if(test-condition-1):

statement-1 elif(test-condition-2):

statement-2 . . . . . . . . . elif(test-condition-n):

statement-n else: default-statement statement-x

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Flowchart

For example: if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on

the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a': draw_a() elif choice == 'b': draw_b() elif choice == 'c': draw_c()

Each condition is checked in order. If the first is false, the next is checked, and so on. If one

of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs. 3.7 NESTED CONDITIONALS (Nested if...else STATEMENT)

One conditional can also be nested within another.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

Syntax if(test-condition-1): if(test-condition-2): statement-1 else: statement-2 else: statement-3 statement-x

Flowchart

We could have written the example in the previous section like this: if x == y: print('x and y are equal') else: if x < y: print('x is less than y') else: print('x is greater than y')

The outer conditional contains two branches. The first branch contains a simple statement.

The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x: if x < 10: print('x is a positive single-digit number.') The print statement runs only if we make it past both conditionals, so we can get the same

effect with the and operator:

if 0 < x and x < 10: print('x is a positive single-digit number.')

For this kind of condition, Python provides a more concise option: if 0 < x < 10: print('x is a positive single-digit number.')

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

REVIEW QUESTIONS 1. What is the purpose of // operator? 2. List out the controls for decision making statements. 3. Write the syntax and draw the flow chart for if statement in Python. 4. Write the syntax and draw the flow chart for if...else statement in Python. 5. Write the syntax and draw the flow chart for if...elif...else statement in Python. 6. Write the syntax and draw the flow chart for Nested if...else statement in Python. 7. Explain with syntax and example for if statement in Python. 8. Explain Nested if...elif...else statements with example. 9. Write a program to check if the number is positive or negative or zero. 10. Explain various decision making statements in Python. 11. Write a program to find whether the given number is an odd or even number. 12. Explain control statements with suitable examples.

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to demonstrate sequence execution (average of three numbers). 2. Develop a Python program to find the cutoff marks in an engineering admission using if

statement. 3. Develop a Python program to find whether the given number is even or odd using if statement. 4. Develop a Python program to find whether the given number is positive or negative using if

statement. 5. Develop a Python program to check whether the person is eligible to vote or not using if

statement. 6. Develop a Python program to check whether the person is in teen age or not using if

statement. 7. Develop a Python program to find whether the given number is positive or negative using

if...else statement. 8. Develop a Python program to find whether the given number is even or odd using if...else

statement. 9. Develop a Python program to check whether the person is eligible to vote or not using if...else

statement. 10. Develop a Python program to check whether the person is in teen age or not using if...else

statement. 11. Develop Python program to input the mark and print grade. Grades are awarded according to

the following criteria: 91 to 100 S Grade 81 to 90 A Grade 71 to 80 B Grade 61 to 70 C Grade 57 to 60 D Grade 50 to 56 E Grade <50 U Grade

12. Develop a Python program to check whether the given year is leap year or not using if...elif...else statement.

13. Develop a Python program to calculate electricity bill for domestic consumers as follows: Units Charges (Rs. / Unit)

Upto 100 3.00 101 – 200 3.25 201 – 500 Rs.700 + 4.60 per unit excess of 200

501 and above Rs.2080 + 6.60 per unit excess of 500 14. Develop a Python program to compute the roots of a quadratic equation. 15. Develop a Python program to check if the number is positive or negative or zero using nested

if..else statement. 16. Develop a Python program to find the biggest of 3 numbers using nested if...else statement. 17. Develop a Python program to check whether the given year is leap year or not using nested

if...else statement.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

CHAPTER 4 - ITERATION

This chapter is about iteration, which is the ability to run a block of statements repeatedly. 4.1 REASSIGNMENT

As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).

>>> x = 5 >>> x 5 >>> x = 7 >>> x 7

The first time we display x, its value is 5; the second time, its value is 7.

Figure 4-1 shows what reassignment looks like in a state diagram.

Figure 7-1. State diagram.

Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a mathematical proposition of equality; that is, the claim that a and b are equal. But this interpretation is wrong.

First, equality is a symmetric relationship and assignment is not. For example, in mathematics, if a=7 then 7=a. But in Python, the statement a = 7 is legal and 7 = a is not.

Also, in mathematics, a proposition of equality is either true or false for all time. If a=b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don’t have to stay that way:

>>> a = 5 >>> b = a # a and b are now equal >>> a = 3 # a and b are no longer equal >>> b 5

The third line changes the value of a but does not change the value of b, so they are no

longer equal.

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Reassigning variables is often useful, but you should use it with caution. If the values of variables change frequently, it can make the code difficult to read and debug. 4.2 UPDATING VARIABLES

A common kind of reassignment is an update, where the new value of the variable depends on the old.

>>> x = x + 1

This means “get the current value of x, add one, and then update x with the new value.”

If you try to update a variable that doesn’t exist, you get an error, because Python

evaluates the right side before it assigns a value to x: >>> x = x + 1 NameError: name 'x' is not defined

Before you can update a variable, you have to initialize it, usually with a simple

assignment: >>> x = 0 >>> x = x + 1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

4.3 THE while STATEMENT

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration. Syntax

while(test-condition):

body of the loop; statement-x;

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 31

Flowchart

Here is a version of countdown that uses a while statement:

while n > 0: print(n) n = n - 1 print('Blastoff!')

You can almost read the while statement as if it were English. It means, “While n is greater

than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!”

More formally, here is the flow of execution for a while statement: 1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the

condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

In the case of countdown, we can prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.

32 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

For some other loops, it is not so easy to tell. For example: while n != 1: print(n) if n % 2 == 0: # n is even n = n / 2 else: # n is odd n = n*3 + 1 The condition for this loop is n != 1, so the loop will continue until n is 1, which makes the

condition false.

Each time through the loop, the program outputs the value of n and then checks whether it is even or odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3 + 1. For example, if the argument passed to n is 3, the resulting values of n are 3, 10, 5, 16, 8, 4, 2, 1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or that the program terminates. For some particular values of n, we can prove termination. For example, if the starting value is a power of two, n will be even every time through the loop until it reaches 1. The previous example ends with such a sequence, starting with 16. 4.4 THE for STATEMENT

A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top.

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks

without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.

The syntax of a for statement has a header that ends with a colon and an indented body. The body can contain any number of statements. Syntax

for variable in sequence:

body of the loop; statement-x;

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 33

Flowchart

For example: for i in range(4): print('Hello!')

You should see something like this: Hello! Hello! Hello! Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

4.5 break STATEMENT

Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case you can use the break statement to jump out of the loop. break is used to break out of the innermost loop.

For example, suppose you want to take input from the user until they type done. You could write:

while True: line = input('> ') if line == 'done': break print(line) print('Done!')

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The loop condition is True, which is always true, so the loop runs until it hits the break statement.

Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here’s a sample run:

> not done not done > done Done!

This way of writing while loops is common because you can check the condition anywhere

in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens”).

The while loop to print the squares of all the odd numbers below 10, can be modified using

the break statement, as follows i = 1 while True: print (i * i) i = i + 2 if(i > 10): break

produces the output

1 9 25 49 81

4.6 continue STATEMENT

continue is used to skip execution of the rest of the loop on this iteration and continue to the end of this iteration.

For example we wish to print the squares of all the odd numbers below 10, which are not

multiples of 3, we would modify the for loop as follows. for n in range(1, 10, 2): if n % 3 == 0: continue print (n * n) produces the output

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 35

1 25 49

4.7 pass STATEMENT

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

if x < 0: pass # TODO: need to handle negative values!

“pass” statement acts as a place holder for the block of code. It is equivalent to a null operation. It literally does nothing. It can used as a place holder when the actual code implementation for a particular block of code is not known yet but has to be filled up later.

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

REVIEW QUESTIONS 1. Define loops in Python. 2. Explain the types of looping constructs. 3. Explain for loop with else case with an example. 4. Explain looping through a sequence of numbers. 5. Write the syntax and draw the flow chart for while statement in Python. 6. Explain while loop with suitable examples. 7. Differentiate while loop and while loop with else case with examples. 8. Write a program to find the sum of first N natural numbers using while loop. 9. Write the syntax and draw the flow chart for for statement in Python. 10. Explain nested loops with syntax and example. 11. What is the purpose of break statement? 12. What is the purpose of continue statement? 13. What is the purpose of pass statement in Python? 14. Differentiate break and continue statements. 15. Explain infinite loop with an example. 16. Write a program to generate Fibonacci series of N terms. 17. Write a program to concatenate all elements in a list into a string and return it.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 37

PROGRAMMING EXERCISES 1. Develop a Python program to find the sum of numbers up to 10 using while statement. 2. Develop a Python program to count the number of digits in an integer using while statement. 3. Develop a Python program to find the sum of digits in an integer using while statement. 4. Develop a Python program to reverse the digits of a given number using while statement. 5. Develop a Python program to check whether the number and its reverse are same or not using

while statement. 6. Develop a Python program to find the largest digit of a number using while statement. 7. Develop a Python program to find sum of digits, reversal of digits and largest of digit using

while statement. 8. Develop a Python program to check whether the given number is Armstrong number or not

using while statement. 9. Develop a Python program to find the value of xn using while statement. 10. Develop a Python program to find the factorial of a given number using while statement. 11. Develop a Python program to find the sum of numbers up to 10 using for statement. 12. Develop a Python program to find the factorial of a given number using for statement. 13. Develop a Python program to print addition table of the given number using for statement. 14. Develop a Python program to print multiplication table of the given number using for

statement. 15. Develop a Python program to find the average of first n natural numbers without using the

formula using for statement. 16. Develop a Python program to print the numbers that are divisible by a given number using for

statement. 17. Develop a Python program to print all the divisors of a given number using for statement. 18. Develop a Python program to generate odd and even numbers using for statement. 19. Develop a Python program to find the sum of odd and even numbers using for statement. 20. Develop a Python program to print first ‘n’ terms of the Fibonacci series using for statement. 21. Develop a Python program to the sum of Fibonacci series using for statement. 22. Develop a Python program to find the given number is perfect number or not using for

statement. 23. Develop a Python program to generate numbers between 20 and 100 which are divisible by 2

and not divisible by 3 and 5 using for statement. 24. Develop a Python program to find the sum of the series 1 + x2/2 + x3/3 + ... xn/n using for

statement. 25. Develop a Python program to find the sum of the series 1 + 1/2 + 1/3 + ... 1/n using for

statement. 26. Develop a Python program to generate the Armstrong numbers from 1 – 1000. 27. Develop a Python program to check whether a given number is a prime number or not and

print the result using for statement. 28. Develop a Python program to print 10 x 10 multiplication table using nested for statement. 29. Develop a Python program to generate Floyd's triangle using nested for statement. 30. Develop a Python program to the first ‘N’ prime numbers using nested for statement.

38 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Develop a Python to add the two integers 10 and 20. Program: firstno = 10 secondno = 20 result = firstno + secondno print("Result =", result) Output: Result = 30

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the type of various values. Program: a = 10 b = 3.14 c = "REC" d = True print("Type of a is", type(a)) print("Type of b is", type(b)) print("Type of c is", type(c)) print("Type of d is", type(d)) Output: Type of a is <class 'int'> Type of b is <class 'float'> Type of c is <class 'str'> Type of d is <class 'bool'>

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Develop a Pyton program to swap two numbers (using three variables). Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print("Before swapping :") print("a =", a, "b =",b) c = a a = b b = c print("After swapping :") print("a =", a, "b =",b) Output: Enter the first number : 10 Enter the second number : 20 Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to swap two numbers (using two variables). Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print("Before swapping :") print("a =", a, "b =",b) a = a + b b = a - b a = a - b print("After swapping :") print("a =", a, "b =",b) Output: Enter the first number : 10 Enter the second number : 20 Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Develop a Python Program to read numerator and denominator and print their quotient and remainder. Program: n = int(input("Enter the numerator : ")) d = int(input("Enter the denominator : ")) q = n // d r = n % d print("Quotient =", q, "Remainder =", r) Output: Enter the numerator : 10 Enter the denominator : 3 Quotient = 3 Remainder = 1

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to compute the simple interest. Program: p = int(input("Enter the principle amount : ")) n = int(input("Enter the number of years : ")) r = float(input("Enter the rate of interest : ")) si = (p * n * r) / 100 print("Simple interest =", si) Output: Enter the principle amount : 10000 Enter the number of years : 5 Enter the rate of interest : 12.00 Simple interest = 6000.0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Develop a Python program to find the area and circumference of a circle. Program: r = float(input("Enter the radius : ")) area = 3.14 * r * r circum = 2 * 3.14 * r print("Area = :", area) print("Circumference = :", circum) Output: Enter the radius : 3 Area = : 28.259999999999998 Circumference = : 18.84

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to convert the °C to °F. Program: c = float(input("Enter the centigrade : ")) f = (1.8 * c + 32) print("The fahrenheit is =", f) Output: Enter the centigrade : 45 The fahrenheit is = 113.0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

Develop a Python program to convert the °F to °C. Program: f = float(input("Enter the fahrenheit : ")) c = (f - 32) / 1.8 print("The centigrade is =", c) Output: Enter the fahrenheit : 113 The centigrade is = 45.0

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to demonstrate sequence execution (average of three numbers). Program: num1 = float(input("Enter the first number : ")) num2 = float(input("Enter the first number : ")) num3 = float(input("Enter the first number : ")) avg = (num1 + num2 + num3) / 3 print("Average =", avg) Output: Enter the first number : 10 Enter the first number : 20 Enter the first number : 30 Average = 20.0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

Develop a Python program to find the cutoff marks in an engineering admission using if statement. Program: cutoff = float(input("Enter cutoff mark : ")) quota = int(input("Enter the quota 1-General 2-Sports : ")) if (quota == 2): cutoff = cutoff + 5 print("Cutoff mark =", cutoff) Output: Enter cutoff mark : 170 Enter the quota 1-General 2-Sports : 1 Cutoff mark = 170.0 Enter cutoff mark : 160 Enter the quota 1-General 2-Sports : 2 Cutoff mark = 165.0

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find whether the given number is even or odd using if statement. Program: num = int(input("Enter the number : ")) if (num % 2 == 0): print("The given number is even") if (num % 2 != 0): print("The given number is odd") Output: Enter the number : 10 The given number is even Enter the number : 5 The given number is odd

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

Develop a Python program to find whether the given number is positive or negative using if statement. Program: num = int(input("Enter the number : ")) if (num > 0): print("The given number is positive") if (num < 0): print("The given number is negative") Output: Enter the number : 2 The given number is positive Enter the number : -14 The given number is negative

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to check whether the person is eligible to vote or not using if statement. Program: num = int(input("Enter the number : ")) if (num > 0): print("The given number is positive") if (num < 0): print("The given number is negative") Output: Enter the age : 20 The person is eligible to vote Enter the age : 16 The person is not eligible to vote

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

Develop a Python program to check whether the person is in teen age or not using if statement. Program: age = int(input("Enter the age : ")) if (age >= 13 and age <= 19): print("The person is in teen age") if (age <= 12 or age >= 20): print("The person is not in teen age") Output: Enter the age : 16 The person is in teen age Enter the age : 21 The person is not in teen age

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find whether the given number is positive or negative using if...else statement. Program: num = int(input("Enter the number : ")) if (num > 0): print("The given number is positive") else: print("The given number is negative") Output: Enter the number : 2 The given number is positive Enter the number : -14 The given number is negative

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

Develop a Python program to find whether the given number is even or odd using if...else statement. Program: num = int(input("Enter the number : ")) if (num % 2 == 0): print("The given number is even") else: print("The given number is odd") Output: Enter the number : 10 The given number is even Enter the number : 5 The given number is odd

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to check whether the person is eligible to vote or not using if...else statement. Program: age = int(input("Enter the age : ")) if (age >= 18): print("The person is eligible to vote") else: print("The person is not eligible to vote") Output: Enter the age : 20 The person is eligible to vote Enter the age : 16 The person is not eligible to vote

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

Develop a Python program to check whether the person is in teen age or not using if...else statement. Program: age = int(input("Enter the age : ")) if (age >= 13 and age <= 19): print("The person is in teen age") else: print("The person is not in teen age") Output: Enter the age : 16 The person is in teen age Enter the age : 21 The person is not in teen age

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop Python program to input the mark and print grade. Grades are awarded according to the following criteria:

91 to 100 S Grade 81 to 90 A Grade 71 to 80 B Grade 61 to 70 C Grade 57 to 60 D Grade 50 to 56 E Grade <50 U Grade

Program: mark = int(input("Enter the mark : ")) if(mark >= 91): print("S Grade") elif(mark >= 81): print("A Grade") elif(mark >= 71): print("B Grade") elif(mark >= 61): print("C Grade") elif(mark >= 57): print("D Grade") elif(mark >= 50): print("E Grade") else: print("U Grade") Output Enter the mark : 85 A Grade Enter the mark : 45 U Grade

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

Develop a Python program to check whether the given year is leap year or not using if...elif...else statement. Program: year = int(input("Enter the year : ")) if(year % 400 == 0): print(year, "is a leap year") elif(year % 4 == 0 and year % 100 != 0): print(year, "is a leap year") else: print(year, "is not a leap year") Output: Enter the year : 2012 2012 is a leap year Enter the year : 2013 2013 is not a leap year

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to calculate electricity bill for domestic consumers as follows:

Units Charges (Rs. / Unit) Upto 100 3.00 101 – 200 3.25 201 – 500 Rs.700 + 4.60 per unit excess of 200

501 and above Rs.2080 + 6.60 per unit excess of 500 Program: units = int(input("Enter the units consumed : ")) if(units <= 100): amount = 3.00 * units elif(units <= 200): amount = 3.25 * units elif(units <= 500): amount = 700.00 + 4.60 * (units - 200) else: amount = 2080.00 + 6.60 * (units - 500) print("Units =", units, "Amount =", amount) Output: Enter the units consumed : 77 Units = 77 Amount = 231.0 Enter the units consumed : 140 Units = 140 Amount = 455.0 Enter the units consumed : 280 Units = 280 Amount = 1068.0 Enter the units consumed : 560 Units = 560 Amount = 2476.0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

Develop a Python program to compute the roots of a quadratic equation. Program: a = float(input("Enter the value for a : ")) b = float(input("Enter the value for b : ")) c = float(input("Enter the value for c : ")) d = (b ** 2) - (4 * a * c) if(d < 0): print("Roots are imaginary") real = - b / (2 * a) d = -d imag = (d ** 0.5) / (2 * a) print("root 1 =", real, "+ j", imag) print("root 2 =", real, "- j", imag) elif(d == 0): print("Roots are real and equal") r = - b / (2 * a) print("root =", r) elif(d > 0): print("Roots are real and unequal") r1 = (- b + (d ** 0.5)) / (2 * a) r2 = (- b - (d ** 0.5)) / (2 * a) print("root 1 =", r1) print("root 2 =", r2) Output: Enter the value for a : 1 Enter the value for b : 2 Enter the value for c : 7 Roots are imaginary root 1 = -1.0 + j 2.449489742783178 root 2 = -1.0 - j 2.449489742783178 Enter the value for a : 1 Enter the value for b : 2 Enter the value for c : 1 Roots are real and equal root = -1.0 Enter the value for a : 2 Enter the value for b : 7 Enter the value for c : 1 Roots are real and unequal root 1 = -0.14921894064178787 root 2 = -3.350781059358212

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to check if the number is positive or negative or zero using nested if..else statement. Program: num = int(input("Enter the number : ")) if(num == 0): print('The number is zero') else: if(num > 0): print('The number is positive') else: print('The number is negative') Output: Enter the number : 2 The number is positive Enter the number : -14 The number is negative Enter the number : 0 The number is zero

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

Develop a Python program to find the biggest of 3 numbers using nested if...else statement. Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) c = int(input("Enter the third number : ")) if(a > b): if(a > c): print(a, "is the biggest number") else: print(c, "is the biggest number") else: if(b > c): print(b, "is the biggest number") else: print(c, "is the biggest number") Output: Enter the first number : 10 Enter the second number : 20 Enter the third number : 30 30 is the biggest number Enter the first number : 20 Enter the second number : 30 Enter the third number : 10 30 is the biggest number Enter the first number : 30 Enter the second number : 10 Enter the third number : 20 30 is the biggest number

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to check whether the given year is leap year or not using nested if...else statement. Program: year = int(input("Enter the year: ")) if(year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): print(year, "is a leap year") else: print(year, "is not a leap year") else: print(year, "is a leap year") else: print(year, "is not a leap year") Output: Enter the year: 2012 2012 is a leap year Enter the year: 2013 2013 is not a leap year

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

Develop a Python program to find the sum of numbers up to 10 using while statement. Program: s = 0 i = 1 while(i <= 10): s = s + i i = i + 1 print("The sum =", s) Output: The sum = 55

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to count the number of digits in an integer using while statement. Program: n = int(input("Enter the number : ")) count = 0 while(n > 0): count = count + 1 n = n // 10 print("The number of digits =", count) Output: Enter the number : 179 The number of digits = 3

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 31

Develop a Python program to find the sum of digits in an integer using while statement. Program: n = int(input("Enter the number : ")) s = 0 while(n > 0): rem = n % 10 s = s + rem n = n // 10 print("The sum of the digits =", s) Output: Enter the number : 786 The sum of the digits = 21

32 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to reverse the digits of a given number using while statement. Program: n = int(input("Enter the number : ")) rev = 0 while(n > 0): rem = n % 10 rev = rem + (rev * 10) n = n // 10 print("The reversed number =", rev) Output: Enter the number : 2468 The reversed number = 8642

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 33

Develop a Python program to check whether the number and its reverse are same or not using while statement. Program: n = int(input("Enter the number : ")) temp = n rev = 0 while(n > 0): rem = n % 10 rev = rem + (rev * 10) n = n // 10 if(temp == rev): print("The number and its reverse are same") else: print("The number and its reverse are not same") Output: Enter the number : 143 The number and its reverse are not same Enter the number : 141 The number and its reverse are same

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the largest digit of a number using while statement. Program: n = int(input("Enter the number : ")) large = 0 while(n > 0): rem = n % 10 if(rem > large): large = rem n = n // 10 print("The largest digit =", large) Output: Enter the number : 786 The largest digit = 8

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 35

Develop a Python program to find sum of digits, reversal of digits and largest of digit using while statement. Program: n = int(input("Enter the number : ")) s = 0 rev = 0 large = 0 while(n > 0): rem = n % 10 s = s + rem rev = rem + (rev * 10) if(rem > large): large = rem n = n // 10 print("The sum of the digits =", s) print("The reverse of the digits =", rev) print("The largest digit =", large) Output: Enter the number : 786 The sum of the digits = 21 The reverse of the digits = 687 The largest digit = 8

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to check whether the given number is Armstrong number or not using while statement. Program: n = int(input("Enter the number : ")) temp = n s = 0 while(n > 0): rem = n % 10 s = s + (rem ** 3) n = n // 10 if(s == temp): print(temp, "is an Armstrong number") else: print(temp, "is not an Armstrong number") Output: Enter the number : 153 153 is an Armstrong number Enter the number : 123 123 is not an Armstrong number

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 37

Develop a Python program to find the value of xn using while statement. Program: x = int(input("Enter the value of x : ")) n = int(input("Enter the value of n : ")) i = 1 s = 1 while(i <= n): s = s * x i = i + 1 print("The power of", x, "^", n, "=", s) Output: Enter the value of x : 2 Enter the value of n : 4 The power of 2 ^ 4 = 16 Enter the value of x : 2 Enter the value of n : 0 The power of 2 ^ 0 = 1

38 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the factorial of a given number using while statement. Program: n = int(input("Enter the number : ")) fact = 1 i = 1 while(i <= n): fact = fact * i i = i + 1 print("The factorial of", n, "is", fact) Output: Enter the number : 5 The factorial of 5 is 120

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 39

Develop a Python program to find the sum of numbers up to 10 using for statement. Program: s = 0 for i in range(1, 11): s = s + i print("The sum =", s) Output: The sum = 55

40 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the factorial of a given number using for statement. Program: n = int(input("Enter the number : ")) fact = 1 for i in range(1, n + 1): fact = fact * i print("The factorial of", n, "is", fact) Output: Enter the number : 5 The factorial of 5 is 120

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 41

Develop a Python program to print addition table of the given number using for statement. Program: t = int(input("Enter the table : ")) n = int(input("Enter the limit : ")) for i in range(1, n + 1): print(i, "+", t, "=", i + t) Output: Enter the table : 5 Enter the limit : 15 1 + 5 = 6 2 + 5 = 7 3 + 5 = 8 4 + 5 = 9 5 + 5 = 10 6 + 5 = 11 7 + 5 = 12 8 + 5 = 13 9 + 5 = 14 10 + 5 = 15 11 + 5 = 16 12 + 5 = 17 13 + 5 = 18 14 + 5 = 19 15 + 5 = 20

42 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print multiplication table of the given number using for statement. Program: t = int(input("Enter the table : ")) n = int(input("Enter the limit : ")) for i in range(1, n + 1): print(i, "*", t, "=", i * t) Output: Enter the table : 5 Enter the limit : 15 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50 11 * 5 = 55 12 * 5 = 60 13 * 5 = 65 14 * 5 = 70 15 * 5 = 75

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 43

Develop a Python program to find the average of first n natural numbers without using the formula using for statement. Program: n = int(input("Enter the limit : ")) s = 0 for i in range(1, n + 1): s = s + i avg = s / n print("Average of first", n, "numbers is :", avg) Output: Enter the limit : 10 Average of first 10 numbers is : 5.5

44 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print the numbers that are divisible by a given number using for statement. Program: n = int(input("Enter the limit : ")) d = int(input("Enter the number : ")) print("The numbers divisible by", d, "are :") for i in range(1, n + 1): if(i % d == 0): print(i, end = "\t") Output: Enter the limit : 15 Enter the number : 3 The numbers divisible by 3 are : 3 6 9 12 15

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 45

Develop a Python program to print all the divisors of a given number using for statement. Program: n = int(input("Enter the number : ")) print("The divisors are :") for i in range(1, n + 1): if(n % i == 0): print(i, end = "\t") Output: Enter the number : 15 The divisors are : 1 3 5 15

46 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to generate odd and even numbers using for statement. Program: n = int(input("Enter the limit : ")) print("The odd numbers are :") for i in range(1, n + 1, 2): print(i, end = "\t") print("\nThe even numbers are :") for i in range(2, n + 1, 2): print(i, end = "\t") Output: Enter the limit : 10 The odd numbers are : 1 3 5 7 9 The even numbers are : 2 4 6 8 10

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 47

Develop a Python program to find the sum of odd and even numbers using for statement. Program: n = int(input("Enter the limit : ")) oddsum = 0 evensum = 0 for i in range(1, n + 1, 2): oddsum = oddsum + i for i in range(2, n + 1, 2): evensum = evensum + i print("The odd numbers sum is :", oddsum) print("The even numbers sum is :", evensum) Output: Enter the limit : 10 The odd numbers sum is : 25 The even numbers sum is : 30

48 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print first ‘n’ terms of the Fibonacci series using for statement. Program: n = int(input("Enter the number of terms : ")) a = -1 b = 1 print("The fibonacci series is :") for i in range(1, n + 1): c = a + b print(c, end = "\t") a = b b = c Output: Enter the number of terms : 7 The fibonacci series is : 0 1 1 2 3 5 8

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 49

Develop a Python program to the sum of Fibonacci series using for statement. Program: n = int(input("Enter the number of terms : ")) a = -1 b = 1 s = 0 print("The fibonacci series is :") for i in range(1, n + 1): c = a + b print(c, end = "\t") s = s + c a = b b = c print("\nThe sum of the series is :", s) Output: Enter the number of terms : 5 The fibonacci series is : 0 1 1 2 3 The sum of the series is : 7

50 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the given number is perfect number or not using for statement. Program: n = int(input("Enter the number : ")) s = 0 for i in range(1, n): if(n % i == 0): s = s + i if(s == n): print(n, "is a perfect number") else: print(n, "is not a perfect number") Output: Enter the number : 6 6 is a perfect number Enter the number : 28 28 is a perfect number Enter the number : 12 12 is not a perfect number

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 51

Develop a Python program to generate numbers between 20 and 100 which are divisible by 2 and not divisible by 3 and 5 using for statement. Program: print("The numbers are :") for i in range(20, 101): if(i % 2 == 0 and (i % 3 != 0 and i % 5 != 0)): print(i, end = "\t") Output: The numbers are : 22 26 28 32 34 38 44 46 52 56 58 62 64 68 74 76 82 86 88 92 94 98

52 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the sum of the series 1 + x2/2 + x3/3 + ... xn/n using for statement. Program: n = int(input("Enter the number of terms : ")) x = int(input("Enter the value of x : ")) s = 1 for i in range(2, n + 1): s = s + (x ** i) / i print("The sum of the series is =", s) Output: Enter the number of terms : 5 Enter the value of x : 2 The sum of the series is = 16.066666666666666

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 53

Develop a Python program to find the sum of the series 1 + 1/2 + 1/3 + ... 1/n using for statement. Program: n = int(input("Enter the number of terms : ")) s = 1 for i in range(2, n + 1): s = s + 1 / i print("The sum of the series is =", s) Output: Enter the number of terms : 5 The sum of the series is = 2.283333333333333

54 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to generate the Armstrong numbers from 1 – 1000. Program: print("The Armstrong numbers from 1 to 1000 are :") for i in range(1, 1001): n = i s = 0 while(n > 0): rem = n % 10 s = s + (rem ** 3) n = n // 10 if(s == i): print(i, end = "\t") Output: The Armstrong numbers from 1 to 1000 are : 1 153 370 371 407

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 55

Develop a Python program to check whether a given number is a prime number or not and print the result using for statement. Program: n = int(input("Enter the number : ")) flag = 0 for i in range(2, n//2 + 1): if(n % i == 0): flag = 1 break if(flag == 1): print("The number is not a prime") else: print("The number is a prime") Output: Enter the number : 6 The number is not a prime Enter the number : 11 The number is a prime

56 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print 10 x 10 multiplication table using nested for statement. Program: print("Multiplication Table") for i in range(1, 11): for j in range(1, 11): print(i * j, end = "\t") print() Output: Multiplication Table 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 57

Develop a Python program to generate Floyd's triangle using nested for statement. Program: n = int(input("Enter the number of rows : ")) c = 1 for i in range(n): for j in range(i + 1): print(c, end = "\t") c = c + 1 print() Output: Enter the number of rows : 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

58 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to the first ‘N’ prime numbers using nested for statement. Program: a = int(input("Enter the limit : ")) for n in range(1, a + 1): flag = 0 for i in range(2, n//2 + 1): if(n % i == 0): flag = 1 break if(flag == 0): print(n, end = "\t") Output: Enter the limit : 7 1 2 3 5 7

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 59

60 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - II Part - A

Question Bank 1. Differentiate compiler and interpreter.

An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations.

A compiler reads the program and translates it completely before the program starts running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. 2. Describe about Python?

Python was created by Guido van Rossum. The idea of Python was conceived in December 1989. The name Python comes from the 70s comedy series “Monty Python’s Flying Circus” and has nothing to do with the reptilian. 3. List some of the features of Python.

Simple and easy to learn Portable Interactive mode Broad standard library Extendable Databases GUI Programming Scalable

4. Differentiate interactive and script mode. (or) How can you run Python?

In interactive mode, you type Python programs and the interpreter displays the result: >>> 1 + 1 2

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you

type 1 + 1, the interpreter replies 2.

Alternatively, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. By convention, Python scripts have names that end with .py.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

5. What are values and types in Python?

A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2, 42.0, and 'Hello, World!'

These values belong to different types: 2 is an integer, 42.0 is a floating-point number, and 'Hello, World!' is a string, so-called because the letters it contains are strung together.

6. How can you give comments in Python? Give example.

These notes are called comments, and they start with the #symbol: # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end

of a line: percentage = (minute * 100) / 60 # percentage of an hour

Everything from the # to the end of the line is ignored - it has no effect on the execution of

the program. 7. Define variable.

A variable is basically a name that represents (or refers to) some value. Variable are reserved memory locations to store values. 8. Give the rules for naming a variable in Python.

They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lowercase for

variables names. The underscore character, _, can appear in a name. It is often used in names with

multiple words, such as your_name or airspeed_of_unladen_swallow. The interpreter uses keywords to recognize the structure of the program, and they

cannot be used as variable names. 9. Define keywords.

Keywords are the reserved words in Python. We cannot use keywords as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. 10. What is an expression? Give example.

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

>>> 42 42 >>> n 17 >>> n + 25 42

11. What is a statement? Give example.

A statement is a unit of code that has an effect, like creating a variable or displaying a value.

>>> n = 17 >>> print(n)

The first line is an assignment statement that gives a value to n. The second line is a print

statement that displays the value of n.

12. List the types of operators in Python.

Arithmetic operators Relational or comparison operators Assignment operators Bitwise operators Logical operators Membership operators Identity operators

13. What is an assignment statement? Give example.

An assignment statement creates a new variable and gives it a value: >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.141592653589793 This example makes three assignments. The first assigns a string to a new variable

named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.

14. What is the purpose of floor division? Give example. (or) What is the purpose of // operator?

Give example.

The floor division operator, //, divides two numbers and rounds down to an integer. For example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Floor division returns the integer number of hours, dropping the fraction part:

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> minutes = 105 >>> hours = minutes // 60 >>> hours 1

15. What is the purpose of modulus operator? Give example.

The modulus operator, %, which divides two numbers and returns the remainder: >>> remainder = minutes % 60 >>> remainder 45

The modulus operator is more useful than it seems. For example, you can check whether

one number is divisible by another - if x % y is zero, then x is divisible by y. 16. What is Boolean expression? Give example.

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

>>> 5 == 5 True >>> 5 == 6 False

17. List out the controls for decision making statements.

if statement if...else statement if...elif...else statement Nested if...else statement

18. Write the syntax and draw the flow chart for if statement in Python. Syntax

if(test-expression): statement-block(s)

statement-x

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Flowchart

19. Write the syntax and draw the flow chart for if...else statement in Python. Syntax

The syntax looks like this: if(test-expression):

true-block-statement(s) else:

false-block-statement(s) statement-x

Flowchart

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

20. Write the syntax and draw the flow chart for if...elis...else statement in Python. Syntax

if(test-condition-1):

statement-1 elif(test-condition-2):

statement-2 . . . . . . . . . elif(test-condition-n):

statement-n else: default-statement statement-x

Flowchart

21. Write the syntax and draw the flow chart for nested if...else statement in Python. Syntax

if(test-condition-1): if(test-condition-2): statement-1 else: statement-2 else: statement-3 statement-x

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Flowchart

22. List out the operator precedence in Python.

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is

18, not 36.

Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by , you can use parentheses or write degrees / 2 / pi. 23. Define iteration.

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

24. What are the types of looping constructs in Python?

Python provides two types of looping constructs. They are: while loop for loop

25. Write the syntax and draw the flow chart for while statement in Python. Syntax

while(test-condition): body of the loop statement-x

Flowchart

26. What is the flow of execution for a while statement?

More formally, here is the flow of execution for a while statement: 1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1.

27. What is an infinite loop? Give example.

The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

28. Write the syntax and draw the flow chart for for statement in Python. Syntax

for variable in sequence: body of the loop statement-x

Flowchart

29. What is nested loop? Give example.

Nesting is defined as the placing of one loop inside the body of another loop. When we nest two loops, the outer loop takes control of the number of complete repetitions of the inner loop. Example:

for i in range(1, 6): for j in range(1, i + 1): print(j, end = " ") print()

Output:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

30. What is the purpose of break statement? Give example.

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

For example, suppose you want to take input from the user until they type done. You could write:

while True: line = input('> ') if line == 'done': break print(line) print('Done!') The loop condition is True, which is always true, so the loop runs until it hits the break

statement. 31. What is the purpose of continue statement? Give example.

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

For example we wish to print the squares of all the odd numbers below 10, which are not

multiples of 3, we would modify the for loop as follows. for n in range(1, 10, 2): if n % 3 == 0: continue print (n * n) produces the output 1 25 49

32. What is the purpose of pass statement in Python? Give example.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

if x < 0: pass # TODO: need to handle negative values!

“pass” statement acts as a place holder for the block of code. It is equivalent to a null operation. It literally does nothing. It can used as a place holder when the actual code implementation for a particular block of code is not known yet but has to be filled up later.

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai – 602 105

Department of Computer Science and Engineering GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - II Part - B

Question Bank 1. Explain the arithmetic operators in Python.

The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:

>>> 40 + 2 42 >>> 43 – 1 42 >>> 6 * 7 42

The operator / performs division: >>> 84 / 2 42.0

You might wonder why the result is 42.0 instead of 42.

Finally, the operator ** performs exponentiation; that is, it raises a number to a power:

>>> 6**2 + 6 42

In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator

called XOR. If you are not familiar with bitwise operators, the result will surprise you: >>> 6 ^ 2 4

Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example + Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand.

a - b = -10 b - a = 10

* Multiplication Multiplies values on either side of the operator. a * b = 200

/ Division Divides left hand operand by right hand operand. a / b = 0.5 b / a = 2.0

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

% Modulus Divides left hand operand by right hand operand and returns remainder.

a % b = 10 b % a = 0

** Exponent Performs exponential (power) calculation on operators.

a**2 =100 b ** 3 = 8000

//

Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity).

a // b = 0 b // a = 2

2. Explain the logical operators in Python.

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.

n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y.

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True:

>>> 42 and True True This flexibility can be useful, but there are some subtleties to it that might be confusing.

You might want to avoid it (unless you know what you are doing).

Assume variable a holds 10 and variable b holds 20.

Operator Description Example

and Logical AND

If both the operands are True then condition becomes True. If any one of the operand is False, then the condition becomes False.

(a and b) is True

or Logical OR

If any of the two operands are non-zero then condition becomes True. If both the operands are False, then the condition becomes False.

(a or b) is True

not Logical NOT

It returns False when the condition is True and vice versa. Used to reverse the logical state of its operand.

Not(a and b) is False

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

3. Explain the Python’s order op operations.

When an expression contains more than one operator, the order of evaluation depends on the order of operations.

Operator

Description

** Exponentiation (raise to the power) ~ + -

Complement, unary plus and minus

* / % //

Multiply, divide, modulo and floor division

+ -

Addition and subtraction

>> <<

Right and left bitwise shift

& Bitwise 'AND' ^ | Bitwise exclusive `OR' and regular `OR'

<= < >

>=

Comparison operators

== !=

Equality operators

= %= /= //= -= += *=

**=

Assignment operators

is is not Identity operators

in not in Membership operators

not or

and Logical operators

For mathematical operators, Python follows mathematical convention. The

acronym PEMDAS is a useful way to remember the rules:

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is 18, not 36.

Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by , you can use parentheses or write degrees / 2 / pi.

4. Explain the various conditional statements available in Python. if Statement

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. Syntax

if(test-expression): statement-block(s) statement-x

Flowchart

The simplest form is the if statement: if x > 0: print('x is positive')

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

The boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens.

if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements. if...else Statement

A second form of the if statement is “alternative execution”, in which there are two possibilities and the condition determines which one runs. Syntax

The syntax looks like this: if(test-expression): true-block-statement(s) else: false-block-statement(s) statement-x

Flowchart

For example: if x % 2 == 0: print('x is even') else: print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program

displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

if...elif...else Statement

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional. Syntax

if(test-condition-1): statement-1 elif(test-condition-2): statement-2 . . . . . . . . . elif(test-condition-n): statement-n else: default-statement statement-x

Flowchart

For example: if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

Each condition is checked in order. If the first is false, the next is checked, and so on. If one

of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs. 5. Explain the various iteration statements available in Python.

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration. while Statement Syntax

while(test-condition): body of the loop statement-x

Flowchart

Here is a version of countdown that uses a while statement:

while n > 0: print(n) n = n - 1 print('Blastoff!')

More formally, here is the flow of execution for a while statement: 1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. for Statement

A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top.

The syntax of a for statement has a header that ends with a colon and an indented body.

The body can contain any number of statements. Syntax

for variable in sequence: body of the loop statement-x

Flowchart

For example: for i in range(4): print('Hello!')

You should see something like this: Hello! Hello! Hello! Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai – 602 105

Department of Computer Science and Engineering Unit - II Part - C

Question Bank GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING

Develop a Python to add the two integers 10 and 20. Program: firstno = 10 secondno = 20 result = firstno + secondno print("Result =", result) Output: Result = 30 Develop a Python program to find the type of various values. Program: a = 10 b = 3.14 c = "REC" d = True print("Type of a is", type(a)) print("Type of b is", type(b)) print("Type of c is", type(c)) print("Type of d is", type(d)) Output: Type of a is <class 'int'> Type of b is <class 'float'> Type of c is <class 'str'> Type of d is <class 'bool'>

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Pyton program to swap two numbers (using three variables). Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print("Before swapping :") print("a =", a, "b =",b) c = a a = b b = c print("After swapping :") print("a =", a, "b =",b) Output: Enter the first number : 10 Enter the second number : 20 Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10 Develop a Python program to swap two numbers (using two variables). Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print("Before swapping :") print("a =", a, "b =",b) a = a + b b = a - b a = a - b print("After swapping :") print("a =", a, "b =",b) Output: Enter the first number : 10 Enter the second number : 20 Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Develop a Python Program to read numerator and denominator and print their quotient and remainder. Program: n = int(input("Enter the numerator : ")) d = int(input("Enter the denominator : ")) q = n // d r = n % d print("Quotient =", q, "Remainder =", r) Output: Enter the numerator : 10 Enter the denominator : 3 Quotient = 3 Remainder = 1 Develop a Python program to compute the simple interest. Program: p = int(input("Enter the principle amount : ")) n = int(input("Enter the number of years : ")) r = float(input("Enter the rate of interest : ")) si = (p * n * r) / 100 print("Simple interest =", si) Output: Enter the principle amount : 10000 Enter the number of years : 5 Enter the rate of interest : 12.00 Simple interest = 6000.0 Develop a Python program to find the area and circumference of a circle. Program: r = float(input("Enter the radius : ")) area = 3.14 * r * r circum = 2 * 3.14 * r print("Area = :", area) print("Circumference = :", circum) Output: Enter the radius : 3 Area = : 28.259999999999998 Circumference = : 18.84

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to Convert the °C to °F. Program: c = float(input("Enter the centigrade : ")) f = (1.8 * c + 32) print("The fahrenheit is =", f) Output: Enter the centigrade : 45 The fahrenheit is = 113.0 Develop a Python program to Convert the °F to °C. Program: f = float(input("Enter the fahrenheit : ")) c = (f - 32) / 1.8 print("The centigrade is =", c) Output: Enter the fahrenheit : 113 The centigrade is = 45.0 Develop a Python program to demonstrate sequence execution (average of three numbers). Program: num1 = float(input("Enter the first number : ")) num2 = float(input("Enter the first number : ")) num3 = float(input("Enter the first number : ")) avg = (num1 + num2 + num3) / 3 print("Average =", avg) Output: Enter the first number : 10 Enter the first number : 20 Enter the first number : 30 Average = 20.0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Develop a Python program to find the cutoff marks in an engineering admission using if statement. Program: cutoff = float(input("Enter cutoff mark : ")) quota = int(input("Enter the quota 1-General 2-Sports : ")) if (quota == 2): cutoff = cutoff + 5 print("Cutoff mark =", cutoff) Output: Enter cutoff mark : 170 Enter the quota 1-General 2-Sports : 1 Cutoff mark = 170.0 Enter cutoff mark : 160 Enter the quota 1-General 2-Sports : 2 Cutoff mark = 165.0 Develop a Python program to find whether the given number is even or odd using if statement. Program: num = int(input("Enter the number : ")) if (num % 2 == 0): print("The given number is even") if (num % 2 != 0): print("The given number is odd") Output: Enter the number : 10 The given number is even Enter the number : 5 The given number is odd

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find whether the given number is positive or negative using if statement. Program: num = int(input("Enter the number : ")) if (num > 0): print("The given number is positive") if (num < 0): print("The given number is negative") Output: Enter the number : 2 The given number is positive Enter the number : -14 The given number is negative Develop a Python program to check whether the person is eligible to vote or not using if statement. Program: age = int(input("Enter the age : ")) if (age >= 18): print("The person is eligible to vote") if (age < 18): print("The person is not eligible to vote") Output: Enter the age : 20 The person is eligible to vote Enter the age : 16 The person is not eligible to vote

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Develop a Python program to check whether the person is in teen age or not using if statement. Program: age = int(input("Enter the age : ")) if (age >= 13 and age <= 19): print("The person is in teen age") if (age <= 12 or age >= 20): print("The person is not in teen age") Output: Enter the age : 16 The person is in teen age Enter the age : 21 The person is not in teen age Develop a Python program to find whether the given number is positive or negative using if...else statement. Program: num = int(input("Enter the number : ")) if (num > 0): print("The given number is positive") else: print("The given number is negative") Output: Enter the number : 2 The given number is positive Enter the number : -14 The given number is negative

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find whether the given number is even or odd using if...else statement. Program: num = int(input("Enter the number : ")) if (num % 2 == 0): print("The given number is even") else: print("The given number is odd") Output: Enter the number : 10 The given number is even Enter the number : 5 The given number is odd Develop a Python program to check whether the person is eligible to vote or not using if...else statement. Program: age = int(input("Enter the age : ")) if (age >= 18): print("The person is eligible to vote") else: print("The person is not eligible to vote") Output: Enter the age : 20 The person is eligible to vote Enter the age : 16 The person is not eligible to vote

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Develop a Python program to check whether the person is in teen age or not using if...else statement. Program: age = int(input("Enter the age : ")) if (age >= 13 and age <= 19): print("The person is in teen age") else: print("The person is not in teen age") Output: Enter the age : 16 The person is in teen age Enter the age : 21 The person is not in teen age Develop Python program to input the mark and print grade. Grades are awarded according to the following criteria:

91 to 100 S Grade 81 to 90 A Grade 71 to 80 B Grade 61 to 70 C Grade 57 to 60 D Grade 50 to 56 E Grade <50 U Grade

Program: mark = int(input("Enter the mark : ")) if(mark >= 91): print("S Grade") elif(mark >= 81): print("A Grade") elif(mark >= 71): print("B Grade") elif(mark >= 61): print("C Grade") elif(mark >= 57): print("D Grade") elif(mark >= 50): print("E Grade") else: print("U Grade")

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Output Enter the mark : 85 A Grade Enter the mark : 45 U Grade Develop a Python program to check whether the given year is leap year or not using if...elif...else statement. Program: year = int(input("Enter the year : ")) if(year % 400 == 0): print(year, "is a leap year") elif(year % 4 == 0 and year % 100 != 0): print(year, "is a leap year") else: print(year, "is not a leap year") Output: Enter the year : 2012 2012 is a leap year Enter the year : 2013 2013 is not a leap year Develop a Python program to calculate electricity bill for domestic consumers as follows:

Units Charges (Rs. / Unit) Upto 100 3.00 101 – 200 3.25 201 – 500 Rs.700 + 4.60 per unit excess of 200

501 and above Rs.2080 + 6.60 per unit excess of 500 Program: units = int(input("Enter the units consumed : ")) if(units <= 100): amount = 3.00 * units elif(units <= 200): amount = 3.25 * units elif(units <= 500): amount = 700.00 + 4.60 * (units - 200) else: amount = 2080.00 + 6.60 * (units - 500) print("Units =", units, "Amount =", amount)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

Output: Enter the units consumed : 77 Units = 77 Amount = 231.0 Enter the units consumed : 140 Units = 140 Amount = 455.0 Enter the units consumed : 280 Units = 280 Amount = 1068.0 Enter the units consumed : 560 Units = 560 Amount = 2476.0 Develop a Python program to check if the number is positive or negative or zero using nested if..else statement. Program: num = int(input("Enter the number : ")) if(num == 0): print('The number is zero') else: if(num > 0): print('The number is positive') else: print('The number is negative') Output: Enter the number : 2 The number is positive Enter the number : -14 The number is negative Enter the number : 0 The number is zero

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the biggest of 3 numbers using nested if...else statement. Program: a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) c = int(input("Enter the third number : ")) if(a > b): if(a > c): print(a, "is the biggest number") else: print(c, "is the biggest number") else: if(b > c): print(b, "is the biggest number") else: print(c, "is the biggest number") Output: Enter the first number : 10 Enter the second number : 20 Enter the third number : 30 30 is the biggest number Enter the first number : 20 Enter the second number : 30 Enter the third number : 10 30 is the biggest number Enter the first number : 30 Enter the second number : 10 Enter the third number : 20 30 is the biggest number

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

Develop a Python program to check whether the given year is leap year or not using nested if...else statement. Program: year = int(input("Enter the year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(year, "is a leap year") else: print(year, "is not a leap year") else: print(year, "is a leap year") else: print(year, "is not a leap year") Output: Enter the year: 2012 2012 is a leap year Enter the year: 2013 2013 is not a leap year

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to compute the roots of a quadratic equation. Program: a = float(input("Enter the value for a : ")) b = float(input("Enter the value for b : ")) c = float(input("Enter the value for c : ")) d = (b ** 2) - (4 * a * c) if(d < 0): print("Roots are imaginary") real = - b / (2 * a) d = -d imag = (d ** 0.5) / (2 * a) print("root 1 =", real, "+ j", imag) print("root 2 =", real, "- j", imag) elif(d == 0): print("Roots are real and equal") r = - b / (2 * a) print("root =", r) elif(d > 0): print("Roots are real and unequal") r1 = (- b + (d ** 0.5)) / (2 * a) r2 = (- b - (d ** 0.5)) / (2 * a) print("root 1 =", r1) print("root 2 =", r2) Output: Enter the value for a : 1 Enter the value for b : 2 Enter the value for c : 7 Roots are imaginary root 1 = -1.0 + j 2.449489742783178 root 2 = -1.0 - j 2.449489742783178 Enter the value for a : 1 Enter the value for b : 2 Enter the value for c : 1 Roots are real and equal root = -1.0 Enter the value for a : 2 Enter the value for b : 7 Enter the value for c : 1 Roots are real and unequal root 1 = -0.14921894064178787 root 2 = -3.350781059358212

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

CHAPTER – 1 - FUNCTIONS 1.1 INTRODUCTION

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name.

1.2 FUNCTION CALLS - TYPE CONVERSION

We have already seen one example of a function call:

>>> type(42) <class 'int'>

The name of the function is type. The expression in parentheses is called the argument of

the function. The result, for this function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is also called the return value.

Python provides functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

>>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int() with base 10: 'Hello'

int can convert floating-point values to integers, but it doesn’t round off; it chops off the

fraction part:

>>> int(3.99999) 3 >>> int(-2.3) -2

float converts integers and strings to floating-point numbers:

>>> float(32) 32.0 >>> float('3.14159') 3.14159

Finally, str converts its argument to a string:

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> str(32) '32' >>> str(3.14159) '3.14159'

1.3 MATH FUNCTIONS

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.

Before we can use the functions in a module, we have to import it with an import statement:

>>> import math This statement creates a module object named math. If you display the module object, you

get some information about it:

>>> math <module 'math' (built-in)>

The module object contains the functions and variables defined in the module. To access

one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians)

The first example uses math.log10 to compute a signal-to-noise ratio in decibels (assuming

that signal_power and noise_power are defined). The math module also provides log, which computes logarithms base e.

The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 180 and multiply by π:

>>> degrees = 45 >>> radians = degrees / 180.0 * math.pi >>> math.sin(radians) 0.707106781187

The expression math.pi gets the variable pi from the math module. Its value is a floating-

point approximation of π, accurate to about 15 digits.

If you know trigonometry, you can check the previous result by comparing it to the square root of 2 divided by 2:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

>>> math.sqrt(2) / 2.0 0.707106781187

1.4 COMPOSITION

So far, we have looked at the elements of a program-variables, expressions, and statements-in isolation, without talking about how to combine them.

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:

x = math.sin(degrees / 360.0 * 2 * math.pi) And even function calls:

x = math.exp(math.log(x+1))

Almost anywhere you can put a value, you can put an arbitrary expression, with one

exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later).

>>> minutes = hours * 60 # right >>> hours * 60 = minutes # wrong! SyntaxError: can't assign to operator

1.5 ADDING NEW FUNCTIONS (FUNCTION DEFINITION)

So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that run when the function is called. Syntax

def function_name(parameters): """docstring""" statement(s)

Here is an example:

def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.")

def is a keyword that indicates that this is a function definition. The name of the function

is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and underscore are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.

The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.

All quotation marks (single and double) must be “straight quotes”, usually located next to Enter on the keyboard. “Curly quotes”, like the ones in this sentence, are not legal in Python.

If you type a function definition in interactive mode, the interpreter prints dots (...) to let you know that the definition isn’t complete:

>>> def print_lyrics(): ... print("I'm a lumberjack, and I'm okay.") ... print("I sleep all night and I work all day.") ... To end the function, you have to enter an empty line.

Defining a function creates a function object, which has type function: >>> print(print_lyrics) <function print_lyrics at 0x000001D41AD82EA0> >>> type(print_lyrics) <class 'function'>

The syntax for calling the new function is the same as for built-in functions:

>>> print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

Once you have defined a function, you can use it inside another function. For example, to

repeat the previous refrain, we could write a function called repeat_lyrics: def repeat_lyrics(): print_lyrics() print_lyrics()

And then call repeat_lyrics:

>>> repeat_lyrics()

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

1.6 DEFINITIONS AND USES

Pulling together the code fragments from the previous section, the whole program looks like this:

def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.") def repeat_lyrics(): print_lyrics() print_lyrics() repeat_lyrics()

This program contains two function definitions: print_lyrics and repeat_lyrics. Function

definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not run until the function is called, and the function definition generates no output.

As you might expect, you have to create a function before you can run it. In other words, the function definition has to run before the function gets called.

As an exercise, move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.

Now move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program? 1.7 FLOW OF EXECUTION

To ensure that a function is defined before its first use, you have to know the order statements run in, which is called the flow of execution.

Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the program, but remember that statements inside the function don’t run until the function is called.

A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to run the statements in another function. Then, while running that new function, the program might have to run yet another function!

Fortunately, Python is good at keeping track of where it is, so each time a function

completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.

In summary, when you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.

Figure 1-1. Flow of execution.

1.8 PARAMETERS AND ARGUMENTS

Some of the functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent.

Inside the function, the arguments are assigned to variables called parameters. Here is a definition for a function that takes an argument:

def print_twice(bruce): print(bruce) print(bruce)

This function assigns the argument to a parameter named bruce. When the function is

called, it prints the value of the parameter (whatever it is) twice.

This function works with any value that can be printed: >>> print_twice('Spam') Spam Spam

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

>>> print_twice(42) 42 42 >>> print_twice(math.pi) 3.14159265359 3.14159265359

The same rules of composition that apply to built-in functions also apply to programmer-

defined functions, so we can use any kind of expression as an argument for print_twice: >>> print_twice('Spam '*4) Spam Spam Spam Spam Spam Spam Spam Spam >>> print_twice(math.cos(math.pi))-1.0 -1.0

The argument is evaluated before the function is called, so in the examples the

expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.

You can also use a variable as an argument: >>> michael = 'Eric, the half a bee.' >>> print_twice(michael) Eric, the half a bee. Eric, the half a bee.

The name of the variable we pass as an argument (michael) has nothing to do with the

name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce. 1.9 VARIABLES AND PARAMETERS ARE LOCAL

When you create a variable inside a function, it is local, which means that it only exists inside the function. For example:

def cat_twice(part1, part2): cat = part1 + part2 print_twice(cat)

This function takes two arguments, concatenates them, and prints the result twice. Here is

an example that uses it: >>> line1 = 'Bing tiddle ' >>> line2 = 'tiddle bang.' >>> cat_twice(line1, line2) Bing tiddle tiddle bang. Bing tiddle tiddle bang.

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an

exception: >>> print(cat) NameError: name 'cat' is not defined

Parameters are also local. For example, outside print_twice, there is no such thing

as bruce. 1.10 STACK DIAGRAMS

To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.

Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure 1-2.

Figure 1-2. Stack diagram.

The frames are arranged in a stack that indicates which function called which, and so on. In this example, print_twice was called by cat_twice, and cat_twice was called by __main__, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to __main__.

Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat.

If an error occurs during a function call, Python prints the name of the function, the name of the function that called it, and the name of the function that called that, all the way back to __main__.

For example, if you try to access cat from within print_twice, you get a NameError: Traceback (innermost last): File "test.py", line 13, in __main__ cat_twice(line1, line2)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

File "test.py", line 5, in cat_twice print_twice(cat) File "test.py", line 9, in print_twice print(cat) NameError: name 'cat' is not defined

This list of functions is called a traceback. It tells you what program file the error occurred

in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.

The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom. 1.11 FRUITFUL FUNCTIONS AND VOID FUNCTIONS

Some of the functions we have used, such as the math functions, return results; for lack of a better name, we call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions.

When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:

>>> x = math.cos(radians) >>> golden = (math.sqrt(5) + 1) / 2

When you call a function in interactive mode, Python displays the result:

>>> math.sqrt(5) 2.2360679774997898

But in a script, if you call a fruitful function all by itself, the return value is lost forever!

math.sqrt(5)

This script computes the square root of 5, but since it doesn’t store or display the result, it

is not very useful.

Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you assign the result to a variable, you get a special value called None:

>>> result = print_twice('Bing') Bing Bing >>> print(result) None

The value None is not the same as the string 'None'. It is a special value that has its own

type:

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> print(type(None)) <class 'NoneType'>

The functions we have written so far are all void. We will start writing fruitful functions in a

few chapters. 1.12 WHY FUNCTIONS?

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

Creating a new function gives you an opportunity to name a group of statements,

which makes your program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Later, if you

make a change, you only have to make it in one place. Dividing a long program into functions allows you to debug the parts one at a time and

then assemble them into a working whole. Well-designed functions are often useful for many programs. Once you write and

debug one, you can reuse it.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

REVIEW QUESTIONS 1. Write the syntax for defining the function. 2. What are the features of DocString? 3. List the advantages of functions in Python. 4. What are the two types of functions? 5. Briefly explain the function definition and function calling in Python.

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program using function to concatenate two strings and print the same. 2. Develop a Python program using function to repeat the given string in n number of times. 3. Develop a Python program using function to compute the cube of a number and print the

same.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

CHAPTER - 2 - FRUITFUL FUNCTIONS 2.1 INTRODUCTION

Many of the Python functions we have used, such as the math functions, produce return values. But the functions we’ve written are all void: they have an effect, like printing a value or moving a turtle, but they don’t have a return value. In this chapter you will learn to write fruitful functions. 2.2 RETURN VALUES

Calling the function generates a return value, which we usually assign to a variable or use as part of an expression.

e = math.exp(1.0) height = radius * math.sin(radians)

The functions we have written so far are void. Speaking casually, they have no return value;

more precisely, their return value is None.

In this chapter, we are (finally) going to write fruitful functions. The first example is area, which returns the area of a circle with the given radius:

def area(radius): a = math.pi * radius**2 return a

We have seen the return statement before, but in a fruitful function the return statement

includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely:

def area(radius): return math.pi * radius**2

Syntax

return [expression_list] On the other hand, temporary variables like a can make debugging easier.

Sometimes it is useful to have multiple return statements, one in each branch of a

conditional:

def absolute_value(x): if x < 0: return -x else: return x

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Since these return statements are in an alternative conditional, only one runs. As soon as a return statement runs, the function terminates without executing any

subsequent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.

In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example:

def absolute_value(x): if x < 0: return -x if x > 0: return x

This function is incorrect because if x happens to be 0, neither condition is true, and the

function ends without hitting a return statement. If the flow of execution gets to the end of a function, the return value is None, which is not the absolute value of 0:

>>> absolute_value(0) None

By the way, Python provides a built-in function called abs that computes absolute values.

As an exercise, write a compare function takes two values, x and y, and returns 1 if x >

y, 0 if x == y, and -1 if x < y. 2.3 BOOLEAN FUNCTIONS

Functions can return booleans, which is often convenient for hiding complicated tests inside functions. For example:

def is_divisible(x, y): if x % y == 0: return True else: return False

It is common to give boolean functions names that sound like yes/no

questions; is_divisible returns either True or False to indicate whether x is divisible by y.

Here is an example: >>> is_divisible(6, 4) False >>> is_divisible(6, 3) True

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

The result of the == operator is a boolean, so we can write the function more concisely by returning it directly:

def is_divisible(x, y): return x % y == 0

Boolean functions are often used in conditional statements:

if is_divisible(x, y): print('x is divisible by y')

It might be tempting to write something like:

if is_divisible(x, y) == True: print('x is divisible by y')

But the extra comparison is unnecessary.

As an exercise, write a function is_between(x, y, z) that returns True if or False

otherwise. 2.4 RECURSION

It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function:

def countdown(n): if n <= 0: print('Blastoff!') else: print(n) countdown(n-1)

If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n and then calls a

function named countdown-itself-passing n-1 as an argument.

What happens if we call this function like this?

>>> countdown(3)

The execution of countdown begins with n=3, and since n is greater than 0, it outputs the value 3, and then calls itself...

The execution of countdown begins with n=2, and since n is greater than 0, it outputs the value 2, and then calls itself...

The execution of countdown begins with n=1, and since n is greater than 0, it outputs the value 1, and then calls itself...

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the word, “Blastoff!” and then returns.

The countdown that got n=1 returns.

The countdown that got n=2 returns.

The countdown that got n=3 returns.

And then you’re back in __main__. So, the total output looks like this:

3 2 1 Blastoff!

A function that calls itself is recursive; the process of executing it is called recursion.

As another example, we can write a function that prints a string n times:

def print_n(s, n): if n <= 0: return print(s) print_n(s, n-1)

If n <= 0 the return statement exits the function. The flow of execution immediately

returns to the caller, and the remaining lines of the function don’t run.

The rest of the function is similar to countdown: it displays s and then calls itself to display s n-1 additional times. So the number of lines of output is 1 + (n - 1), which adds up to n.

For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early. 2.5 MORE RECURSION

If you looked up the definition of the factorial function, denoted with the symbol !, you might get something like this:

This definition says that the factorial of 0 is 1, and the factorial of any other value, n,

is n multiplied by the factorial of n-1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

If you can write a recursive definition of something, you can write a Python program to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that factorial takes an integer:

def factorial(n):

If the argument happens to be 0, all we have to do is return 1:

def factorial(n): if n == 0: return 1

Otherwise, and this is the interesting part, we have to make a recursive call to find the

factorial of n-1 and then multiply it by n:

def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result

The flow of execution for this program is similar to the flow of countdown in “Recursion”. If

we call factorial with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of n-1... Since 2 is not 0, we take the second branch and calculate the factorial of n-1... Since 1 is not 0, we take the second branch and calculate the factorial of n-1...

Since 0 equals 0, we take the first branch and return 1 without making any more recursive

calls.

The return value, 1, is multiplied by n, which is 1, and the result is returned.

The return value, 1, is multiplied by n, which is 2, and the result is returned. The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return

value of the function call that started the whole process. Figure 2-1 shows what the stack diagram looks like for this sequence of function calls.

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Figure 2-1. Stack diagram. The return values are shown being passed back up the stack. In each frame, the return

value is the value of result, which is the product of n and recurse.

In the last frame, the local variables recurse and result do not exist, because the branch that creates them does not run. 2.6 ONE MORE EXAMPLE

After factorial, the most common example of a recursively defined mathematical function is fibonacci, which has the following definition:

Translated into Python, it looks like this: def fibonacci (n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

REVIEW QUESTIONS 1. What is the purpose of a return statement? 2. Illustrate with an example, the working of recursive functions.

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program using function to compute the factorial of a given number. 2. Develop a Python program to find maximum of given three numbers using parameter passing. 3. Develop a Python program to find minimum of given three numbers using parameter passing. 4. Develop a Python program to find the sum of ‘N’ natural number using function. 5. Develop a Python program to find the square and cube of a number using a function

declaration using the return statement. 6. Develop a Python program to find the given number as an Armstrong number or not using user

defined function. 7. Develop a Python program using functions that will compute and print the area of any four

geometric shapes. Write a main function to get the input and invoke the function using conditional statement.

8. Develop a Python program to find the second largest digit from a number using function. 9. Develop a Python program to find the sum of digits of a number using function. 10. Develop a Python program using function, to check whether the given number and its reverse

are same. 11. Develop a Python program to find the sum of square of individual digits of a number using

function. 12. Develop a Python program to find the smallest digit from a number using function. 13. Develop a Python program using function to find the sum of the following series:

14. Develop a Python program using function that will scan a character string passed as an

argument and convert all lower-case characters to their upper-case equivalents. 15. Develop a Python program to sort ‘N’ names alphabetically. Use functions. 16. Develop a Python program using function to print all combinations of a 4-digit number. 17. Develop a Python program using function to generate permutation of the given string. 18. Develop a Python program to find the absolute value of the number without using abs

function. 19. Develop a Python program using function to find the given number is odd or even. 20. Develop a Python program to find the factorial of a number using recursive function. 21. Develop a Python program to print the Fibonacci series using recursion. 22. Develop a Python program to find nCr using recursive function. 23. Develop a Python program to find the sum of numbers up to n using recursive function.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

CHAPTER - 3 - FUNCTION ARGUMENTS AND ANONYMOUS FUNCTIONS 3.1 FUNCTION ARGUMENTS

In Python, user-defined functions can take four different types of arguments. The argument types and their meanings, however, are pre-defined and can’t be changed. But a developer can, instead, follow these pre-defined rules to make their own custom functions. The following are the four types of arguments and their rules.

Required arguments Keyword arguments Default arguments Variable-length arguments

3.1.1 Required Arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. Example:

def printme(s): print(s) printme()

To call the function printme(), you definitely need to pass one argument, otherwise it gives

a syntax error as follows: Traceback (most recent call last): printme() TypeError: printme() missing 1 required positional argument: 's'

3.1.2 Keyword Arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

Example: def printinfo(name, age): print ("Name :", name) print ("Age :", age) printinfo(age = 19, name = "Arun")

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Output: Name : Arun Age : 19 Note that the order of parameters does not matter. Python expects all the keyword to be

present towards the end.

3.1.3 Default Arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed:

def printinfo(name, age = 19): print ("Name :", name) print ("Age :", age) printinfo("Arun", 20) printinfo("Babu")

Output: Name : Arun

Age : 20 Name : Babu Age : 19

Note that when defining a function all the argument with default values should come at the end. 3.1.4 Variable-length Arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is given below: def functionname([formal_args,] *var_args_tuple): '''function_docstring''' function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all non-keyword

variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

def printargs(*vartuple): print("Arguments are :") for i in vartuple: print(i) printargs(10, 20) printargs(10, 20, 30) Output: Arguments are : 10 20 Arguments are : 10 20 30

3.2 ANONYMOUS FUNCTIONS (LAMBDA FUNCTIONS)

A function is said to be an anonymous function when it is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using lambda keyword.

Syntax: lambda [arg1 [,arg2,.....argn]]:expression Lambda forms can take any number of arguments but return just one value in the form of

an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an

expression. Lambda functions have their own local namespace and cannot access variables other than

those in their parameter list and those in the global namespace. Example: add = lambda arg1, arg2: arg1 + arg2 print("Sum =", add(10, 20)) Output: Sum = 30

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

3.3 SCOPE OF VARIABLES

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

Global variables Local variables

3.3.1 Global vs. Local Variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example:

total = 0 # This is global variable. def add(arg1, arg2): total = arg1 + arg2; # Here total is local variable. print ("Inside the function local total :", total) return total add(10, 20) print("Outside the function global total :", total ) Output: Inside the function local total : 30 Outside the function global total : 0 To assign to global variables (or variables which can be accessed from outside the

function), we need to use the global statement. We could redefine the add function as shown below:

total = 0 # This is global variable. def add(arg1, arg2): global total total = arg1 + arg2; # Here total is global variable. print ("Inside the function global total :", total) return total add(10, 20) print("Outside the function global total :", total ) Output: Inside the function local total : 30 Outside the function global total : 30

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

REVIEW QUESTIONS 1. What are keyword arguments? 2. What do you mean by default arguments? 3. What do you mean by required arguments? 4. Explain with an example the execution of variable-length arguments. 5. What are lambda functions? 6. What are the characteristics of anonymous functions? 7. What are the applications of lambda functions?

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to find the sum of any number of arguments.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

CHAPTER - 4 - BUILT-IN FUNCTIONS 4.1 INTRODUCTION

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set() 4.2 abs(x)

Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.

Example: >>> n = -42 >>> abs(n) 42 >>> c = (3 - 4j) >>> abs(c) 5.0

4.3 bin(x)

Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression.

Example: >>> n = 5 >>> bin(5) '0b101'

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4.4 bool([x])

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True.

Example: >>> n = 0 >>> bool(n) False >>> n = 10 >>> bool(n) True >>> s = 'REC' >>> bool(s) True

4.5 chr(i)

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

Example: >>> chr(98) 'b' >>> chr(66) 'B' >>> chr(-1) ValueError: chr() arg not in range(0x110000)

4.6 divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 31

Example: >>> n = 10 >>> d = 3 >>> divmod(n, d) (3, 1)

4.7 eval(expression, globals=None, locals=None)

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.

Example:

>>> n = 3 >>> eval('n + 2') 5

4.8 float([x])

Return a floating point number constructed from a number or string x. Example: >>> n = 6 >>> float(n) 6.0 >>> pi = '3.14' >>> float(pi) 3.14

4.9 hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. Example: >>> n = 10 >>> hex(n) '0xa' >>> n = 16 >>> hex(n) '0x10'

4.10 id(object)

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

32 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Example: >>> a = 6 >>> id(a) 1546479824 >>> b = a >>> id(b) 1546479824 >>> c = 6.0 >>> id(c) 43433728

4.11 input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Example: >>> s = input() REC >>> print(s) REC >>> s = input('Enter the string : ') Enter the string : REC >>> print(s) REC

4.12 int(x=0)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

Example: >>> n = 3.14 >>> int(n) 3 >>> s = '6' >>> int(s) 6

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 33

4.13 len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Example: >>> s = 'REC' >>> len(s) 3 >>> n = list(range(10)) >>> len(n) 10

4.14 max()

Return the largest item in an iterable or the largest of two or more arguments.

Example: >>> max(1, 3, 2, 5, 4) 5

4.15 min() Return the smallest item in an iterable or the smallest of two or more arguments.

Example: >>> min(1, 3, 2, 5, 4) 1

4.16 oct(x)

Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression.

Example: >>> n = 8 >>> oct(8) '0o10' >>> n = 10 >>> oct(10) '0o12'

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4.17 ord(c)

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

Example: >>> s = 'b' >>> ord(s) 98 >>> s = 'B' >>> ord(s) 66

4.18 pow(x, y[, z])

Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x,y) is equivalent to using the power operator: x**y.

Example: >>> x = 2 >>> y = 3 >>> z = 5 >>> pow(x, y) 8 >>> pow(x, y, z) 3

4.19 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.

Example: >>> a = 10 >>> b = 20 >>> print(a, b) 10 20 >>> print(a, b, sep = '\t') 10 20 >>> print(a, b, sep = '\n') 10 20

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 35

4.20 range(stop) range(start, stop[, step])

Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

Example: >>> print(list(range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print(list(range(1, 10))) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print(list(range(1, 10, 2))) [1, 3, 5, 7, 9]

4.21 round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Example:

>>> round(3.14) 3 >>> round(5.5) 6 >>> round(3.14159, 4) 3.1416 For the built-in types supporting round(), values are rounded to the closest multiple of 10

to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67

instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4.22 sorted(iterable, *, key=None, reverse=False)

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments. key specifies a function of one argument that is used to extract a comparison key from

each list element: key=str.lower. The default value is None(compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Example: >>> s = 'CSE' >>> sorted(s) ['C', 'E', 'S'] >>> sorted(s, reverse = True) ['S', 'E', 'C']

4.23 type(object)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

Example: >>> n = 10 >>> type(n) <class 'int'> >>> pi = 3.14 >>> type(pi) <class 'float'> >>> s = 'REC' >>> type(s) <class 'str'>

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 37

REVIEW QUESTIONS 1. List any three Python built-in functions.

38 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to print the ASCII table.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 39

CHAPTER - 5 - STRINGS 5.1 INTRODUCTION

Strings are not like integers, floats, and booleans. A string is a sequence, which means it is an ordered collection of other values. 5.2 A STRING IS A SEQUENCE

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana' >>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

The expression in brackets is called an index. The index indicates which character in the

sequence you want (hence the name).

But you might not get what you expect: >>> letter 'a'

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the

index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0] >>> letter 'b'

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the

2th letter (“two-eth”).

As an index, you can use an expression that contains variables and operators:

>>> i = 1 >>> fruit[i] 'a' >>> fruit[i+1] 'n'

But the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5] TypeError: string indices must be integers

40 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

5.3 len

len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana' >>> len(fruit) 6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range

The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since

we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

>>> last = fruit[length-1] >>> last 'a'

Or you can use negative indices, which count backward from the end of the string. The

expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. 5.4 TRAVERSAL WITH A for LOOP

A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1

This loop traverses the string and displays each letter on a line by itself. The loop condition

is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop doesn’t run. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.

As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line.

Another way to write a traversal is with a for loop:

for letter in fruit: print(letter)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 41

Each time through the loop, the next character in the string is assigned to the variable letter. The loop continues until no characters are left.

The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:

prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: print(letter + suffix)

The output is: Jack Kack Lack Mack Nack Oack Pack Qack

Of course, that’s not quite right because “Ouack” and “Quack” are misspelled. As an

exercise, modify the program to fix this error. 5.5. STRING SLICES

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python'

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”

character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure 5-1.

Figure 5-1. Slice indices.

42 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:

>>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana'

If the first index is greater than or equal to the second the result is an empty string,

represented by two quotation marks:

>>> fruit = 'banana' >>> fruit[3:3] ''

An empty string contains no characters and has length 0, but other than that, it is the same

as any other string.

Continuing this example, what do you think fruit[:] means? Try it and see. 5.6 STRINGS ARE IMMUTABLE

It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:

>>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment The “object” in this case is the string and the “item” is the character you tried to assign. For

now, an object is the same thing as a value, but we will refine that definition later (“Objects and Values”).

The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

>>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> new_greeting 'Jello, world!'

This example concatenates a new first letter onto a slice of greeting. It has no effect on the

original string.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 43

5.7 SEARCHING

What does the following function do? def find(word, letter): index = 0 while index < len(word): if word[index] == letter: return index index = index + 1 return -1

In a sense, find is the inverse of the [] operator. Instead of taking an index and extracting

the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.

This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately.

If the character doesn’t appear in the string, the program exits the loop normally and returns -1.

This pattern of computation—traversing a sequence and returning when we find what we are looking for-is called a search.

As an exercise, modify find so that it has a third parameter: the index in word where it should start looking. 5.8 LOOPING AND COUNTING

The following program counts the number of times the letter a appears in a string:

word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count)

This program demonstrates another pattern of computation called a counter. The

variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result-the total number of a’s.

As an exercise, encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.

Then rewrite the function so that instead of traversing the string, it uses the three-parameter version of find from the previous section.

44 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

5.9 STRING METHODS

Strings provide methods that perform a variety of useful operations. A method is similar to a function-it takes arguments and returns a value-but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters.

Instead of the function syntax upper(word), it uses the method syntax word.upper(): >>> word = 'banana' >>> new_word = word.upper() >>> new_word 'BANANA'

This form of dot notation specifies the name of the method, upper, and the name of the

string to apply the method to, word. The empty parentheses indicate that this method takes no arguments.

A method call is called an invocation; in this case, we would say that we are invoking upper on word.

As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana' >>> index = word.find('a') >>> index 1

In this example, we invoke find on word and pass the letter we are looking for as a

parameter.

Actually, the find method is more general than our function; it can find substrings, not just characters:

>>> word.find('na') 2

By default, find starts at the beginning of the string, but it can take a second argument, the

index where it should start:

>>> word.find('na', 3) 4

This is an example of an optional argument. find can also take a third argument, the index

where it should stop:

>>> name = 'bob' >>> name.find('b', 1, 2) -1

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 45

This search fails because b does not appear in the index range from 1 to 2, not including 2. Searching up to, but not including, the second index makes find consistent with the slice operator. 5.10 THE in OPERATOR

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana' True >>> 'seed' in 'banana' False

For example, the following function prints all the letters from word1 that also appear

in word2:

def in_both(word1, word2): for letter in word1: if letter in word2: print(letter)

With well-chosen variable names, Python sometimes reads like English. You could read this

loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges') a e s

5.11 STRING COMPARISON

The relational operators work on strings. To see if two strings are equal:

if word == 'banana': print('All right, bananas.')

Other relational operations are useful for putting words in alphabetical order:

if word < 'banana': print('Your word, ' + word + ', comes before banana.') elif word > 'banana': print('Your word, ' + word + ', comes after banana.') else: print('All right, bananas.')

46 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Python does not handle uppercase and lowercase letters the same way people do. All the uppercase letters come before all the lowercase letters, so:

Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a standard format, such as

all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple. 5.11 ADDITIONAL STRING METHODS 5.11.1 str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased. Example:

s = "python programming" print(s.capitalize())

Output:

Python programming 5.11.2 str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Example:

s = "python programming" print(s.count("a"))

Output: 1

5.11.3 str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Example:

s = "python programming" print(s.endswith("ing")) print(s.endswith("ogy"))

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 47

Output:

True False

5.11.4 str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The find() method should be used only if you need to know the position of sub.

Example: s = "python programming" print(s.find("on")) print(s.find("va")) Output:

4 -1

5.11.5 str.index(sub[, start[, end]])

Like find(), but raise ValueError when the substring is not found.

Example: s = "python programming" print(s.index("on")) print(s.index("va")) Output:

4

ValueError: substring not found 5.11.6 str.isalnum()

Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

Example: s = "GE17151" p = "Thandalam - 602105" print(s.isalnum()) print(p.isalnum())

48 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Output:

True False

5.11.7 str.isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

Example: s = "PSPP" p = "Python Programming" print(s.isalpha()) print(p.isalpha()) Output:

True False

5.11.8 str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

Example: s = "Thandalam" p = "602105" print(s.isdigit()) print(p.isdigit()) Output:

False True

5.11.9 str.islower()

Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.

Example: s = "python programming" p = "CSE Lab"

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 49

print(s.islower()) print(p.islower()) Output:

True False

5.11.10 str.isnumeric()

Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

Example: s = "Thandalam" p = "602105" print(s.isnumeric()) print(p.isnumeric()) Output:

False True

5.11.11 str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. Whitespace characters are those characters defined in the Unicode character database as “Other” or “Separator” and those with bidirectional property being one of “WS”, “B”, or “S”.

Example: s = "python programming" p = " " print(s.isspace()) print(p.isspace()) Output:

False True

50 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

5.11.12 str.istitle()

Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.

Example: s = "python programming" p = "Computer Lab" t = "CSE Department" print(s.istitle()) print(p.istitle()) print(t.istitle()) Output:

False True False

5.11.13 str.isupper()

Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise.

Example: s = "python programming" p = "PSPP" t = "CSE Lab" print(s.isupper()) print(p.isupper()) print(t.isupper()) Output:

False True False

5.11.14 str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytesobjects. The separator between elements is the string providing this method.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 51

Example: sep = "-" phone = ("91", "44", "37181111") print (sep.join(phone)) Output:

91-44-37181111

5.11.15 str.lower()

Return a copy of the string with all the cased characters [4] converted to lowercase. The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.

Example: s = "python programming" p = "PSPP" t = "CSE Lab" print(s.lower()) print(p.lower()) print(t.lower()) Output:

python programming pspp cse lab

5.11.16 str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Example: s = "python programming" print(s.replace("python", "java")) Output:

java programming

5.11.17 str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

52 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit

empty strings (for example, '1,,2'.split(',') returns ['1','', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

Example: phone = "91-44-37181111" print(phone.split("-")) Output:

['91', '44', '37181111']

5.11.18 str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

Example: s = "python programming" print(s.startswith("py")) print(s.startswith("ja"))

Output:

True False

5.11.19 str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.

Example: s = "python programming" p = "CSE Lab" print(s.swapcase()) print(p.swapcase())

Output:

PYTHON PROGRAMMING cse lAB

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 53

5.11.20 str.title()

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

Example: s = "python programming" p = "CSE Lab" print(s.title()) print(p.title())

Output:

Python Programming Cse Lab

5.11.21 str.upper()

Return a copy of the string with all the cased characters converted to uppercase.

Example: s = "python programming" p = "PSPP" print(s.upper()) print(p.upper())

Output:

PYTHON PROGRAMMING PSPP

54 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

REVIEW QUESTIONS 1. Define String. 2. Explain how to initialize string variable with suitable example. 3. Explain how to access string variable with suitable example. 4. Explain string indexing in Python. 5. Explain the purpose of slicing string in Python. 6. Define string concatenation. 7. Explain replication operator in Python with suitable examples. 8. Define Control characters. 9. Explain Escape sequences in Python. 10. What is the purpose of ‘0’ format symbol in Python? 11. Explain the syntax of format method with suitable examples. 12. Explain the string built-in function len() with an example. 13. Briefly explain the various string methods in Python. 14. Explain string module with suitable example. 15. Differentiate string module and methods in Python. 16. Write a Python function that takes a list of words and returns the length of the longest one. 17. Write a Python script that takes input from the user and displays that input back in upper and

lower cases. 18. Write a Python function to insert a string in the middle of a string. 19. Write a Python program to remove a new line in Python. 20. Write a Python program to count occurrences of a substring in a string.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 55

PROGRAMMING EXERCISES 1. Develop a Python program to print the alphabets with ASCII values. 2. Develop a Python program to check the given character is vowel or not. 3. Develop a Python program to find the length of the given string. 4. Develop a Python program to find a character is no./letter/special character. 5. Develop a Python program to convert uppercase characters to lowercase. 6. Develop a Python program to print the number of vowels in a given paragraph. 7. Develop a Python program to concatenate the given two strings. 8. Develop a Python program to count the number of occurrence of a character in a string. 9. Develop a Python program to reverse a given string. 10. Develop a Python program to check whether a string is a palindrome or not and print the

result. 11. Develop a Python program for finding string length, string concatenation, string comparison

and string copy without using library function. 12. Develop a Python program to copy 4 characters of a character array from the 4th position in

another character array. 13. Develop a Python program to copy one string into another and count the number of characters

copied. 14. Develop a Python program to display all ASCII numbers and their equivalent characters,

numbers and symbols using while loops. User should prompt every time to press ‘Y’ or ‘N’, if user press ‘Y’ display the next alphabet. Otherwise terminate the program. Test your program and report the results obtained.

15. Develop a Python program to count the number of lines, vowels, consonants, words of a given text.

16. Develop a Python program for finding string length, string concatenation, string comparison and string copy using library function.

17. Develop a Python program to sort ‘N’ names alphabetically. 18. Develop a Python program to find whether a substring is present in the string or not. 19. Develop a Python program to accept a line of text and to print the number of vowels,

consonants, digits and whitespaces. 20. Develop a Python program to find the day of the given date.

56 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Develop a Python program using function to compute the factorial of a given number. Program: def factorial(n): fact = 1 for i in range(1, n + 1): fact = fact * i return fact n = int(input("Enter the number : ")) print("The factorial of", n, "is", factorial(n)) Output: Enter the number : 5 The factorial of 5 is 120

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find maximum of given three numbers using parameter passing. Program: def maximum(a, b, c): if(a > b and a > c): return a elif(b > a and b > c): return b; else: return c; a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) c = int(input("Enter the third number : ")) print("The maximum number is", maximum(a, b, c)) Output: Enter the first number : 20 Enter the second number : 30 Enter the third number : 10 The maximum number is 30

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Develop a Python program to find minimum of given three numbers using parameter passing. Program: def minimum(a, b, c): if(a < b and a < c): return a elif(b < a and b < c): return b; else: return c; a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) c = int(input("Enter the third number : ")) print("The minimum number is", minimum(a, b, c)) Output: Enter the first number : 20 Enter the second number : 30 Enter the third number : 10 The minimum number is 10

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the sum of ‘N’ natural number using function. Program: def sumofn(n): s = 0 for i in range(1, n + 1): s = s + i return s n = int(input("Enter the number of elements : ")) son = sumofn(n) print("The sum of first", n, "number is", son) Output: Enter the number of elements : 5 The sum of first 5 number is 15

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Develop a Python program to find the square and cube of a number using a function declaration using the return statement. Program: def square(n): return n * n def cube(n): return n * n * n n = int(input("Enter the number : ")) s = square(n) c = cube(n) print("Square :", s, "Cube :", c) Output: Enter the number : 2 Square : 4 Cube : 8

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the given number as an Armstrong number or not using user defined function. Program: def armstrong(n): s = 0 while(n > 0): rem = n % 10 s = s + (rem ** 3) n = n // 10 return s n = int(input("Enter the number : ")) a = armstrong(n) if(a == n): print(n, "is an Armstrong number") else: print(n, "is not an Armstrong number") Output: Enter the number : 153 153 is an Armstrong number Enter the number : 123 123 is not an Armstrong number

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Develop a Python program using functions that will compute and print the area of any four geometric shapes. Write a main function to get the input and invoke the function using conditional statement. Program: def circle(r): a = 3.14 * r ** 2 return a def rectangle(l, b): a = l * b return a def triangle(b, h): a = 0.5 * b * h return a def square(s): a = s * s return a print("1.Circle\n2.Rectangle\n3.Triangle\n4.Square") choice = int(input("Enter your choice : ")) if choice == 1: radius = float(input("Enter the radius : ")) area = circle(radius) print("Area of circle =", area) elif choice == 2: length = float(input("Enter the breadth : ")) breadth = float(input("Enter the breadth : ")) area = rectangle(length, breadth) print("Area of rectangle =", area) elif choice == 3: base = float(input("Enter the base : ")) height = float(input("Enter the height : ")) area = triangle(base, height) print("Area of triangle =", area) elif choice == 4: side = float(input("Enter the side : ")) area = square(side) print("Area of square =", area) else: print("Invalid choice...!")

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Output: 1.Circle 2.Rectangle 3.Triangle 4.Square Enter your choice : 1 Enter the radius : 5 Area of circle = 78.5 1.Circle 2.Rectangle 3.Triangle 4.Square Enter your choice : 2 Enter the breadth : 3 Enter the breadth : 4 Area of rectangle = 12.0 1.Circle 2.Rectangle 3.Triangle 4.Square Enter your choice : 3 Enter the base : 5 Enter the height : 2 Area of triangle = 5.0 1.Circle 2.Rectangle 3.Triangle 4.Square Enter your choice : 4 Enter the side : 5 Area of square = 25.0 1.Circle 2.Rectangle 3.Triangle 4.Square Enter your choice : 5 Invalid choice...!

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

Develop a Python program to find the second largest digit from a number using function. Program: def second(n): a = 0 b = 0 while(n > 0): r = n % 10 if(r > a): b = a a = r elif(r > b): b = r; n = n // 10; return b; n = int(input("Enter the number : ")) s = second(n) print("The second largest digit is :", s) Output: Enter the number : 1983 The second largest digit is : 8

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the sum of digits of a number using function. Program: def sumofdigits(n): s = 0 while(n > 0): rem = n % 10 s = s + rem n = n // 10 return s n = int(input("Enter the number : ")) sod = sumofdigits(n) print("The sum of the digits =", sod) Output: Enter the number : 786 The sum of the digits = 21

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

Develop a Python program using function, to reverse the digits of a given number. Program: def revofnum(n): rev = 0 while(n > 0): rem = n % 10 rev = rem + (rev * 10) n = n // 10 return rev n = int(input("Enter the number : ")) ron = revofnum(n) print("The reversed number =", ron) Output: Enter the number : 2468 The reversed number = 8642

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program using function, to check whether the given number and its reverse are same. Program: def revofnum(n): rev = 0 while(n > 0): rem = n % 10 rev = rem + (rev * 10) n = n // 10 return rev n = int(input("Enter the number : ")) ron = revofnum(n) if(ron == n): print("The number and its reverse are same") else: print("The number and its reverse are not same") Output: Enter the number : 143 The number and its reverse are not same Enter the number : 141 The number and its reverse are same

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

Develop a Python program to find the sum of square of individual digits of a number using function. Program: def sumsquare(n): s = 0 while(n > 0): rem = n % 10 s = s + (rem * rem) n = n // 10 return s n = int(input("Enter the number : ")) sos = sumsquare(n) print("Sum of square of individual digits is =", sos) Output: Enter the number : 124 Sum of square of individual digits is = 21

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the largest digit from a number using function. Program: def largest(n): large = 0 while(n > 0): rem = n % 10 if(rem > large): large = rem n = n // 10 return large n = int(input("Enter the number : ")) ld = largest(n) print("The largest digit =", ld) Output: Enter the number : 786 The largest digit = 8

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

Develop a Python program to find the smallest digit from a number using function. Program: def smallest(n): small = 9 while(n > 0): rem = n % 10 if(rem < small): small = rem n = n // 10 return small n = int(input("Enter the number : ")) sd = smallest(n) print("The smallest digit =", sd) Output: Enter the number : 786 The smallest digit = 6

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the absolute value of the number without using abs function. Program: def absval(x): if x < 0: return -x else: return x n = int(input("Enter the number : ")) print("Absolute value of", n, "is", absval(n)) Output: Enter the number : 2 Absolute value of 2 is 2 Enter the number : -14 Absolute value of -14 is 14

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

Develop a Python program to find the factorial of a number using recursive function. Program: def factorial(n): if (n == 0 or n == 1): return 1; else: return(n * factorial(n - 1)); n = int(input("Enter the number : ")) fact = factorial(n) print("The factorial of", n, "is", fact) Output: Enter the number : 5 The factorial of 5 is 120

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print the Fibonacci series using recursion. Program: def fibonacci(n): if(n == 0 or n == 1): return n else: return fibonacci(n - 1) + fibonacci(n - 2) n = int(input("Enter the number of terms : ")) for i in range(n): print(fibonacci(i), end = " ") Output: Enter the number of terms : 10 0 1 1 2 3 5 8 13 21 34

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

Develop a Python program to find nCr using recursive function. Program: def factorial(n): if (n == 0 or n == 1): return 1; else: return(n * factorial(n - 1)); n = int(input("Enter the value for n : ")) r = int(input("Enter the value for r : ")) if n >= r: ncr = factorial(n) / (factorial(n - r) * factorial(r)) print("The NCR value is :", ncr) else: print("Calculating NCR value is not possible") Output: Enter the value for n : 7 Enter the value for r : 5 The NCR value is : 21.0 Enter the value for n : 5 Enter the value for r : 7 Calculating NCR value is not possible

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to find the sum of numbers up to n using recursive function. Program: def sumofnum(n): if (n <= 1): return n else: return n + sumofnum(n - 1) n = int(input("Enter the value for n : ")) son = sumofnum(n) print("The sum is :", son) Output: Enter the value for n : 10 The sum is : 55

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

Develop a Python program to accept a word from the user and reverse it without using any string modules. Program: s = input("Enter the string : ") r = "" for i in range(len(s) - 1, -1, -1): r = r + s[i] print("The reversed string is :", r) Output: Enter the string : Python The reversed string is : nohtyP

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program that accepts a string and count the number of digits, letters and other characters. Program: s = input("Enter the string : ") digits = 0 letters = 0 others = 0 for c in s: if c.isdigit(): digits = digits + 1 elif c.isalpha(): letters = letters + 1 else: others = others + 1 print("Digits : ", digits) print("Letters : ", letters) print("Other characters : ", others) Output: Enter the string : Thandalam - 602 105 Digits : 6 Letters : 9 Other characters : 4

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

Develop a Python program to count the number of vowels in the given string. Program: s = input("Enter the string : ") count = 0 for c in s: if c in 'aeiouAEIOU': count = count + 1 print("Number of vowels : ", count) Output: Enter the string : Rajalakshmi Number of vowels : 4

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to using function to print all the letters from word1 that also appear in word2: Program: def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) a = input("Enter the first word : ") b = input("Enter the second word : ") in_both(a, b) Output: Enter the first word : apples Enter the second word : oranges a e s

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

Develop a Python program to calculate the length of a string without using a built-in function. Program: s = input("Enter the string : ") count = 0 for i in s: count = count + 1 print("Length of the string :", count) Output: Enter the string : Rajalakshmi Length of the string : 11

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to calculate the number of upper case letters and lower case letters in a string. Program: s = input("Enter the string : ") upper = 0 lower = 0 for c in s: if c.isupper(): upper = upper + 1 elif c.islower(): lower = lower + 1 print("Upper case letters : ", upper) print("Lower case letters : ", lower) Output: Enter the string : Rajalakshmi Engineering College Upper case letters : 3 Lower case letters : 26

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

Develop a Python program that takes input from the user and displays that input back in upper and lower cases. Program: s = input("Enter the string : ") print("String in upper case : ", s.upper()) print("String in lower case : ", s.lower()) Output: Enter the string : Rajalakshmi String in upper case : RAJALAKSHMI String in lower case : rajalakshmi

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - III Part - B

Question Bank 1. Define function.

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name. 2. What are the types of functions? (or) Mention the types of functions available in Python.

There are two types of functions:

• Built-in functions • User-defined functions

3. What is function definition? Give syntax.

A function definition specifies the name of a new function and the sequence of statements

that run when the function is called.

Syntax:

def function_name(parameters): """docstring""" statement(s)

4. What are the elements of function definition? 1. def is a keyword that indicates that this is a function definition. 2. The name of the function. 3. The empty parentheses after the name indicate that this function doesn’t take any

arguments. 4. The first line of the function definition is called the header; the rest is called the body.

The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.

5. What is function’s flow of execution?

To ensure that a function is defined before its first use, you have to know the order

statements run in, which is called the flow of execution.

Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Function definitions do not alter the flow of execution of the program, but remember that statements inside the function don’t run until the function is called.

A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off. 6. List the advantages of functions in Python.

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

Creating a new function gives you an opportunity to name a group of statements,

which makes your program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Later, if you

make a change, you only have to make it in one place. Dividing a long program into functions allows you to debug the parts one at a time and

then assemble them into a working whole. Well-designed functions are often useful for many programs. Once you write and

debug one, you can reuse it. 7. What is the purpose of a return statement?

Calling the function generates a return value, which we usually assign to a variable or use as part of an expression.

The example is area, which returns the area of a circle with the given radius: def area(radius): a = math.pi * radius**2 return a

In a fruitful function the return statement includes an expression. This statement means:

“Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely:

def area(radius): return math.pi * radius**2

8. What is recursion? Give example.

A function that calls itself is recursive; the process of executing it is called recursion. For example, we can write a function that prints a string n times:

def print_n(s, n): if n <= 0: return print(s) print_n(s, n-1)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

9. What do you mean by required arguments? Give example. Required arguments are the arguments passed to a function in correct positional order.

Here, the number of arguments in the function call should match exactly with the function definition. Example:

def printme(s): print(s) printme()

To call the function printme(), you definitely need to pass one argument, otherwise it gives

a syntax error as follows: Traceback (most recent call last): printme() TypeError: printme() missing 1 required positional argument: 's'

10. What are keyword arguments? Give example. Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

Example: def printinfo(name, age): print ("Name :", name) print ("Age :", age) printinfo(age = 19, name = "Arun") Output: Name : Arun Age : 19

11. What do you mean by default arguments? Give example.

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed:

def printinfo(name, age = 19): print ("Name :", name) print ("Age :", age) printinfo("Arun", 20) printinfo("Babu")

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Output: Name : Arun

Age : 20 Name : Babu Age : 19

12. Explain with an example the execution of variable-length arguments.

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:

def printargs(*vartuple): print("Arguments are :") for i in vartuple: print(i) printargs(10, 20)

printargs(10, 20, 30) Output: Arguments are : 10 20 Arguments are : 10 20 30

13. What are lambda functions?

A function is said to be an anonymous function when it is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using lambda keyword.

Syntax: lambda [arg1 [,arg2,.....argn]]:expression

14. What are the characteristics of anonymous functions?

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

An anonymous function cannot be a direct call to print because lambda requires an expression.

Lambda functions have their own local namespace and cannot access variables other than

those in their parameter list and those in the global namespace.

15. List the Python built-in functions.

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set() 16. Define String.

Strings are not like integers, floats, and booleans. A string is a sequence, which means it is an ordered collection of other values. 17. Explain how to initialize string variable with suitable example.

A string can be initialized by using an assignment statement where it is enclosed in pair of single or double or triple quotes.

>>> fruit = 'banana'

18. Explain how to access string variable with suitable example.

A string is a sequence of characters. You can access the characters one at a time with the

bracket operator:

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> fruit = 'banana' >>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

19. Explain string indexing in Python.

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana' >>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

The expression in brackets is called an index. The index indicates which character in the

sequence you want (hence the name).

But you might not get what you expect: >>> letter 'a'

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the

index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0] >>> letter 'b'

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the

2th letter (“two-eth”).

20. Explain the string built-in function len() with an example.

len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana' >>> len(fruit) 6

21. Explain the purpose of slicing string in Python.

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python' >>> s[0:5] 'Monty'

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

>>> s[6:12] 'Python'

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”

character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure.

22. Define string concatenation.

The + operator performs string concatenation, which means it joins the strings by linking them end-to-end. For example:

>>> first = 'throat' >>> second = 'warbler' >>> first + second throatwarbler

23. Explain replication operator in Python with suitable examples.

The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the values is a string, the other has to be an integer. 24. Explain the features of “in” operator for string in Python with suitable example.

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana' True >>> 'seed' in 'banana' False

For example, the following function prints all the letters from word1 that also appear

in word2:

def in_both(word1, word2): for letter in word1: if letter in word2: print(letter)

With well-chosen variable names, Python sometimes reads like English. You could read this

loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges') a e s

25. Define the scope of variable.

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. 26. How variables are categorized in Python?

There are two basic scopes of variables in Python: Global variables Local variables

27. Differentiate between local and global variables.

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are

declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - III Part - B

Question Bank 1. Briefly explain the function definition and function calling in Python.

So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that run when the function is called. Syntax

def function_name(parameters): """docstring""" statement(s)

Here is an example:

def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.")

def is a keyword that indicates that this is a function definition. The name of the function

is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and underscore are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

The empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.

The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.

All quotation marks (single and double) must be “straight quotes”, usually located next to Enter on the keyboard. “Curly quotes”, like the ones in this sentence, are not legal in Python.

If you type a function definition in interactive mode, the interpreter prints dots (...) to let you know that the definition isn’t complete:

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> def print_lyrics(): ... print("I'm a lumberjack, and I'm okay.") ... print("I sleep all night and I work all day.") ... To end the function, you have to enter an empty line.

Defining a function creates a function object, which has type function: >>> print(print_lyrics) <function print_lyrics at 0x000001D41AD82EA0> >>> type(print_lyrics) <class 'function'>

The syntax for calling the new function is the same as for built-in functions:

>>> print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

Once you have defined a function, you can use it inside another function. For example, to

repeat the previous refrain, we could write a function called repeat_lyrics: def repeat_lyrics(): print_lyrics() print_lyrics()

And then call repeat_lyrics:

>>> repeat_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

2. Illustrate with an example, the working of recursive functions.

It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do.

A function that calls itself is recursive; the process of executing it is called recursion.

If you looked up the definition of the factorial function, denoted with the symbol !, you

might get something like this: 0! = 1

n! = n(n-1)!

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

This definition says that the factorial of 0 is 1, and the factorial of any other value, n, is n multiplied by the factorial of n-1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6.

If you can write a recursive definition of something, you can write a Python program to

evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that factorial takes an integer:

def factorial(n):

If the argument happens to be 0, all we have to do is return 1: def factorial(n): if n == 0: return 1

Otherwise, and this is the interesting part, we have to make a recursive call to find the

factorial of n-1 and then multiply it by n:

def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result

The flow of execution for this program is similar to the flow of countdown in “Recursion”. If

we call factorial with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of n-1... Since 2 is not 0, we take the second branch and calculate the factorial of n-1... Since 1 is not 0, we take the second branch and calculate the factorial of n-1...

Since 0 equals 0, we take the first branch and return 1 without making any more recursive

calls.

The return value, 1, is multiplied by n, which is 1, and the result is returned.

The return value, 1, is multiplied by n, which is 2, and the result is returned. The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return

value of the function call that started the whole process. Figure shows what the stack diagram looks like for this sequence of function calls.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Figure 2-1. Stack diagram. The return values are shown being passed back up the stack. In each frame, the return

value is the value of result, which is the product of n and recurse.

In the last frame, the local variables recurse and result do not exist, because the branch that creates them does not run. 3. Explain in detail about strings in Python.

Strings are not like integers, floats, and booleans. A string is a sequence, which means it is an ordered collection of other values. A String is a Sequence

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana' >>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

The expression in brackets is called an index. The index indicates which character in the

sequence you want (hence the name).

But you might not get what you expect: >>> letter 'a'

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the

index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0] >>> letter 'b'

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th letter (“two-eth”).

As an index, you can use an expression that contains variables and operators:

>>> i = 1 >>> fruit[i] 'a' >>> fruit[i+1] 'n'

But the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5] TypeError: string indices must be integers

4. Explain the purpose of slicing string in Python with suitable example.

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python'

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”

character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure.

Figure. Slice indices.

If you omit the first index (before the colon), the slice starts at the beginning of the string.

If you omit the second index, the slice goes to the end of the string: >>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana'

If the first index is greater than or equal to the second the result is an empty string,

represented by two quotation marks:

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> fruit = 'banana' >>> fruit[3:3] ''

An empty string contains no characters and has length 0, but other than that, it is the same

as any other string.

Continuing this example, what do you think fruit[:] means? Try it and see. 5. Briefly explain the various string methods in Python. str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased. Example:

s = "python programming" print(s.capitalize())

Output:

Python programming str.count()

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Example:

s = "python programming" print(s.count("a"))

Output: 1

str.endswith()

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Example:

s = "python programming" print(s.endswith("ing")) print(s.endswith("ogy"))

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Output:

True False

str.find()

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The find() method should be used only if you need to know the position of sub.

Example: s = "python programming" print(s.find("on")) print(s.find("va")) Output:

4 -1

str.index()

Like find(), but raise ValueError when the substring is not found.

Example: s = "python programming" print(s.index("on")) print(s.index("va")) Output:

4

ValueError: substring not found str.lower()

Return a copy of the string with all the cased characters [4] converted to lowercase. The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.

Example: s = "python programming" p = "PSPP" t = "CSE Lab" print(s.lower())

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

print(p.lower()) print(t.lower()) Output:

python programming pspp cse lab

str.replace()

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Example: s = "python programming" print(s.replace("python", "java")) Output:

java programming

str.startswith()

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

Example: s = "python programming" print(s.startswith("py")) print(s.startswith("ja"))

Output:

True False

str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.

Example: s = "python programming" p = "CSE Lab" print(s.swapcase())

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

print(p.swapcase())

Output:

PYTHON PROGRAMMING cse lAB

5.11.20 str.title()

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

Example: s = "python programming" p = "CSE Lab" print(s.title()) print(p.title())

Output:

Python Programming Cse Lab

5.11.21 str.upper()

Return a copy of the string with all the cased characters converted to uppercase.

Example: s = "python programming" p = "PSPP" print(s.upper()) print(p.upper())

Output:

PYTHON PROGRAMMING PSPP

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - III Part - C

Question Bank 1. Explain the type conversion functions.

We have already seen one example of a function call:

>>> type(42) <class 'int'>

The name of the function is type. The expression in parentheses is called the argument of

the function. The result, for this function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is also called the return value.

Python provides functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

>>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int() with base 10: 'Hello'

int can convert floating-point values to integers, but it doesn’t round off; it chops off the

fraction part:

>>> int(3.99999) 3 >>> int(-2.3) -2

float converts integers and strings to floating-point numbers:

>>> float(32) 32.0 >>> float('3.14159') 3.14159

Finally, str converts its argument to a string:

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> str(32) '32' >>> str(3.14159) '3.14159'

2. Briefly explain the math functions.

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.

Before we can use the functions in a module, we have to import it with an import statement:

>>> import math This statement creates a module object named math. If you display the module object, you

get some information about it:

>>> math <module 'math' (built-in)>

The module object contains the functions and variables defined in the module. To access

one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians)

The first example uses math.log10 to compute a signal-to-noise ratio in decibels (assuming

that signal_power and noise_power are defined). The math module also provides log, which computes logarithms base e.

The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 180 and multiply by π:

>>> degrees = 45 >>> radians = degrees / 180.0 * math.pi >>> math.sin(radians) 0.707106781187

The expression math.pi gets the variable pi from the math module. Its value is a floating-

point approximation of π, accurate to about 15 digits.

If you know trigonometry, you can check the previous result by comparing it to the square root of 2 divided by 2:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

>>> math.sqrt(2) / 2.0 0.707106781187

3. Briefly explain the function definition and function calling in Python.

So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that run when the function is called. Syntax

def function_name(parameters): """docstring""" statement(s)

Here is an example:

def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.")

def is a keyword that indicates that this is a function definition. The name of the function

is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and underscore are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

The empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.

The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.

All quotation marks (single and double) must be “straight quotes”, usually located next to Enter on the keyboard. “Curly quotes”, like the ones in this sentence, are not legal in Python.

If you type a function definition in interactive mode, the interpreter prints dots (...) to let you know that the definition isn’t complete:

>>> def print_lyrics(): ... print("I'm a lumberjack, and I'm okay.") ... print("I sleep all night and I work all day.") ... To end the function, you have to enter an empty line.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Defining a function creates a function object, which has type function: >>> print(print_lyrics) <function print_lyrics at 0x000001D41AD82EA0> >>> type(print_lyrics) <class 'function'>

The syntax for calling the new function is the same as for built-in functions:

>>> print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

Once you have defined a function, you can use it inside another function. For example, to

repeat the previous refrain, we could write a function called repeat_lyrics: def repeat_lyrics(): print_lyrics() print_lyrics()

And then call repeat_lyrics:

>>> repeat_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

4. What are parameters and arguments in functions?

Some of the functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent.

Inside the function, the arguments are assigned to variables called parameters. Here is a definition for a function that takes an argument:

def print_twice(bruce): print(bruce) print(bruce)

This function assigns the argument to a parameter named bruce. When the function is

called, it prints the value of the parameter (whatever it is) twice.

This function works with any value that can be printed:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

>>> print_twice('Spam') Spam Spam >>> print_twice(42) 42 42 >>> print_twice(math.pi) 3.14159265359 3.14159265359

The same rules of composition that apply to built-in functions also apply to programmer-

defined functions, so we can use any kind of expression as an argument for print_twice: >>> print_twice('Spam '*4) Spam Spam Spam Spam Spam Spam Spam Spam >>> print_twice(math.cos(math.pi))-1.0 -1.0

The argument is evaluated before the function is called, so in the examples the

expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.

You can also use a variable as an argument: >>> michael = 'Eric, the half a bee.' >>> print_twice(michael) Eric, the half a bee. Eric, the half a bee.

The name of the variable we pass as an argument (michael) has nothing to do with the

name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce. 5. Explain the return statement in Python.

Calling the function generates a return value, which we usually assign to a variable or use as part of an expression.

e = math.exp(1.0) height = radius * math.sin(radians)

The functions we have written so far are void. Speaking casually, they have no return value;

more precisely, their return value is None.

In this chapter, we are (finally) going to write fruitful functions. The first example is area, which returns the area of a circle with the given radius:

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

def area(radius): a = math.pi * radius**2 return a

We have seen the return statement before, but in a fruitful function the return statement

includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely:

def area(radius): return math.pi * radius**2

Syntax

return [expression_list] On the other hand, temporary variables like a can make debugging easier.

Sometimes it is useful to have multiple return statements, one in each branch of a

conditional:

def absolute_value(x): if x < 0: return -x else: return x

Since these return statements are in an alternative conditional, only one runs. As soon as a return statement runs, the function terminates without executing any

subsequent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.

In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example:

def absolute_value(x): if x < 0: return -x if x > 0: return x

This function is incorrect because if x happens to be 0, neither condition is true, and the

function ends without hitting a return statement. If the flow of execution gets to the end of a function, the return value is None, which is not the absolute value of 0:

>>> absolute_value(0) None

By the way, Python provides a built-in function called abs that computes absolute values.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

As an exercise, write a compare function takes two values, x and y, and returns 1 if x > y, 0 if x == y, and -1 if x < y. 6. Illustrate with an example, the working of recursive functions.

It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do.

A function that calls itself is recursive; the process of executing it is called recursion.

As another example, we can write a function that prints a string n times: def print_n(s, n): if n <= 0: return print(s) print_n(s, n-1)

If n <= 0 the return statement exits the function. The flow of execution immediately

returns to the caller, and the remaining lines of the function don’t run.

The rest of the function is similar to countdown: it displays s and then calls itself to display s n-1 additional times. So the number of lines of output is 1 + (n - 1), which adds up to n.

For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early. More Recursion

If you looked up the definition of the factorial function, denoted with the symbol !, you might get something like this:

This definition says that the factorial of 0 is 1, and the factorial of any other value, n,

is n multiplied by the factorial of n-1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6.

If you can write a recursive definition of something, you can write a Python program to

evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that factorial takes an integer:

def factorial(n):

If the argument happens to be 0, all we have to do is return 1:

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

def factorial(n): if n == 0: return 1

Otherwise, and this is the interesting part, we have to make a recursive call to find the

factorial of n-1 and then multiply it by n:

def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result

The flow of execution for this program is similar to the flow of countdown in “Recursion”. If

we call factorial with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of n-1... Since 2 is not 0, we take the second branch and calculate the factorial of n-1... Since 1 is not 0, we take the second branch and calculate the factorial of n-1...

Since 0 equals 0, we take the first branch and return 1 without making any more recursive

calls.

The return value, 1, is multiplied by n, which is 1, and the result is returned.

The return value, 1, is multiplied by n, which is 2, and the result is returned. The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return

value of the function call that started the whole process. Figure 2-1 shows what the stack diagram looks like for this sequence of function calls.

Figure 2-1. Stack diagram.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

The return values are shown being passed back up the stack. In each frame, the return value is the value of result, which is the product of n and recurse.

In the last frame, the local variables recurse and result do not exist, because the branch that creates them does not run. 7. Discuss the different argument passing mechanism in Python with suitable examples.

In Python, user-defined functions can take four different types of arguments. The argument types and their meanings, however, are pre-defined and can’t be changed. But a developer can, instead, follow these pre-defined rules to make their own custom functions. The following are the four types of arguments and their rules.

Required arguments Keyword arguments Default arguments Variable-length arguments

Required Arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. Example:

def printme(s): print(s) printme()

To call the function printme(), you definitely need to pass one argument, otherwise it gives

a syntax error as follows: Traceback (most recent call last): printme() TypeError: printme() missing 1 required positional argument: 's'

Keyword Arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

Example:

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

def printinfo(name, age): print ("Name :", name) print ("Age :", age) printinfo(age = 19, name = "Arun") Output: Name : Arun Age : 19 Note that the order of parameters does not matter. Python expects all the keyword to be

present towards the end.

Default Arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed:

def printinfo(name, age = 19): print ("Name :", name) print ("Age :", age) printinfo("Arun", 20) printinfo("Babu")

Output: Name : Arun

Age : 20 Name : Babu Age : 19

Note that when defining a function all the argument with default values should come at the end. Variable-length Arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is given below: def functionname([formal_args,] *var_args_tuple): '''function_docstring''' function_suite return [expression]

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:

def printargs(*vartuple): print("Arguments are :") for i in vartuple: print(i) printargs(10, 20) printargs(10, 20, 30) Output: Arguments are : 10 20 Arguments are : 10 20 30

8. What are lambda functions?

A function is said to be an anonymous function when it is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using lambda keyword.

Syntax: lambda [arg1 [,arg2,.....argn]]:expression Lambda forms can take any number of arguments but return just one value in the form of

an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an

expression. Lambda functions have their own local namespace and cannot access variables other than

those in their parameter list and those in the global namespace. Example: add = lambda arg1, arg2: arg1 + arg2 print("Sum =", add(10, 20)) Output: Sum = 30

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

9. Explain in detail about strings in Python.

Strings are not like integers, floats, and booleans. A string is a sequence, which means it is an ordered collection of other values. A String is a Sequence

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana' >>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

The expression in brackets is called an index. The index indicates which character in the

sequence you want (hence the name).

But you might not get what you expect: >>> letter 'a'

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the

index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0] >>> letter 'b'

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the

2th letter (“two-eth”).

As an index, you can use an expression that contains variables and operators:

>>> i = 1 >>> fruit[i] 'a' >>> fruit[i+1] 'n'

But the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5] TypeError: string indices must be integers

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

10. Explain the string built-in function len() with an example.

len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana' >>> len(fruit) 6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range

The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since

we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

>>> last = fruit[length-1] >>> last 'a'

Or you can use negative indices, which count backward from the end of the string. The

expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. 11. Explain the purpose of slicing string in Python with suitable example.

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python'

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”

character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure.

Figure. Slice indices.

If you omit the first index (before the colon), the slice starts at the beginning of the string.

If you omit the second index, the slice goes to the end of the string:

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana'

If the first index is greater than or equal to the second the result is an empty string,

represented by two quotation marks:

>>> fruit = 'banana' >>> fruit[3:3] ''

An empty string contains no characters and has length 0, but other than that, it is the same

as any other string.

Continuing this example, what do you think fruit[:] means? Try it and see. 12. Briefly explain the various string methods in Python.

Strings provide methods that perform a variety of useful operations. A method is similar to a function-it takes arguments and returns a value-but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters.

Instead of the function syntax upper(word), it uses the method syntax word.upper(): >>> word = 'banana' >>> new_word = word.upper() >>> new_word 'BANANA'

This form of dot notation specifies the name of the method, upper, and the name of the

string to apply the method to, word. The empty parentheses indicate that this method takes no arguments.

A method call is called an invocation; in this case, we would say that we are invoking upper on word.

As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana' >>> index = word.find('a') >>> index 1

In this example, we invoke find on word and pass the letter we are looking for as a

parameter.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

Actually, the find method is more general than our function; it can find substrings, not just characters:

>>> word.find('na') 2

By default, find starts at the beginning of the string, but it can take a second argument, the

index where it should start:

>>> word.find('na', 3) 4

This is an example of an optional argument. find can also take a third argument, the index

where it should stop:

>>> name = 'bob' >>> name.find('b', 1, 2) -1 This search fails because b does not appear in the index range from 1 to 2, not including 2.

Searching up to, but not including, the second index makes find consistent with the slice operator. 13. Explain the features of “in” operator for string in Python with suitable example.

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana' True >>> 'seed' in 'banana' False

For example, the following function prints all the letters from word1 that also appear

in word2:

def in_both(word1, word2): for letter in word1: if letter in word2: print(letter)

With well-chosen variable names, Python sometimes reads like English. You could read this

loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges') a e s

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

14. Briefly explain the String Comparison.

The relational operators work on strings. To see if two strings are equal:

if word == 'banana': print('All right, bananas.')

Other relational operations are useful for putting words in alphabetical order:

if word < 'banana': print('Your word, ' + word + ', comes before banana.') elif word > 'banana': print('Your word, ' + word + ', comes after banana.') else: print('All right, bananas.') Python does not handle uppercase and lowercase letters the same way people do. All the

uppercase letters come before all the lowercase letters, so:

Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

CHAPTER - 1 - LISTS 1.1 INTRODUCTION

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40] ['crunchy frog', 'ram bladder', 'lark vomit']

The first example is a list of four integers. The second is a list of three strings. The elements

of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]] A list within another list is nested.

A list that contains no elements is called an empty list; you can create one with empty

brackets, [].

As you might expect, you can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> numbers = [42, 123] >>> empty = [] >>> print(cheeses, numbers, empty) ['Cheddar', 'Edam', 'Gouda'] [42, 123] []

1.2 LISTS ARE MUTABLE

The syntax for accessing the elements of a list is the same as for accessing the characters of a string-the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:

>>> cheeses[0] 'Cheddar'

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an

assignment, it identifies the element of the list that will be assigned:

>>> numbers = [42, 123] >>> numbers[1] = 5 >>> numbers [42, 5]

The one-eth element of numbers, which used to be 123, is now 5.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Figure 1-1 shows the state diagram for cheeses, numbers and empty.

Figure 1-1. State diagram.

Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses refers to a list with three elements indexed 0, 1 and 2. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list with no elements.

List indices work the same way as string indices: Any integer expression can be used as an index. If you try to read or write an element that does not exist, you get an IndexError. If an index has a negative value, it counts backward from the end of the list.

The in operator also works on lists:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> 'Edam' in cheeses True >>> 'Brie' in cheeses False

1.3 TRAVERSING A LIST

The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

for cheese in cheeses: print(cheese)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the built-in functions range and len:

for i in range(len(numbers)): numbers[i] = numbers[i] * 2

This loop traverses the list and updates each element. len returns the number of elements

in the list. range returns a list of indices from 0 to n-1, where n is the length of the list. Each time through the loop, i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.

A for loop over an empty list never runs the body:

for x in []: print('This never happens.')

Although a list can contain another list, the nested list still counts as a single element. The

length of this list is four:

['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] 1.4 LIST OPERATIONS

The + operator concatenates lists:

>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6]

The * operator repeats a list a given number of times:

>>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three

times. 1.5 LIST SLICES

The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c']

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice

goes to the end. So if you omit both, the slice is a copy of the whole list:

>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy before performing operations that

modify lists.

A slice operator on the left side of an assignment can update multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> t ['a', 'x', 'y', 'd', 'e', 'f']

1.6 LIST METHODS 1.6.1 append()

Python provides methods that operate on lists. For example, append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd']

1.6.2 extend()

extend takes a list as an argument and appends all of the elements:

>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.

1.6.3 sort()

sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a']

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

>>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e']

Most list methods are void; they modify the list and return None. If you accidentally write t

= t.sort(), you will be disappointed with the result.

1.7 MAP, FILTER AND REDUCE

To add up all the numbers in a list, you can use a loop like this:

def add_all(t): total = 0 for x in t: total += x return total

total is initialized to 0. Each time through the loop, x gets one element from the list.

The += operator provides a short way to update a variable. This augmented assignment statement,

total += x

is equivalent to total = total + x

As the loop runs, total accumulates the sum of the elements; a variable used this way is

sometimes called an accumulator.

Adding up the elements of a list is such a common operation that Python provides it as a built-in function, sum:

>>> t = [1, 2, 3] >>> sum(t) 6

An operation like this that combines a sequence of elements into a single value is

sometimes called reduce.

Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:

def capitalize_all(t): res = [] for s in t: res.append(s.capitalize()) return res

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

res is initialized with an empty list; each time through the loop, we append the next element. So res is another kind of accumulator.

An operation like capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence.

Another common operation is to select some of the elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:

def only_upper(t): res = [] for s in t: if s.isupper(): res.append(s) return res

isupper is a string method that returns True if the string contains only uppercase letters.

An operation like only_upper is called a filter because it selects some of the elements and

filters out the others.

Most common list operations can be expressed as a combination of map, filter and reduce. 1.8 DELETING ELEMENTS 1.8.1 pop()

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'

pop modifies the list and returns the element that was removed. If you don’t provide an

index, it deletes and returns the last element. 1.8.2 del Operator

If you don’t need the removed value, you can use the del operator:

>>> t = ['a', 'b', 'c'] >>> del t[1] >>> t ['a', 'c']

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

1.8.3 remove()

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']

The return value from remove is None.

1.8.4 del Operator with Slice

To remove more than one element, you can use del with a slice index:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> t ['a', 'f']

As usual, the slice selects all the elements up to but not including the second index.

1.9 LISTS AND STRINGS

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:

>>> s = 'spam' >>> t = list(s) >>> t ['s', 'p', 'a', 'm']

The list function breaks a string into individual letters. If you want to break a string into

words, you can use the split method:

>>> s = 'pining for the fjords' >>> t = s.split() >>> t ['pining', 'for', 'the', 'fjords']

An optional argument called a delimiter specifies which characters to use as word

boundaries. The following example uses a hyphen as a delimiter:

>>> s = 'spam-spam-spam' >>> delimiter = '-' >>> t = s.split(delimiter) >>> t ['spam', 'spam', 'spam']

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:

>>> t = ['pining', 'for', 'the', 'fjords'] >>> delimiter = ' ' >>> s = delimiter.join(t) >>> s 'pining for the fjords'

In this case the delimiter is a space character, so join puts a space between words. To

concatenate strings without spaces, you can use the empty string, '', as a delimiter. 1.10 OBJECTS AND VALUES

If we run these assignment statements:

a = 'banana' b = 'banana'

We know that a and b both refer to a string, but we don’t know whether they refer to

the same string. There are two possible states, shown in Figure 1-2.

Figure 1-2. State diagram.

In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.

To check whether two variables refer to the same object, you can use the is operator:

>>> a = 'banana' >>> b = 'banana' >>> a is b True

In this example, Python only created one string object, and both a and b refer to it. But

when you create two lists, you get two objects:

>>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

So the state diagram looks like Figure 1-3.

Figure 1-3. State diagram. In this case we would say that the two lists are equivalent, because they have the same

elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you evaluate [1, 2, 3], you get a list object whose value is a sequence of integers. If another list has the same elements, we say it has the same value, but it is not the same object. 1.11 ALIASING

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False

The state diagram looks like Figure 1-4.

Figure 1-4. State diagram.

The association of a variable with an object is called a reference. In this example, there are two references to the same object.

An object with more than one reference has more than one name, so we say that the object is aliased.

If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 42 >>> a [42, 2, 3]

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.

For immutable objects like strings, aliasing is not as much of a problem. In this example:

a = 'banana' b = 'banana' It almost never makes a difference whether a and b refer to the same string or not.

1.12 LIST ARGUMENTS

When you pass a list to a function, the function gets a reference to the list. If the function modifies the list, the caller sees the change. For example, delete_head removes the first element from a list:

def delete_head(t): del t[0]

Here’s how it is used:

>>> letters = ['a', 'b', 'c'] >>> delete_head(letters) >>> letters ['b', 'c']

The parameter t and the variable letters are aliases for the same object. The stack diagram

looks like Figure 1-5.

Figure 1-5. Stack diagram.

Since the list is shared by two frames, I drew it between them.

It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list:

>>> t1 = [1, 2] >>> t2 = t1.append(3) >>> t1 [1, 2, 3] >>> t2 None

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

append modifies the list and returns None:

>>> t3 = t1 + [4] >>> t1 [1, 2, 3] >>> t3 [1, 2, 3, 4]

The + operator creates a new list and leaves the original list unchanged. This difference is important when you write functions that are supposed to modify lists. For

example, this function does not delete the head of a list:

def bad_delete_head(t): t = t[1:] # WRONG!

The slice operator creates a new list and the assignment makes t refer to it, but that

doesn’t affect the caller.

>>> t4 = [1, 2, 3] >>> bad_delete_head(t4) >>> t4 [1, 2, 3]

At the beginning of bad_delete_head, t and t4 refer to the same list. At the end, t refers to

a new list, but t4 still refers to the original, unmodified list.

An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:

def tail(t): return t[1:]

This function leaves the original list unmodified. Here’s how it is used:

>>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> rest ['b', 'c']

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

REVIEW QUESTIONS 1. Define List. 2. How to access elements on a list? 3. How to change elements of a list? 4. Explain the built-in functions with list. 5. What is the difference between del() and remove() methods of list? 6. Explain how to get the index of an object in a list. 7. Explain how to insert and reverse an object at given index in a list. 8. Explain how to remove last object from a list. 9. Explain mutable and immutable objects in Python. 10. Explain List comprehension in detail.

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to display only the positive elements of the list. 2. Develop a Python program to display only the negative elements of the list. 3. Develop a Python program to find the sum of positive elements and negative elements in a list. 4. Develop a Python program to remove the duplicate items from a list. 5. Develop a Python program to read marks of 10 students in the range of 0 - 100. Then make 10

groups: 0-10, 10-20, 20-30, etc. Count the number of values that falls in each group and display the results.

6. Develop a Python program to read in a list of ‘N’ integers and print its elements in reverse order without using reverse slicing, reverse method.

7. Develop a Python program to store ‘N’ numbers in a list and print the numbers divisible by five with the list location.

8. Develop a Python program to find the greatest of ’N’ numbers stored in a list and print the result.

9. Develop a Python program to accept any number and print it in words. 10. Develop a Python program to sort a list of N numbers using bubble sort. 11. Develop a Python program to search an element from a list of N numbers using linear search. 12. Develop a Python program to search an element from a list of N numbers using binary search. 13. Develop a Python program to add two matrices. 14. Develop a Python program to subtract two matrices. 15. Develop a Python program to perform matrix multiplication. 16. Develop a Python program to count the number of each vowel.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

CHAPTER - 2 - DICTIONARIES 2.1 A DICTIONARY IS A MAPPING

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a

dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.

In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.

>>> eng2sp = dict() >>> eng2sp {}

The squiggly brackets, {}, represent an empty dictionary. To add items to the dictionary,

you can use square brackets:

>>> eng2sp['one'] = 'uno'

This line creates an item that maps from the key 'one' to the value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and value:

>>> eng2sp {'one': 'uno'}

This output format is also an input format. For example, you can create a new dictionary

with three items:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

But if you print eng2sp, you might be surprised:

>>> eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}

The order of the key-value pairs might not be the same. If you type the same example on

your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable.

But that’s not a problem because the elements of a dictionary are never indexed with

integer indices. Instead, you use the keys to look up the corresponding values:

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> eng2sp['two'] 'dos' The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter.

If the key isn’t in the dictionary, you get an exception:

>>> eng2sp['four'] KeyError: 'four'

The len function works on dictionaries; it returns the number of key-value pairs:

>>> len(eng2sp) 3

The in operator works on dictionaries, too; it tells you whether something appears as

a key in the dictionary (appearing as a value is not good enough).

>>> 'one' in eng2sp True >>> 'uno' in eng2sp False

To see whether something appears as a value in a dictionary, you can use the

method values, which returns a collection of values, and then use the in operator:

>>> vals = eng2sp.values() >>> 'uno' in vals True

The in operator uses different algorithms for lists and dictionaries. For lists, it searches the

elements of the list in order, as in “Searching”. As the list gets longer, the search time gets longer in direct proportion.

For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items are in the dictionary. 2.2 DICTIONARY AS A COLLECTION OF COUNTERS

Suppose you are given a string and you want to count how many times each letter appears. There are several ways you could do it:

1. You could create 26 variables, one for each letter of the alphabet. Then you could

traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.

2. You could create a list with 26 elements. Then you could convert each character to a number (using the built-in function ord), use the number as an index into the list, and increment the appropriate counter.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

3. You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item.

Each of these options performs the same computation, but each of them implements that

computation in a different way.

An implementation is a way of performing a computation; some implementations are better than others. For example, an advantage of the dictionary implementation is that we don’t have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear.

Here is what the code might look like:

def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d

The name of the function is histogram, which is a statistical term for a collection of

counters (or frequencies).

The first line of the function creates an empty dictionary. The for loop traverses the string. Each time through the loop, if the character c is not in the dictionary, we create a new item with key c and the initial value 1 (since we have seen this letter once). If c is already in the dictionary we increment d[c].

Here’s how it works:

>>> h = histogram('brontosaurus') >>> h {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}

The histogram indicates that the letters ’a’ and 'b' appear once; 'o' appears twice, and so

on.

Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example:

>>> h = histogram('a') >>> h {'a': 1} >>> h.get('a', 0) 1

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> h.get('b', 0) 0

2.3 LOOPING AND DICTIONARIES

If you use a dictionary in a for statement, it traverses the keys of the dictionary. For example, print_hist prints each key and the corresponding value:

def print_hist(h): for c in h: print(c, h[c])

Here’s what the output looks like:

>>> h = histogram('parrot') >>> print_hist(h) p 1 a 1 r 2 o 1 t 1

Again, the keys are in no particular order. To traverse the keys in sorted order, you can use

the built-in function sorted:

for key in sorted(h): print(key, h[key])

a 1 o 1 p 1 r 2 t 1

2.4 DICTIONARIES AND LISTS

Lists can appear as values in a dictionary. For example, if you are given a dictionary that maps from letters to frequencies, you might want to invert it; that is, create a dictionary that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted dictionary should be a list of letters.

Here is a function that inverts a dictionary:

def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key]

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

else: inverse[val].append(key) return inverse

Each time through the loop, key gets a key from d and val gets the corresponding value.

If val is not in inverse, that means we haven’t seen it before, so we create a new item and initialize it with a singleton (a list that contains a single element). Otherwise we have seen this value before, so we append the corresponding key to the list.

Here is an example:

>>> hist = histogram('parrot') >>> hist {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1} >>> inverse = invert_dict(hist) >>> inverse {1: ['a', 'p', 't', 'o'], 2: ['r']}

Figure 2-1 is a state diagram showing hist and inverse. A dictionary is represented as a box

with the type dict above it and the key-value pairs inside. If the values are integers, floats or strings, I draw them inside the box, but I usually draw lists outside the box, just to keep the diagram simple.

Figure 2-1. State diagram.

Lists can be values in a dictionary, as this example shows, but they cannot be keys. Here’s what happens if you try:

>>> t = [1, 2, 3] >>> d = dict() >>> d[t] = 'oops' TypeError: unhashable type: 'list' I mentioned earlier that a dictionary is implemented using a hashtable and that means that

the keys have to be hashable.

A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

This system works fine if the keys are immutable. But if the keys are mutable, like lists, bad things happen. For example, when you create a key-value pair, Python hashes the key and stores it in the corresponding location. If you modify the key and then hash it again, it would go to a different location. In that case you might have two entries for the same key, or you might not be able to find a key. Either way, the dictionary wouldn’t work correctly.

That’s why keys have to be hashable, and why mutable types like lists aren’t. The simplest way to get around this limitation is to use tuples, which we will see in the next chapter. Since dictionaries are mutable, they can’t be used as keys, but they can be used as values.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

REVIEW QUESTIONS 1. What do you mean by a Python dictionary? 2. Explain how to create a dictionary in Python? 3. Explain how to create a dictionary using tuples in Python? 4. Explain popitem() and clear() method. 5. Explain dictionary built-in functions in detail.

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to add a key-value pair to the dictionary. 2. Develop a Python program to concatenate two dictionaries into one. 3. Develop a Python program to check if a given key exists in a dictionary or not. 4. Develop a Python program to generate a dictionary that contains numbers (between 1 and n)

in the form (x, x*x). 5. Develop a Python program to sum all the items in a dictionary. 6. Develop a Python program to multiply all the items in a dictionary. 7. Develop a Python program to remove the given key from a dictionary. 8. Develop a Python program to count the frequency of words appearing in a string using a

dictionary.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

CHAPTER - 3 - TUPLES 3.1 TUPLES ARE IMMUTABLE

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values: >>> t = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in parentheses:

>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include a final comma:

>>> t1 = 'a', >>> type(t1) <class 'tuple'>

A value in parentheses is not a tuple:

>>> t2 = ('a') >>> type(t2) <class 'str'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an

empty tuple:

>>> t = tuple() >>> t ()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements

of the sequence:

>>> t = tuple('lupins') >>> t ('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a built-in function, you should avoid using it as a variable

name.

Most list operators also work on tuples. The bracket operator indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e') >>> t[0] 'a'

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

And the slice operator selects a range of elements:

>>> t[1:3] ('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A' TypeError: 'tuple' object does not support item assignment

Because tuples are immutable, you can’t modify the elements. But you can replace one

tuple with another:

>>> t = ('A',) + t[1:] >>> t ('A', 'b', 'c', 'd', 'e')

This statement makes a new tuple and then makes t refer to it.

The relational operators work with tuples and other sequences; Python starts by

comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).

>>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True

3.2 TUPLE ASSIGNMENT

It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:

>>> temp = a >>> a = b >>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

>>> a, b = b, a The left side is a tuple of variables; the right side is a tuple of expressions. Each value is

assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

>>> a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2)

More generally, the right side can be any kind of sequence (string, list or tuple). For

example, to split an email address into a user name and a domain, you could write:

>>> addr = '[email protected]' >>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned

to uname, the second to domain: >>> uname 'monty' >>> domain 'python.org'

3.3 TUPLES AS RETURN VALUES

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values: the quotient and remainder. You can store the result as a tuple:

>>> t = divmod(7, 3) >>> t (2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3) >>> quot 2 >>> rem 1

Here is an example of a function that returns a tuple:

def min_max(t): return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a

sequence. min_max computes both and returns a tuple of two values.

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

3.4. VARIABLE-LENGTH ARGUMENT TUPLES

Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, printall takes any number of arguments and prints them:

def printall(*args): print(args)

The gather parameter can have any name you like, but args is conventional. Here’s how the

function works:

>>> printall(1, 2.0, '3') (1, 2.0, '3')

The complement of gather is scatter. If you have a sequence of values and you want to

pass it to a function as multiple arguments, you can use the * operator. For example, divmod takes exactly two arguments; it doesn’t work with a tuple:

>>> t = (7, 3) >>> divmod(t) TypeError: divmod expected 2 arguments, got 1 But if you scatter the tuple, it works:

>>> divmod(*t) (2, 1)

Many of the built-in functions use variable-length argument tuples. For

example, max and min can take any number of arguments:

>>> max(1, 2, 3) 3

But sum does not:

>>> sum(1, 2, 3) TypeError: sum expected at most 2 arguments, got 3

3.5 LISTS AND TUPLES

zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence. The name of the function refers to a zipper, which joins and interleaves two rows of teeth.

This example zips a string and a list:

>>> s = 'abc' >>> t = [0, 1, 2]

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

>>> zip(s, t) <zip object at 0x000001C59F7AF0C8>

The result is a zip object that knows how to iterate through the pairs. The most common

use of zip is in a for loop:

for pair in zip(s, t): print(pair) ('a', 0) ('b', 1) ('c', 2)

A zip object is a kind of iterator, which is any object that iterates through a sequence.

Iterators are similar to lists in some ways, but unlike lists, you can’t use an index to select an element from an iterator.

If you want to use list operators and methods, you can use a zip object to make a list:

>>> list(zip(s, t)) [('a', 0), ('b', 1), ('c', 2)]

The result is a list of tuples; in this example, each tuple contains a character from the string

and the corresponding element from the list.

If the sequences are not the same length, the result has the length of the shorter one:

>>> list(zip('Anne', 'Elk')) [('A', 'E'), ('n', 'l'), ('n', 'k')]

You can use tuple assignment in a for loop to traverse a list of tuples:

t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print(number, letter)

Each time through the loop, Python selects the next tuple in the list and assigns the

elements to letter and number. The output of this loop is: 0 a 1 b 2 c

If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or

more) sequences at the same time. For example, has_match takes two sequences, t1and t2, and returns True if there is an index i such that t1[i] == t2[i]:

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False If you need to traverse the elements of a sequence and their indices, you can use the built-

in function enumerate:

for index, element in enumerate('abc'): print(index, element)

The result from enumerate is an enumerate object, which iterates a sequence of pairs;

each pair contains an index (starting from 0) and an element from the given sequence. In this example, the output is

0 a 1 b 2 c

Again.

3.6 DICTIONARIES AND TUPLES

Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair:

>>> d = {'a':0, 'b':1, 'c':2} >>> t = d.items() >>> t dict_items([('c', 2), ('a', 0), ('b', 1)])

The result is a dict_items object, which is an iterator that iterates the key-value pairs. You

can use it in a for loop like this:

d = {'a':0, 'b':1, 'c':2} for key, value in d.items(): print(key, value)

a 0 b 1 c 2 As you should expect from a dictionary, the items are in no particular order.

Going in the other direction, you can use a list of tuples to initialize a new dictionary:

>>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 31

>>> d {'a': 0, 'c': 2, 'b': 1}

Combining dict with zip yields a concise way to create a dictionary:

>>> d = dict(zip('abc', range(3))) >>> d {'a': 0, 'c': 2, 'b': 1}

The dictionary method update also takes a list of tuples and adds them, as key-value pairs,

to an existing dictionary.

It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:

directory[last, first] = number The expression in brackets is a tuple. We could use tuple assignment to traverse this

dictionary:

for last, first in directory: print(first, last, directory[last,first])

This loop traverses the keys in directory, which are tuples. It assigns the elements of each

tuple to last and first, then prints the name and corresponding telephone number.

There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple ('Cleese', 'John') would appear as in Figure 3-1.

Figure 3-1. State diagram.

But in a larger diagram you might want to leave out the details. For example, a diagram of

the telephone directory might appear as in Figure 3-2.

Figure 3-2. State diagram.

32 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Here the tuples are shown using Python syntax as a graphical shorthand. 3.7 TUPLE METHODS 3.7.1 count()

The count() method returns the number of occurrences of an element in a tuple.

The syntax of count() method is:

tuple.count(element)

The count() method takes a single parameter: element - element whose count is to be found.

Example: >>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.count('r') 2

3.7.2 index()

The index() method searches an element in a tuple and returns its index. The syntax of index() method for Tuple is:

tuple.index(element)

index() method takes a single argument: element - element that is to be searched. The index method returns the position/index of the given element in the tuple. If no

element is found, a ValueError exception is raised indicating the element is not found. Example: >>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.index('r') 1

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 33

REVIEW QUESTIONS 1. What are tuples in Python? 2. How to access tuple items? 3. Explain the tuple methods in detail with suitable examples. 4. Explain how to slice a tuple with suitable examples. 5. What is the difference between tuples and lists in Python? 6. Explain how to create a dictionary using tuples in Python?

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to create a list of tuples with the first element as the number and

second element as the square of the number. 2. Develop a Python program to sort a list of tuples in increasing order by the last element in

each tuple.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 35

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Develop a Python program to display only the positive elements of the list. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) print("The positive elements are : ") for i in range(n): if a[i] > 0: print(a[i]) Output: Enter the limit : 5 Enter the elements : 10 -20 30 -40 -50 The positive elements are : 10 30

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to display only the negative elements of the list. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) print("The positive elements are : ") for i in range(n): if a[i] < 0: print(a[i]) Output: Enter the limit : 5 Enter the elements : 10 -20 30 -40 -50 The positive elements are : -20 -40 -50

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Develop a Python program to find the sum of positive elements and negative elements in a list. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] psum = 0 nsum = 0 for i in range(n): a.append(int(input())) for i in range(n): if a[i] > 0: psum = psum + a[i] if a[i] < 0: nsum = nsum + a[i] print("Sum of positive elements : ", psum) print("Sum of negative elements : ", nsum) Output: Enter the limit : 5 Enter the elements : -10 30 50 -20 40 Sum of positive elements : 120 Sum of negative elements : -30

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to remove the duplicate items from a list. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) r = [] for i in a: if i not in r: r.append(i) print("The non-duplicate elements are : ") for i in r: print(i) Output: Enter the limit : 5 Enter the elements : 2 11 14 11 6 The non-duplicate elements are : 2 11 14 6

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Develop a Python program to read marks of 10 students in the range of 0 - 100. Then make 10 groups: 0-10, 10-20, 20-30, etc. Count the number of values that falls in each group and display the results. Program: a = [] for i in range(10): print("Enter the mark of student", i + 1) a.append(int(input())) r = [] for i in range(10): r.append(0) for i in range(10): if a[i] % 10 == 0: q = a[i] // 10 - 1 else: q = a[i] // 10 r[q] = r[q] + 1 print("The result is : ") for i in range(10): print(i * 10 + 1, "-", i * 10 + 10, ":", r[i]) Output: Enter the mark of student 1 75 Enter the mark of student 2 85 Enter the mark of student 3 95 Enter the mark of student 4 100 Enter the mark of student 5 5 Enter the mark of student 6 55 Enter the mark of student 7 60 Enter the mark of student 8 70 Enter the mark of student 9 80 Enter the mark of student 10 40

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

The result is : 1 - 10 : 1 11 - 20 : 0 21 - 30 : 0 31 - 40 : 1 41 - 50 : 0 51 - 60 : 2 61 - 70 : 1 71 - 80 : 2 81 - 90 : 1 91 - 100 : 2

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Develop a Python program to read in a list of ‘N’ integers and print its elements in reverse order without using reverse slicing, reverse method. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) print("Enter reversed list is : ") for i in range(n - 1, -1, -1): print(a[i]) Output: Enter the limit : 5 Enter the elements : 20 30 50 10 40 Enter reversed list is : 40 10 50 30 20

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to store ‘N’ numbers in a list and print the numbers divisible by five with the list location. Program: n = int(input("Enter the limit : ")) print("Enter the numbers : ") a = [] for i in range(n): a.append(int(input())) print("The numbers divisible by 5 are :") for i in range(n): if a[i] % 5 == 0: print("a[", i, "] =", a[i]) Output: Enter the limit : 5 Enter the numbers : 11 20 33 40 55 The numbers divisible by 5 are : a[ 1 ] = 20 a[ 3 ] = 40 a[ 4 ] = 55

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

Develop a Python program to find the greatest of ’N’ numbers stored in a list and print the result. Program: n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) g = a[0] for i in range(1, n): if a[i] > g: g = a[i] print("The greatest number is :", g) Output: Enter the limit : 5 Enter the elements : 20 30 50 40 10 The greatest number is : 50

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to accept any number and print it in words. Program: n = input("Enter the number : ") words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",

"Eight", "Nine"] a = list(n) for i in range(len(a)): print(words[int(a[i])], end = " ") Output: Enter the number : 9791519152 Nine Seven Nine One Five One Nine One Five Two

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

Develop a Python program to sort a list of N numbers using bubble sort. Program: def BubbleSort(a): for i in range(0, len(a) - 1): for j in range(0, len(a) - 1 - i): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] n = int(input("Enter the limit : ")) print("Enter the elements : ") a = [] for i in range(n): a.append(int(input())) BubbleSort(a) print("The sorted elements are : ") for i in range(n): print(a[i]) Output: Enter the limit : 5 Enter the elements : 30 40 50 20 10 The sorted elements are : 10 20 30 40 50

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to search an element from a list of N numbers using linear search. Program: def LinearSearch(a, key): for i in range(len(a)): if a[i] == key: return i return -1 n = int(input("Enter the limit : ")) print("Enter the elements :") a = [] for i in range(n): a.append(int(input())) key = int(input("Enter the element to search : ")) pos = LinearSearch(a, key) if pos != -1: print("Element found at location", pos) else: print("Element not found.") Output: Enter the limit : 5 Enter the elements : 30 40 50 20 10 Enter the element to search : 20 Element found at location 3 Enter the limit : 5 Enter the elements : 30 40 50 20 10 Enter the element to search : 55 Element not found.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

Develop a Python program to search an element from a list of N numbers using binary search. Program: def BinarySearch(a, key): first = 0 last = len(a) - 1 while first <= last: mid = (first + last) // 2 if a[mid] == key: return mid elif a[mid] < key: first = mid + 1 else: last = mid - 1 return -1 n = int(input("Enter the limit : ")) print("Enter the elements in sorted order : ") a = [] for i in range(n): a.append(int(input())) key = int(input("Enter the element to search : ")) pos = BinarySearch(a, key) if pos != -1: print("Element found at location", pos) else: print("Element not found.") Output: Enter the limit : 5 Enter the elements in sorted order : 10 20 30 40 50 Enter the element to search : 30 Element found at location 2 Enter the limit : 5 Enter the elements in sorted order : 10 20 30 40 50 Enter the element to search : 55 Element not found.

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to add two matrices. Program: row = int(input("Enter the number of rows : ")) col = int(input("Enter the number of columns : ")) mat = [] mata = [] matb = [] matc = [] for i in range(col): mat.append(0) for i in range(row): mata.append(mat.copy()) matb.append(mat.copy()) matc.append(mat.copy()) print("Enter the elements of first matrix : ") for i in range(row): for j in range(col): mata[i][j] = int(input()) print("Enter the elements of second matrix : ") for i in range(row): for j in range(col): matb[i][j] = int(input()) for i in range(row): for j in range(col): matc[i][j] = mata[i][j] + matb[i][j] print("The resultant matrix is : ") for i in range(row): for j in range(col): print(matc[i][j], end = "\t") print()

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

Output: Enter the number of rows : 3 Enter the number of columns : 3 Enter the elements of first matrix : 1 3 5 7 9 11 13 15 17 1 3 5 7 9 11 13 15 17 Enter the elements of second matrix : 2 4 6 8 10 12 14 16 18 The resultant matrix is : 3 7 11 15 19 23 27 31 35

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to subtract two matrices. Program: row = int(input("Enter the number of rows : ")) col = int(input("Enter the number of columns : ")) mat = [] mata = [] matb = [] matc = [] for i in range(col): mat.append(0) for i in range(row): mata.append(mat.copy()) matb.append(mat.copy()) matc.append(mat.copy()) print("Enter the elements of first matrix : ") for i in range(row): for j in range(col): mata[i][j] = int(input()) print("Enter the elements of second matrix : ") for i in range(row): for j in range(col): matb[i][j] = int(input()) for i in range(row): for j in range(col): matc[i][j] = mata[i][j] - matb[i][j] print("The resultant matrix is : ") for i in range(row): for j in range(col): print(matc[i][j], end = "\t") print()

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

Output: Enter the number of rows : 3 Enter the number of columns : 3 Enter the elements of first matrix : 5 10 15 20 25 30 35 40 45 5 10 15 20 25 30 35 40 45 Enter the elements of second matrix : 2 4 6 8 10 12 14 16 18 The resultant matrix is : 3 6 9 12 15 18 21 24 27

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to perform matrix multiplication. Program: row1 = int(input("Enter the first matrix rows : ")) col1 = int(input("Enter the first matrix columns : ")) row2 = int(input("Enter the second matrix rows : ")) col2 = int(input("Enter the second matrix columns : ")) if col1 == row2: mat = [] mata = [] matb = [] matc = [] for i in range(col1): mat.append(0) for i in range(row1): mata.append(mat.copy()) mat = [] for i in range(col2): mat.append(0) for i in range(row2): matb.append(mat.copy()) for i in range(row1): matc.append(mat.copy()) print("Enter the elements of first matrix : ") for i in range(row1): for j in range(col1): mata[i][j] = int(input()) print("Enter the elements of second matrix : ") for i in range(row2): for j in range(col2): matb[i][j] = int(input()) for i in range(row1): for j in range(col2): for k in range(col1): matc[i][j] = matc[i][j] + mata[i][k] * matb[k][j] print("The resultant matrix is : ") for i in range(row1): for j in range(col2): print(matc[i][j], end = "\t") print() else: print("Matrix multiplication is not possible.")

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

Output: Enter the first matrix rows : 3 Enter the first matrix columns : 3 Enter the second matrix rows : 3 Enter the second matrix columns : 3 Enter the elements of first matrix : 1 1 1 1 1 1 1 1 1 Enter the elements of second matrix : 1 1 1 1 1 1 1 1 1 The resultant matrix is : 3 3 3 3 3 3 3 3 3 Enter the first matrix rows : 3 Enter the first matrix columns : 3 Enter the second matrix rows : 2 Enter the second matrix columns : 2 Matrix multiplication is not possible.

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to count the number of each vowel. Program: s = input("Enter the string : ") s = s.lower() vowels = "aeiou" d = {}.fromkeys(vowels, 0) for c in s: if c in d: d[c] = d[c] + 1 for i in d: print(i, "=", d[i]) Output: Enter the string : Python Programming a = 1 e = 0 i = 1 o = 2 u = 0

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - IV Part - A

Question Bank 1. Define List.

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.

There are several ways to create a new list; the simplest is to enclose the elements in

square brackets ([ and ]): [10, 20, 30, 40] ['crunchy frog', 'ram bladder', 'lark vomit']

2. Explain how to slice a list with suitable examples.

The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice

goes to the end. So if you omit both, the slice is a copy of the whole list: >>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']

3. How to traverse a list? Give example.

The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

cheeses = ['Cheddar', 'Edam', 'Gouda'] for cheese in cheeses: print(cheese)

This works well if you only need to read the elements of the list.

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4. What are the various list operations? Give example.

The + operator concatenates lists:

>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6]

The * operator repeats a list a given number of times:

>>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three

times. 5. List the built-in functions with list.

all() any() len() list() max() min() sorted() sum()

6. What do you mean by a dictionary in Python?

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item. 7. How to create a dictionary in Python? Give two examples.

The function dict creates a new dictionary with no items. >>> eng2sp = dict() >>> eng2sp {} The squiggly brackets, {}, represent an empty dictionary. You can create a new dictionary with three items: >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

8. Explain the pop() and remove()to delete elements from a list with examples.

If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'

pop modifies the list and returns the element that was removed. If you don’t provide an

index, it deletes and returns the last element.

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']

The return value from remove is None.

9. Define tuple.

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values: >>> t = 'a', 'b', 'c', 'd', 'e' Although it is not necessary, it is common to enclose tuples in parentheses: >>> t = ('a', 'b', 'c', 'd', 'e')

10. Explain the tuple assignment in Python with suitable examples.

Tuple assignment is more elegant:

>>> a, b = b, a The left side is a tuple of variables; the right side is a tuple of expressions. Each value is

assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

11. Explain how to slice a tuple with suitable examples.

The slice operator selects a range of elements: >>> t = ('a', 'b', 'c', 'd', 'e') >>> t[1:3] ('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A' TypeError: 'tuple' object does not support item assignment

Because tuples are immutable, you can’t modify the elements.

12. How to traverse a tuple? Give example.

The most common way to traverse the elements of a tuple is with a for loop. The syntax is the same as for strings:

cheeses = ('Cheddar', 'Edam', 'Gouda') for cheese in cheeses: print(cheese)

This works well if you only need to read the elements of the list. 13. List the built-in functions with tuple.

all() any() len() max() min() sorted() sum() tuple()

14. Write the tuple methods with suitable examples. count() The count() method returns the number of occurrences of an element in a tuple.

>>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.count('r') 2

index()

The index() method searches an element in a tuple and returns its index.

>>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.index('r') 1

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Quick Reference – Built-in Methods

Function List Tuple Dictionary

all()

Return True if all elements of the list are true (or if the list is empty).

Return True if all elements of the tuple are true (or if the tuple is empty).

Return True if all keys of the dictionary are true (or if the dictionary is empty).

any()

Return True if any element of the list is true. If the list is empty, return False.

Return True if any element of the tuple is true. If the tuple is empty, return False.

Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the list.

Return the length (the number of items) in the tuple.

Return the length (the number of items) in the dictionary.

list() Convert an iterable (tuple, string, set, dictionary) to a list.

NA NA

max() Return the largest item in the list.

Return the largest item in the tuple. NA

min() Return the smallest item in the list.

Return the smallest item in the tuple. NA

sorted()

Return a new sorted list (does not sort the list itself).

Take elements in the tuple and return a new sorted list (does not sort the tuple itself).

Return a new sorted list of keys in the dictionary.

sum() Return the sum of all elements in the list.

Return the sum of all elements in the tuple. NA

tuple() NA Convert an iterable (list, string, set, dictionary) to a tuple.

NA

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - IV Part - B

Question Bank 1. Explain in detail about lists in Python?

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40] ['crunchy frog', 'ram bladder', 'lark vomit']

The first example is a list of four integers. The second is a list of three strings. The elements

of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]] A list within another list is nested.

A list that contains no elements is called an empty list; you can create one with empty

brackets, [].

As you might expect, you can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> numbers = [42, 123] >>> empty = [] >>> print(cheeses, numbers, empty) ['Cheddar', 'Edam', 'Gouda'] [42, 123] []

The syntax for accessing the elements of a list is the same as for accessing the characters of

a string-the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:

>>> cheeses[0] 'Cheddar'

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an

assignment, it identifies the element of the list that will be assigned:

>>> numbers = [42, 123] >>> numbers[1] = 5

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> numbers [42, 5]

The one-eth element of numbers, which used to be 123, is now 5.

Figure shows the state diagram for cheeses, numbers and empty.

Figure. State diagram.

Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses refers to a list with three elements indexed 0, 1 and 2. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list with no elements.

List indices work the same way as string indices: Any integer expression can be used as an index. If you try to read or write an element that does not exist, you get an IndexError. If an index has a negative value, it counts backward from the end of the list.

The in operator also works on lists:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> 'Edam' in cheeses True >>> 'Brie' in cheeses False

2. How to traverse a list?

The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

for cheese in cheeses: print(cheese)

This works well if you only need to read the elements of the list. But if you want to write or

update the elements, you need the indices. A common way to do that is to combine the built-in functions range and len:

for i in range(len(numbers)): numbers[i] = numbers[i] * 2

This loop traverses the list and updates each element. len returns the number of elements

in the list. range returns a list of indices from 0 to n-1, where n is the length of the list. Each time through the loop, i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.

A for loop over an empty list never runs the body:

for x in []: print('This never happens.')

Although a list can contain another list, the nested list still counts as a single element. The

length of this list is four:

['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] 3. Explain the process of list slicing in Python.

The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice

goes to the end. So if you omit both, the slice is a copy of the whole list:

>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy before performing operations that

modify lists.

A slice operator on the left side of an assignment can update multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y']

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> t ['a', 'x', 'y', 'd', 'e', 'f']

4. Explain the list methods in Python. append()

Python provides methods that operate on lists. For example, append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd']

extend()

extend takes a list as an argument and appends all of the elements:

>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.

sort()

sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e']

Most list methods are void; they modify the list and return None. If you accidentally write t

= t.sort(), you will be disappointed with the result.

pop()

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element. remove()

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']

The return value from remove is None.

5. Explain in detail about dictionaries in Python.

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.

In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.

>>> eng2sp = dict() >>> eng2sp {}

The squiggly brackets, {}, represent an empty dictionary. To add items to the dictionary,

you can use square brackets:

>>> eng2sp['one'] = 'uno'

This line creates an item that maps from the key 'one' to the value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and value:

>>> eng2sp {'one': 'uno'}

This output format is also an input format. For example, you can create a new dictionary

with three items:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

But if you print eng2sp, you might be surprised:

>>> eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}

The order of the key-value pairs might not be the same. If you type the same example on

your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable.

But that’s not a problem because the elements of a dictionary are never indexed with

integer indices. Instead, you use the keys to look up the corresponding values:

>>> eng2sp['two'] 'dos' The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter.

If the key isn’t in the dictionary, you get an exception:

>>> eng2sp['four'] KeyError: 'four'

The len function works on dictionaries; it returns the number of key-value pairs:

>>> len(eng2sp) 3

The in operator works on dictionaries, too; it tells you whether something appears as

a key in the dictionary (appearing as a value is not good enough).

>>> 'one' in eng2sp True >>> 'uno' in eng2sp False

To see whether something appears as a value in a dictionary, you can use the

method values, which returns a collection of values, and then use the in operator:

>>> vals = eng2sp.values() >>> 'uno' in vals True

The in operator uses different algorithms for lists and dictionaries. For lists, it searches the

elements of the list in order, as in “Searching”. As the list gets longer, the search time gets longer in direct proportion.

For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items are in the dictionary.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

6. Explain in detail about tuples in Python?

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values: >>> t = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in parentheses:

>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include a final comma:

>>> t1 = 'a', >>> type(t1) <class 'tuple'>

A value in parentheses is not a tuple:

>>> t2 = ('a') >>> type(t2) <class 'str'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an

empty tuple:

>>> t = tuple() >>> t ()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements

of the sequence:

>>> t = tuple('lupins') >>> t ('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a built-in function, you should avoid using it as a variable

name.

Most list operators also work on tuples. The bracket operator indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e') >>> t[0] 'a' And the slice operator selects a range of elements:

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> t[1:3] ('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A' TypeError: 'tuple' object does not support item assignment

Because tuples are immutable, you can’t modify the elements. But you can replace one

tuple with another:

>>> t = ('A',) + t[1:] >>> t ('A', 'b', 'c', 'd', 'e')

This statement makes a new tuple and then makes t refer to it.

The relational operators work with tuples and other sequences; Python starts by

comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).

>>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True

7. Explain the tuple assignment in Python with suitable examples.

It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:

>>> temp = a >>> a = b >>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

>>> a, b = b, a The left side is a tuple of variables; the right side is a tuple of expressions. Each value is

assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

>>> a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:

>>> addr = '[email protected]' >>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned

to uname, the second to domain: >>> uname 'monty' >>> domain 'python.org'

8. Explain the tuple methods in Python. count()

The count() method returns the number of occurrences of an element in a tuple.

The syntax of count() method is:

tuple.count(element)

The count() method takes a single parameter: element - element whose count is to be found.

Example: >>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.count('r') 2

index()

The index() method searches an element in a tuple and returns its index. The syntax of index() method for Tuple is:

tuple.index(element)

index() method takes a single argument: element - element that is to be searched. The index method returns the position/index of the given element in the tuple. If no

element is found, a ValueError exception is raised indicating the element is not found. Example: >>> t = ('P', 'r', 'o', 'g', 'r', 'a', 'm') >>> t.index('r') 1

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

CHAPTER - 1 - FILES 1.1 INTRODUCTION

Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate.

Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); and if they shut down and restart, they pick up where they left off.

Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network.

One of the simplest ways for programs to maintain their data is by reading and writing text files. We have already seen programs that read text files; in this chapter we will see programs that write them.

An alternative is to store the state of the program in a database. 1.2 BASIC FILE OPERATIONS In Python there are four basic file-related operations. They are:

1. Opening a file 2. Reading data from a file 3. Writing data to a file 4. Closing a file

1.3 OPENING A FILE

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

file object = open(file_name [, access_mode][, buffering])

file_name − The file_name argument is a string value that contains the name of the file that you want to access.

access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. This is an optional parameter and the default file access mode is read (r).

buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value

is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default (default behavior).

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

1.4 DIFFERENT MODES FOR OPENING A FILE

While opening a file, we can specify whether to read (r), write (w) or append (a) data to the file and also specify whether to open in text or binary mode.

The default way of opening is in read (text mode). In text mode, we get strings while

reading from the file. In binary mode, it returns bytes and are used with non-text files like jpeg or exe files. The different modes for opening a file are as follows:

Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it

exists. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it

does not exist. 'b' Open in binary mode. '+' Open a file for updating (reading and writing)

1.5 WRITING INTO A FILE

A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM. To write a file, you have to open it with mode 'w' as a second parameter:

>>> fout = open('output.txt', 'w')

If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created.

open returns a file object that provides methods for working with the file. The write method puts data into the file:

>>> line1 = "This here's the wattle,\n" >>> fout.write(line1) 24

The return value is the number of characters that were written. The file object keeps track

of where it is, so if you call write again, it adds the new data to the end of the file: >>> line2 = "the emblem of our land.\n" >>> fout.write(line2) 24

When you are done writing, you should close the file:

>>> fout.close()

If you don’t close the file, it gets closed for you when the program ends.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

1.6 READING FROM A FILE

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

>>> fin = open('output.txt')

fin is a common name for a file object used for input. The file object provides several methods for reading, including readline, which reads characters from the file until it gets to a newline and returns the result as a string:

>>> fin.readline() "This here's the wattle,\n"

The first line in this particular file is “This here's the wattle,\n”. The sequence \n represents

whitespace character, a newline, that separate this line from the next.

The file object keeps track of where it is in the file, so if you call readline again, you get the next line:

>>> fin.readline() 'the emblem of our land.\n' The next line is “the emblem of our land.\n”. Or, if it’s the whitespace that’s bothering you,

we can get rid of it with the string method strip: >>> fin = open('output.txt') >>> lines = fin.readline() >>> line = lines.strip() >>> line "This here's the wattle," You can also use a file object as part of a for loop. This program reads output.txt and prints

line by line: fin = open('output.txt') for lines in fin: line = lines.strip() print(line) fin.close() Output: This here's the wattle, the emblem of our land.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

1.7 FILE METHODS 1.7.1 tell()

The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file. 1.7.2 seek()

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. 1.8. FORMAT OPERATOR

The argument of write has to be a string, so if we want to put other values in a file, we have to convert them to strings. The easiest way to do that is with str:

>>> x = 52 >>> fout.write(str(x))

An alternative is to use the format operator, %. When applied to integers, % is the

modulus operator. But when the first operand is a string, % is the format operator.

The first operand is the format string, which contains one or more format sequences, which specify how the second operand is formatted. The result is a string.

For example, the format sequence '%d' means that the second operand should be formatted as a decimal integer:

>>> camels = 42 >>> '%d' % camels '42'

The result is the string '42', which is not to be confused with the integer value 42.

A format sequence can appear anywhere in the string, so you can embed a value in a

sentence: >>> 'I have spotted %d camels.' % camels 'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.

The following example uses '%d' to format an integer, '%g' to format a floating-point number, and '%s' to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have spotted 0.1 camels.'

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: %d format: a number is required, not str In the first example, there aren’t enough elements; in the second, the element is the wrong

type.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

REVIEW QUESTIONS 1. What are the basic file operations available in Python? 2. Explain the syntax for opening a file. 3. Briefly explain various modes for opening a file. 4. What are the various attributes for a file object? 5. Explain the methods to read a file. 6. Explain with syntax of readlines(). 7. Explain the seek() and tell() metho in Python.

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to copy the contents of one file into another. 2. Develop a Python program to count the number of words in a text file. 3. Develop a Python program to count the number of lines in a text file. 4. Develop a Python program to read the contents of a file. 5. Develop a Python program to write the contents into a file. 6. Develop a Python program to append the contents into an existing file. 7. Develop a Python program to count the number of characters in a text file.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

CHAPTER - 2 - COMMAND LINE ARGUMENTS 2.1 INTRODUCTION

The python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes. They are:

1. sys.argv is the list of command-line arguments. 2. len(sys.argv) if the number of command-line arguments.

Here, sys.argv[0] is the program i.e., script name. To use it, you will first have to import it (import sys). The first argument, sys.argv[0], is

always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument: example.py:

import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments) print(count) Output: C:\Bhuvan>python example.py 10 20 30 3 The following is an example on how to read the argument from the command line:

args.py:

import sys for x in sys.argv: print("Argument: ", x) Output: C:\Bhuvan>python args.py Argument: args.py C:\Bhuvan>python args.py hello Argument: args.py Argument: hello C:\Bhuvan>python args.py hello world Argument: args.py Argument: hello Argument: world

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

len(sys.argv) , checks how many arguments that have been entered.

len(sys.argv) != 2 just checks whether you entered at least two elements arglen.py:

import sys if len(sys.argv) != 2: print("Usage: python arglen.py") sys.exit(1)

Output:

C:\Bhuvan>python args.py 10 20 30 Usage: python arglen.py C:\Bhuvan>python args.py 10

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

REVIEW QUESTIONS 1. What is command line argument? 2. Explain the purpose of sys.argv.

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PROGRAMMING EXERCISES 1. Develop a Python program to print the name of the python file and all its arguments using

command line argument. 2. Develop a Python program to print the sum of two numbers using command line argument. 3. Develop a Python program to concatenate the two strings using command line argument.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

CHAPTER - 3 - EXCEPTION HANDLING 3.1 INTRODUCTION

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately

otherwise it terminates and quits.

3.2. HANDLING AN EXCEPTION

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax:

Here is simple syntax of try....except...else blocks:

try: You do your operations here. ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax:

A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block

executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection.

Example:

This example opens a file, writes content in the, file and comes out gracefully because

there is no problem at all:

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can\'t find file or read data") else: print ("Written content in the file successfully") fh.close()

This produces the following result: Written content in the file successfully

Example:

This example tries to open a file where you do not have the write permission, so it raises an

exception: try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can\'t find file or read data") else: print ("Written content in the file successfully") This produces the following result: Error: can't find file or read data The except Clause with No Exceptions

You can also use the except statement with no exceptions defined as follows:

try: You do your operations here ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that occur. Using this kind of

try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

3.3 THE except CLAUSE WITH MULTIPLE EXCEPTIONS

You can also use the same except statement to handle multiple exceptions as follows: try: You do your operations here ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.

3.4. THE try-finally CLAUSE

You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this:

try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed.

Example:

try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print ("Error: can\'t find file or read data") fh.close()

If you do not have permission to open the file in writing mode, then this will produce the

following result:

Error: can't find file or read data

Same example can be written more cleanly as follows −

try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print ("Going to close the file") fh.close()

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

except IOError: print ("Error: can\'t find file or read data")

When an exception is thrown in the try block, the execution immediately passes to

the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

CHAPTER - 4 - MODULES AND PACKAGES

4.1 MODULES

Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:

def linecount(filename): count = 0 for line in open(filename): count += 1 return count

print(linecount('wc.py'))

If you run this program, it reads itself and prints the number of lines in the file, which is 7. You can also import it like this:

>>> import wc 7

Now you have a module object wc:

>>> wc <module 'wc' from 'wc.py'>

The module object provides linecount:

>>> wc.linecount('wc.py') 7

So that’s how you write modules in Python.

4.2 PACKAGES

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

We can import modules from packages using the dot (.) operator.

For example, if want to import the start module in the above example, it is done as follows.

import Game.Level.start

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

Develop a Python program to copy the contents of one file into another. input.txt Welcome to REC CSE Thandalam Program f1 = open("input.txt", "r") f2 = open("output.txt", "w") for line in f1: f2.write(line) f1.close() f2.close() output.txt Welcome to REC CSE Thandalam

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to count the number of words in a text file. input.txt Welcome to REC CSE Thandalam Program: f = open("input.txt",'r') now = 0 for line in f: word = line.split() now = now + len(word) print("No. of words :", now) f.close() Output: No. of words : 5

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

Develop a Python program to count the number of lines in a text file. input.txt Welcome to REC CSE Thandalam Program: f = open("input.txt",'r') nol = 0 for line in f: nol = nol + 1 print("No. of lines :", nol) f.close() Output: No. of lines : 3

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to read the contents of a file. input.txt: Welcome to REC CSE Thandalam Program: f = open("input.txt",'r') print("The content of the file is :") for line in f: print(line, end = "") f.close() Output: The content of the file is : Welcome to REC CSE Thandalam

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

Develop a Python program to write the contents into a file. Program: f = open("output.txt",'w') f.write("Welcome to\n") f.write("REC CSE\n") f.write("Thandalam\n") f.close() output.txt: Welcome to REC CSE Thandalam

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to append the contents into an existing file. output.txt: Welcome to REC CSE Thandalam Program: f = open("output.txt",'a') f.write("Welcome to\n") f.write("RIT IT\n") f.write("Thandalam\n") f.close() output.txt: Welcome to REC CSE Thandalam Welcome to RIT IT Thandalam

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

Develop a Python program to count the number of characters in a text file. input.txt Welcome to REC CSE Thandalam Program: f = open("input.txt", "r") count = 0 for line in f: for char in line.split(): count = count + len(char) print("Number of characters =", count) f.close() Output: Number of characters = 24

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to print the name of the python file and all its arguments using command line argument. Program: import sys print("Name of the Python file :", sys.argv[0]) print("Other arguments are:") for i in sys.argv[1:]: print(i) Output: C:\Bhuvan>python argcla.py REC CSE 10 20 Name of the Python file : C:\Bhuvan\argcla.py Other arguments are: REC CSE 10 20

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

Develop a Python program to print the sum of two numbers using command line argument. Program: import sys n1 = int(sys.argv[1]) n2 = int(sys.argv[2]) s = n1 + n2 print("The sum is :", s) Output: C:\Bhuvan>python sumcla.py 10 20 The sum is : 30

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Develop a Python program to concatenate the two strings using command line argument. Program: import sys s1 = sys.argv[1] s2 = sys.argv[2] s = s1 + s2 print("The concatenated string is :", s) Output: C:\Bhuvan>python cscla.py Raja lakshmi The concatenated string is : Rajalakshmi

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - V Part - A

Question Bank 1. List the basic file operations available in Python? In Python there are four basic file-related operations. They are:

1. Opening a file 2. Reading data from a file 3. Writing data to a file 4. Closing a file

2. Explain the syntax for opening a file.

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

file object = open(file_name [, access_mode][, buffering])

file_name − The file_name argument is a string value that contains the name of the file that you want to access.

access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. This is an optional parameter and the default file access mode is read (r).

buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value

is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default (default behavior). 3. What are the various modes for opening a file?

Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it

exists. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it

does not exist. 'b' Open in binary mode. '+' Open a file for updating (reading and writing)

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4. What is purpose of tell() and seek() methods?

The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. 5. What is command line argument in Python? Give example.

The python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes. They are:

1. sys.argv is the list of command-line arguments. 2. len(sys.argv) if the number of command-line arguments.

Here, sys.argv[0] is the program i.e., script name. To use it, you will first have to import it (import sys). The first argument, sys.argv[0], is

always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument: example.py:

import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments) print(count) Output: C:\Bhuvan>python example.py 10 20 30 3

6. How exceptions are handled in Python? Give its syntax.

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax:

Here is simple syntax of try....except...else blocks:

try: You do your operations here. ......................

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.

7. List the standard exceptions Python?

Following is a list of Standard Exceptions available in Python: ZeroDivisonError KeyboardInterrupt IndexError NameError IOError TypeError ValueError

8. When the ZeroDivisionError exception is raised in Python?

Raised when division or modulo by zero takes place for all numeric types. 9. When the IOError exception is raised in Python?

Raised when an input / output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.

10. When the IndexError exception is raised in Python?

Raised when an index is not found in a sequence. 11. Explain the except clause with multiple exceptions.

You can also use the same except statement to handle multiple exceptions as follows: try: You do your operations here ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

12. What is a module in Python? How to use modules?

A module is a file that contains a collection of related functions.

Before we can use the functions in a module, we have to import it with an import statement:

>>> import math This statement creates a module object named math.

13. What is the purpose of math module?

Python has a math module that provides most of the familiar mathematical functions. 14. How to access functions and variables available in modules? Give example.

The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians)

15. What is a package?

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

16. Explain the concept of packages with an example.

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

We can import modules from packages using the dot (.) operator.

For example, if want to import the start module in the above example, it is done as follows.

import Game.Level.start

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

RAJALAKSHMI ENGINEERING COLLEGE Thandalam, Chennai - 602 105

Department of Computer Science and Engineering GE17151 - PROBLEM SOLVING AND PYTHON PROGRAMMING

Unit - V Part - B

Question Bank 1. Explain in detail about the various modes for opening a file in Python with suitable

examples.

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

file object = open(file_name [, access_mode][, buffering])

file_name − The file_name argument is a string value that contains the name of the file that you want to access.

access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. This is an optional parameter and the default file access mode is read (r).

buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value

is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default (default behavior).

While opening a file, we can specify whether to read (r), write (w) or append (a) data to the file and also specify whether to open in text or binary mode.

The default way of opening is in read (text mode). In text mode, we get strings while

reading from the file. In binary mode, it returns bytes and are used with non-text files like jpeg or exe files. The different modes for opening a file are as follows:

Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it

exists. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it

does not exist. 'b' Open in binary mode. '+' Open a file for updating (reading and writing)

Writing into a file

A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM. To write a file, you have to open it with mode 'w' as a second parameter:

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

>>> fout = open('output.txt', 'w')

If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created.

open returns a file object that provides methods for working with the file. The write method puts data into the file:

>>> line1 = "This here's the wattle,\n" >>> fout.write(line1) 24

The return value is the number of characters that were written. The file object keeps track

of where it is, so if you call write again, it adds the new data to the end of the file: >>> line2 = "the emblem of our land.\n" >>> fout.write(line2) 24

When you are done writing, you should close the file:

>>> fout.close()

If you don’t close the file, it gets closed for you when the program ends.

Reading from a file

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

>>> fin = open('output.txt')

fin is a common name for a file object used for input. The file object provides several methods for reading, including readline, which reads characters from the file until it gets to a newline and returns the result as a string:

>>> fin.readline() "This here's the wattle,\n"

The first line in this particular file is “This here's the wattle,\n”. The sequence \n represents

whitespace character, a newline, that separate this line from the next.

The file object keeps track of where it is in the file, so if you call readline again, you get the next line:

>>> fin.readline() 'the emblem of our land.\n' The next line is “the emblem of our land.\n”. Or, if it’s the whitespace that’s bothering you,

we can get rid of it with the string method strip:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

>>> fin = open('output.txt') >>> lines = fin.readline() >>> line = lines.strip() >>> line "This here's the wattle," You can also use a file object as part of a for loop. This program reads output.txt and prints

line by line: fin = open('output.txt') for lines in fin: line = lines.strip() print(line) fin.close() Output: This here's the wattle, the emblem of our land.

2. Explain the usage of command line arguments in Python with examples.

The python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes. They are:

1. sys.argv is the list of command-line arguments. 2. len(sys.argv) if the number of command-line arguments.

Here, sys.argv[0] is the program i.e., script name. To use it, you will first have to import it (import sys). The first argument, sys.argv[0], is

always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument: example.py:

import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments) print(count) Output: C:\Bhuvan>python example.py 10 20 30 3 The following is an example on how to read the argument from the command line:

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

args.py:

import sys for x in sys.argv: print("Argument: ", x) Output: C:\Bhuvan>python args.py Argument: args.py C:\Bhuvan>python args.py hello Argument: args.py Argument: hello C:\Bhuvan>python args.py hello world Argument: args.py Argument: hello Argument: world len(sys.argv) , checks how many arguments that have been entered.

len(sys.argv) != 2 just checks whether you entered at least two elements

arglen.py:

import sys if len(sys.argv) != 2: print("Usage: python arglen.py") sys.exit(1)

Output:

C:\Bhuvan>python args.py 10 20 30 Usage: python arglen.py C:\Bhuvan>python args.py 10

3. Explain in detail about how exceptions are handled in Python.

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately

otherwise it terminates and quits.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax:

Here is simple syntax of try....except...else blocks:

try: You do your operations here. ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax:

A single try statement can have multiple except statements. This is useful when the try

block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block

executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection.

Example:

This example opens a file, writes content in the, file and comes out gracefully because

there is no problem at all:

try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can\'t find file or read data") else: print ("Written content in the file successfully") fh.close()

This produces the following result: Written content in the file successfully

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

4. Briefly explain the usage of modules and packages in Python with examples. Modules

Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:

def linecount(filename): count = 0 for line in open(filename): count += 1 return count

print(linecount('wc.py'))

If you run this program, it reads itself and prints the number of lines in the file, which is 7. You can also import it like this:

>>> import wc 7

Now you have a module object wc:

>>> wc <module 'wc' from 'wc.py'>

The module object provides linecount:

>>> wc.linecount('wc.py') 7

So that’s how you write modules in Python.

Packages

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

We can import modules from packages using the dot (.) operator.

For example, if want to import the start module in the above example, it is done as follows.

import Game.Level.start

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7