0% found this document useful (0 votes)
22 views30 pages

Chapter Intro To Python

Python notes

Uploaded by

kartikgujjar541
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download as pdf
0% found this document useful (0 votes)
22 views30 pages

Chapter Intro To Python

Python notes

Uploaded by

kartikgujjar541
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download as pdf
Download as pdf
You are on page 1/ 30
| | | 3.1 INTRODUCTION TO PROBLEM-SOLVING Computers help us solve problems but they have no intelligence or thinking power. A computer performs many tasks exactly in the manner as instructed. However, before a problem can be tackled, we need to understand the problem and the ways to solve it. So, in order to instruct a computer correctly, the user must have clear understanding of the problem to be solved. Irrespective of the programming language being used, the first and foremost thing while writing a program is to analyze the problem well and try to solve it in a logical manner. The process of writing a program is called “Programming”. Thus, when we write a program, we need to first clearly understand the problem as well as its solution, otherwise we will end up writing incorrect or inefficient codes. When we write a program, we are writing a set of instructions to solve a problem involving data processing, These instructions must be executed by the computer to solve the problem. If the instructions are correct and given in the right sequence, then the problem will be solved properly by the computer. But if the instructions are incorrect or in the wrong sequence, then the problem will not be solved correctly or will not be solved at all. Fig. 3.1: Computer Programming Therefore, writing correct instructions in proper sequence is extremely important. It means that before we start writing a program, the steps for solving the problem should be clear in our mind. Precise step-by-step instructions should be inputted to the computer system to solve the problem. Thus, proper and flawless execution of any task inside a computer depends on how correctly and precisely we define the problem, design a solution (algorithm) and implement the solution (program) using a programming language. Problem-solving, therefore, is the process of identifying a problem, developing an algorithm for the identified problem and finally implementing the algorithm to develop a computer program. 4.2 STEPS FOR PROBLEM-SOLVING ‘There area number of problems in our day-to- siinple interest, and all problems require proper problem-solving rm Is the act of defining 4 problem, determining the cause of the prob and selecting alternatives for a solution, and implementing a solution. the Problen Fig, 3.2: When problems are 6 complex problem requi ightforward and eas ti a methodic right solution. In other words, ing begins with the precise orking solution in terms of a program using 4 computer are shown in | identification of the problem and ends with a o or software, The key steps required for 5 Fig, 4.3 and discussed in the following sub-sections, am SS. Fig. 3.3: Steps for Problem-solving 3.2.1 Analyzing a Problem Itis important to clearly understand a problem before we begin to find a solution to it. If we not clear as to what is to be solved, we may end up developing a program which our purpose. Thus, we need to read and analyze the problem statement carefully the principal components of the problem and decide the core functionalities that should have, By analyzing a problem, we would be able to figure out what are Program should accept and the outputs that it should produce. femme Getting Started with Python sessumsnsomsscsennssrsseesssscsnesaan eee 3.2.2 Developing an Algorithm It is essential to devise a solution before writing a program code for a given problem. set of sequential steps usually represented in natural language is called an algorithm. ween imagine an algorithm like a very well-written recipe for a dish with clearly defined steps which, jf followed, one will end up preparing a good dish. We start with a tentative solution plan and keep on refining the algorithm until the algorithm is able to capture all aspects of the desired solution. For a given problem, more than one algorithm is possible and we have to select the most suitable solution. The algorithm is discussed in the next section. 3.2.3 Coding [After finalizing the algorithm, we need to convert the algorithm into a format which can be understood by the computer to generate the desired solution. Different high-level programming tanguages can be used for writing a program. It is equally important to record details of the coding procedures followed and document the solution. This is helpful when revisiting the programs at a later stage. 3.2.4 Testing and Debugging The program created should be tested on various parameters. The program should meet the requirements of the user. It must respond within the expected time. It should generate the correct output for all possible inputs. In the presence of syntactical errors, no output will be obtained. In case the output generated is incorrect, then the program should be checked for logical errors. if any. The software industry follows standardized testing methods like unit or component testing, integration testing, system testing, and acceptance testing while developing complex applications. This is to ensure that the software meets all the business and technical requirements and works as expected. The errors or defects found in the testing phases are debugged or rectified and the program is again tested. This continues till all the errors are removed from the Progam: Once the software application has been developed, tested and delivered to the user, still problems in terms of functioning can crop up and need to be resolved from time to time. The maintenance, ofthe solution, thus, involves fixing the problems faced by the user, answering the queries of the user and even serving the request for addition or modification of features. The problem-solving stages explained above help in developing computational thinking and, in turn, offer proper, accurate and complete solution to a given problem. 3.3 ALGORITHM In our day-to-day life, we perform activities by following a certain sequence of steps, Examples of activities include getting ready for school, making breakfast, riding a bicycle, wearing a tie, ity, we follow a sequence of steps. solving a puzzle and so on. To complete each acti Suppose the following steps are required for the activity ‘Riding a car’: 1. Move the car out of the garage. 2. Sit in the driver's seat. 3. Put key in the ignition and start the car. 4. Press the clutch and put gear in the correct position. 5. Accelerate and start driving, 6. Use brakes whenever needed. 7. Stop on reaching the destination. i What is an Algorithm? 7 ae | | | | Algorithm ~ Let us look at another example of calculating and displaying the sum and the average of threg numbers, Step 1: Start Step 2: Read the three numbers, let us say “a’, “b’, “c’ from the user Step 3: Declare a variable “Sum” and “Avg” Step 4: Calculate sum of three numbers, such as Sum =a +b +c Step 5: Calculate average of three numbers, such as Avg = Sum/3. Step 6: Display “Sum’ and “Avg” Step 7: End Hence, itis clear that we need to follow a sequence of steps to accomplish the task. Such a finite Sequence of steps required to get the desired output is called an algorithm. It will lead to desired Tesult in a finite amount of time, if followed correctly. Algorithm has a definite beginning anda definite end, and consists of a finite number of steps, 3.3.1 Need for an Algorithm A programmer writes a program or set of instructions to instruct the computer to do certain tasks to get the desired output. The computer then follows those instructions written in the Program code. Thus, the programmer initially formulates the instructions in simple and easy language before actually writing the source code. Without doing this, the programmer may not be able to clearly visualize the instructions to be written and instructions may end up developing a program which may not work as expected, In simple English, language is nothing but the algorithm which is the building block of a computer Program. For example, searching using a search engine, sending a message, finding a word ina document, booking a taxi through an app, using online banking, playing computer games—all are based on algorithms, Orrect, computer will run the program correctly, every time. So, the purpose of using an algorithm is to increase reliability, accuracy and efficiency of obtaining solutions. Thus, algorithmic problem-solving actually comes in two phases; developing of an algorithm that solves the problem and conversion of the algorithm into code, ‘The latter, usually known as Coding, is comparatively easier since the logic is already present —it ig just a matter of ensuring that the syntax rules of the programming language are adhered to, oi a Computer Science wih Python-XI = 4 aan (A) Characteristics of a good algorithm + Precise — the steps are precisely stated or defined. + Unique — results of each step are well defined and only depend on the inputs and the result of the preceding steps. + Finite — the algorithm always stops after a finite number of steps. + Input — the algorithm receives some input. * Output — the algorithm produces some output. Well-defined Outputs Well-defined Inputs Clear and teristics {Unambiguous| Algorithm bl Language- 2 independent ie required to clearly identify the following: (B) While writing an algorithm, i + The input to be taken from the user. + Processing or computation to be performed to get the desired result. + The output desired by the user. 3.4 REPRESENTATION OF ALGORITHMS Software programmers apply their algorithmic thinking skills to examine the problem and determine the logical sequence of steps required to obtain a solution. After identifying the steps, it is necessary to write down these steps along with the required input and desired output. There are two common methods of representing an algorithm—flow chart and pseudocode. 3.4.1 Flow Char sual Representation of an Algorithm A flow chart is the pictorial representation of an algorithm. It is defined as a visual representation of the sequence of steps and decisions needed to perform a process/task. A flow chart is used to represent how a program works. In other words, a flow chart depicts the “flow” of a program, i.e. the breakdown of a task into separate steps as shown in Fig. 3.4, It shows all the steps of 7A a process. Being visual, it helps in understanding the logic of a task quickly. Thus, flow charts are used in analyzing, designing, documenting or managing a process oF program, Specific parts of the flow chart represent specific parts of your code. A flow chart, when translated into a proper computer language, results in a complete program. Getting Started with Python, There are standardized symbols to draw flow charts, Some of them have been given in Table y Table 3.1: Commonly-used Symbols in a Flow Chart Se mM oe Start/End ‘Ovals show a start point or end point in the code etween different parts of the code, ¢ ae Arrows show connection between different parts of the code, called Connectors Process Rectangles show processes eg., calculations (most things the computer does that do not involve an inpyy, ‘output or decision) y f AE Input/Output Parallelograms show inputs and outputs (remember print is normally an input) Conditional/Decision Diamonds show a decision/condlition (this normally depicts if, else, iFelif-else, while and for) @ Connector Represents the ongoing flow across multiple charts © pages, Note: You may use online diagram software “draw.io” for making flow charts online, How to Make a Flow Chart Flow chart allows you to make a complicated process or task easier to understand, Knowing how to make a flow chartis a valuable skill. The best flow charts are simple and clear, and effectively communicate each step of the process. The seven basic steps for making Step 1: Know the purpose of your flow chart. Step 2: Start with a template, Step 3: Add shapes and symbols, Step 4: Connect your shapes with lines and arrows. Step 5: Split paths or add decisions, 1 flow chart are: Step 6: Customize your flow chart’s appearance. Step 7: Download or share your flow chart. Let us understand flow chart through a few examples. Example 1: Draw a flow chart to find average of three numbers, Ans. > Start by oval shape : avg=(a+b+0)/3 C stop )>———— > End/terminate by oval shape » A parallelogram to input values ® Arectangle for processing ® A parallelogram to display output Computer Stonce with Python Xt qo solve this problem, we will axk the user lo enter three values which get stored in three variables, a, b, © respectively, We will then calculate the average of three varlables and store it jna variable ‘avg’ Finally, we will print the value stored in the variable ‘avg’ Let us see another example to create a flow chart, Rxample speed Net Ltd, plans (o give a 76 year-end bonus to each of Its employees earning & 20,000 or more per month and a fixed & 1,500 bonus to the remaining employees. Draw a flow chart for cateulating the bonus for an employee. Ans. C start >) 1 Input Salary of Employee I No. ts Yes. Salary>=20000?>——-—»]Bonus=0,07*Salary Bonus = 1500 1 C sop > CCTM: Flow chart is the pictorial representation of step-by-step solution to a given problem. Pseudocode is another way of representing an algorithm, It is used to express our Logie independent of any programming language. As the name suggests, it is not a real code it is an. informal approach in English-like language about how we will solve a problem. ociated with writing a pseudocode; it could be a list of instructions in 2 language. Using it, we can easily break down a. -parts and give us better clarity about how we can explained using a real-life example of making nding an astronaut to the There are no rules ai English-like language or in any programm’ bigger problem into smaller modules or solve a particular program or a process. This can be a phone call from a smartphone. Another example we have taken is Moon for navigation as shown in Making a phone call Sending Man to the Moon 1. Unlock Phone —— 2, Open Contacts 3, Search for Contact) Pseudocode A. Launeh 4. Make a Call 2. Navigate to the Moon 5. End Call 3.Land on the Moon Fig, 3.5: Examples of Pseudocode ~ Getting Started with Python = Python is interpreted, interactive, dire that it is processed at run-time by the interp before executing it > Itisa loosely typed Object-Oriented Pro: words) and simple En, ce an porta Itis a free open-sow > Ittakes less time to develop Pytho shorter than equivalent pri Decause of its built-in high-level i > Iris extensible /extendable and hi | types of variables or arguments } Itsupports GU! (Graphical User Interface) and G. > itis easily compatible with other > Python is used for both scientitic anc 3.6.2 Advantages of Pytho Apart from the above salient features, Python o {a) Platform-Independent: It is plattorm-ind systems/platforms like Windows, Linux/Unix, macOS {b) Readability: Python programs use clear, simple, concise are easy to read and understand even by non-programmers ¢ programming background. (©) Object-Oriented Programming Language: |t is 2 Oriented Programming Language. interactive, | (@) Higher Productivity: Since Python is a simple language with small codes and extensive libraries, it offers higher productivity to programmers than languages like G++ and Java So, you write less and get more done. 3 (e) Less Learning Time: Because of a simple and shorter code, lesser time is required to understand and learn Python programming. () GUIProgrammin system calls, librai Class Libr 'ython supports GUI applications that can be created and ported to many and Windows systems such as Windows MFC (Microsoft Foundation -y), Macintosh and the X Window system of Unix. (g)_ Ample Availability of Libraries: It provides large standard libraries to solve a task. (h) Syntax Highlighting: input, output and error messages by different color codes. allows distinguishing betwee! 3.6.3 Limitation: Apart from several advantages that Python offers which make it one of the most popular programming languages, it has a few limitations as well. (a) Speed: Python is slower than C or C++. However, Python is a high-level language unlike C or C++; it is not closer to hardware. le Development: Python is not a very good language for mobile development. It is seen as a weak language for mobile computing. This is the reason very few mobile applications are built in it. (b) (c). Memory Consumption: Python is not a good choice for memory-intensive tasks. Due to the flexibility of the data types, Python's memory consumption is also high. (d) Database Access: Python has limitations with database access. As compared to popular technologies like JDBC (Java Database Connectivity) and ODBC (Open Database | Connectivity), Python's database access layer is found to be a bit underdeveloped and primitive. It cannot be applied in the enterprises that need smooth interaction of complex legacy data. (ec) Runtime Errors: Python programmers have cited several issues with the design of the language. Because the language is dynamically typed, it requires more testing and has errors that only show up at run-time. 3.7 INSTALLING PY Ever since Python language was first developed, it has been becoming popular day by day among programmers. Several versions of Python have been released till now, beginning with Python 1.0. We shall be working on Python 3.6.5; however, any 3.x version can be used to implement Python programming concepts as per CBSE guidelines. Before we start working, Python needs to be installed on our system. To install Python, we must first download the installation package of the required version from the link/URL given below: https://www.python.org/downloads/ For installation details, scan This Python distribution comes with Python ID Program (Python Package Manager). Python Interpreter and Preferred Inst Python is a flexible, dynamic and powerful language that can be used in different ways. It can jy, interactively used simply to test a code or a statement line by line or while exploring its interface To write and run Python programs interactively, we can either use the command line windoy, or the IDLE. IDLE is a simple Integrated Development Learning Environment that comes with | Python. The most important feature of IDLE is that it is a program that allows the user to edit, Tun, browse and debug a Python program from a single interface. When we first start Python IDLE by clicking on its icon created on the desktop or menu item on the START menu -> Apps by name -> IDLE (Python 3.6.5 32-bit) option, it always starts yp in the shell, 4 Fig. 3.8: Starting Python Shell Python shell is an interactive window where we can type in the Python code and see the output in the same window. It is an interface between Python commands and the OS. Be e Computer Science with Pon eae 7" SS ee _— ee by TM: The interactive interpreter of Python is termed as Python Shell. python IDLE comprises two working modes—Python shell (Interactive mode) and Python Editor (Script mode). eat et Oy ees Ye Python 3.6.5 (v3-6.5:£990832b4, Mar 28 2018, 16:07 ¥. (00 32 bit (Intel)} on win32 BP A ype "ecpyrignt, "credits or “License ()* for nore Information Python Shell Python Editor n opening, Python shell shows a welcome message displaying its version and a copyright notice. After this, the command prompt (>>>) followed by a blinking cursor gets displayed, which indicates that IDLE is now ready to take Python commands from the user (Fig. 3.9(a))- Python 3.6.5 (v3.6.5: £59c0932b4, Mar 28 2018, 16:07:46) (use 00 32 bit (Intel)] on win32 Type “copyright”, "credits" or "license()" for more information. >>> | _—_——> Start typing here ‘When we open Python Interactive | mode, Python shell with prompt (>>>) _gets displayed for the user to enter the ‘commands crecty infront of Fig. 3.9(a): Interactive Python Shell Learning Tip: Python shell displays the prompt >>> to indicate that it is waiting for a user command to be entered. This is the Python shell, which is part of Python's Integrated Development Environment. The three greater than signs (>>>) are called the prompt or Python command prompt. 3.8.2 Command Line Interaction When commands are entered directly in IDLE from the keyboard, the Interpreter/IDLE is said to be in Interactive mode. In Interactive mode, type the command “Hello World” in front of the prompt (>>>) and press Enter: See what happens. RT ine ——— >» Our First Program So, we bewin with our first command in Python Interactive made ay Hustrated belay, Practical Implementation-1 Mar 26 2018, 16107146) (Mee v.15 wind? weredita” or "License ()" for more information, Je in Python Shell Fig. 3.9(b): Displaying Mess atement, It gets the Enter key after typing our first executed immediatly and the output is displayed then and th Alternatively, this can be done using the print() function as shown in Fig, 3.9(c) given below, Te at Hut Dany Opes Yn Wp Python 3.6.5 (v3.6.5:£59009%2b4, Mar 2 2018, 16:07:46) (MSC v.1900 32 bit (Intel) on wind Type "copyright", “credits” or “License()" for more into | mation. | >>> prin Hello World >>> print ("Welc ver cua} Fig. 3.9(c): Displaying Multiple Messages using print() function in Python Shell In the above case, we have given two print() statements for displaying two different messages upon pressing the Enter key. > Print method It has now become evident that we can give commands at the primary prompt and see immediate results. print() is a function which is used to display the specified content/result on the sereem (VDU: Visual Display Unit). The content (called argument) is specified within the parentheses. print() function without any arguments will simply jump to the next line. Python is a case-sensitive language. This means that Python differentiates between and small alphabets. For example, Print (P capital) and print (p small) are two different for Python. Whereas print is a valid command keyword in Python, Print is just a word and ‘command, This can be observed by typing the command Print ("Hello World"). eed & Computer Science

You might also like