You are on page 1of 32
and Getting Started with Python 4.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 eee, presi 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 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. 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 (elgorithim) 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. calculating simple interest, and all problems require proper : Problem-solving is the act of defining a problem, determining the cause of the identifying, prioritizing and selecting alternatives for a solution, and Implementing a Understand Create the Problem a Plan the PI Fig, 4.2: Concept of Problem-solv When problems are straightforward and easy, we can find solutions other words, the precise of a program r are shown if complex problem requires a methodical approach to find the right we have to apply problem-solving techniques. Problem-se identification of the problem and ends with a complete work or software. The key steps required for solving a prot Fig, 4.3 and discussed in the following sub-section sis Ear) Bac Testing and Bal Debugging Fig. 4.3: Steps for Problem-solving 4.2.1 Analyzing a Probl to figure o eptand the outputs that it should produce, at 37° RE 4.2.2 Developing an Algorithm Iris essential to devise a solution before writin Ait tens : 8 4 program code for a given problem. The set Bealeton lee fepreeenied in natural language is called ee aigoeiee We can imag ery well-written. ecipe for a dish wi Se pe for a dish with clearly defined steps which, Baa oe “ee UP Preparing a good dish. We start with a tentative solution plan and Boh FOr E given pects nt! the algorithm ts able to capture all sayeew GFems aaa jon. For a given problem, more solutio Diitioe prem more than one algorithm is possible and we fave sels most suitable solution, The als sed in the next section, gorithm is discu: 4.2.3 Coding Bie Healizing the algorithm, we need to convert the algorithm {nto « format WHiEH Ean understood by the computer to generate the desired solution. Different high-level programming @ program. It is equally important to record details of the nd document the solution. This is helpful when revisiting the languages can be used for writing coding procedures followed a programs at a later stage 4.2.4 Testing and Debugging The program created should be tes rn meters, The program should meet the t e obtained. In requirements of the user. | pected time, It should gen output for all possible input tacti ors, no output will ate cori case the outpu ; ene m should be checked for logical errors, if any. The software ind f hods like unit or component testing, integration testing, syster y loping complex applications. This is to ensure that th hnical requirements and works ed or rectified and the expected. The errc ing phases are ¢ program is m the program. Once the software applicatio' : nd delivered user, still problems in terms of functioning can crop up a rom time to time. The maintenance of the solution, thus, involves fixin < faced by the user, answ queries of the user and even serving the request f tion 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 1 problem. 4.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, Solving a puzzle and so on. To complete each activity, we follow a sequence of steps. 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 ¢ brakes whenever needed reaching the destination. < > Cy « What is an Algorithm? a Set of rule? : eeounte Sapa i expected output from the given input Algorithm 1 Divisor (GCD) of two numbe Let us look at another example of finding the Greatest Common Di 7 45 and 54. Note: GCD is the largest number that divides both the given num! mber Jivide the given nu Step 1: Find the numbers (divisors) which cal Div 5 are 9, 15 and 4 lists, which i Step 2: Find the largest cor . (B) I t mpl Prepares ap of the i road map, the programmer 1 ast may end up developing a progra sad map is nothing but the algorithm which is the bu 1 ple, searching using a search engine, se I . daca sooking a tad Ge an app, using online banking, ; comp are based on algorithms Writing an algorithm is mostly considered algorithm to solve a problem, we can the computer in high-level language » programming. Once we h write the computer program for giving instructions Ifthe algorithm j correctly, every time. So, the purpose of usir correct grat orrect, computer will run the progt]l porithm is to increase reliability, accumaa and efficiency of obtaining solutions. Thus Phases: derivation of Into code, The latter, usually known as coding, i Present—it is just a matter of adhered to. algorithmic problem-solving , actually comes int algorithm that solve the problem and conversion of the algorit comparatiy nsuring that the sy ely easier since the logic is area ntax rules o MAX rules of the progr amming language Thus, Progr When (A) Characteristics of a good algorithm 7 jee treciston —~ the steps are precisely stitad or defied oe + Uniqueness — results of each rt the result of the preceding Wee ‘ep are well defined and only depend on the input and , ne | + Finiteness — the algorithm always stops after a finite number of steps. | * Input — the algorithm receives some input. * Output — the algorithm produces some output. Characteristics of an Algorithm aE a] | Well-defined | Well-defined | Inputs | Outputs Clear and Characteristics Unambiguous of an Algorithm nn | Language. |, —~ a | “e ~ independent ee (B) While writing an algorithm, it is required to clearly iden fy the following: * The input to be taken from the * Processing or computation to be performed to get the desired result. + The output desired by the user 4.4 FLOW CHARTS—VISUAL REPRESENTATION OF AN ALGORITHM A flow chart is the pictorial representation of a task. It is defin 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, ie, the breakdown of a task into separate steps as shown in Fig, 4.4. It shows all the steps of a process. Being visual, it helps in understanding the logic of a task quickly. = sala \ i | | ain Fig. 4.41 king and Getting Started with Python Thus, flow charts are used in analyzing, designing, documenting or managing a process oF program, Specific parts of the flow chart represent specifi parts of your code, A flow chart vhen translated into a proper computer language, results in a complete program. isin a Flow Chart ee int in the code used symbol moni se Sara a start point or end P* pin ‘ ‘ovals show ama 1 parts of the code nection between different ‘arrows show con Connection Rectangles show processes Process ions not involve an = Fa i the computer does that do (most things Wall uts and outputs Let us understand flow chart through an example. Example 1 Draw a flow chart to find ave ‘ Stop y oval shap To solve this problem, we variables, a, b, c respectively ina variable ‘avg’ Finally, we Il ask the user to enter three e will then calculate the ill print the value values which get stored in three average of thre variables and store Stored in the variable ‘avg VAtUs see another example to create a flow chart Example 2; Speed Net Ltd. plans to give more per month and a fixe calculating the bonus for a 47% year-end bonus to ¢ d% 1,500 bonus n employee. ach of its e1 ‘mployees earning & 20,000 of 5 to the remaining employees. Draw a flow chart fot cm 4.4. Input Salary of Employee Bonus = 1500 NO (s Salary>=20000 Bonus=0.7*Salary 7 _ Display Bonus CCIM: Flow chart is the pictorial representation of step-by-step solution to a given proble ae 4.4.1 Pseudo-code Pseudo-code is used to express our logic 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 ‘There are no rules associated with writing a pseudo- code; it could be a list of instructions in English-like language or in any programming language. Using it, we can easily break down a bigger problem into smaller modules or sub-parts and give us better clarity about how we tan solve a particular program or a process. This can be explained using a real-life example of making a phone call from a smartphone. Another example we have taken is sending an astronaut to the Moon for navigation as shown in Fig. 4.5 = Sending Man to the Moon 4 . lock Phone le fim" ?) 2.Open Contacts j vtouner EW Search for Contact) Pseudo-code fi Pseudo-code 2.Navigate to the Moon 4, Place a Call 3.Land on the Moon 5.End Call Fig. 4.5: Examples of Pseudo-code Asis evident from the previous figure, the pseudo-code defined the steps involved in solving above problem in simple steps using English-like structure. A good pseudo-code should: be in a specific coding language, the structure of your code, Getting Started with Python ru) Example 3: Write a pseudo-code that reads marks of te Ans, Set total to zero. Set marks counter to one While marks counter is less than or equal to ten Input the next marks ‘Add the marks into the total Set the average by dividing total by ten Display the average. Example 4: Write a pseudo-code along with Python code to get a user's concatenate this name with “Hello” message as ‘Hello [Name] wn students and displays averaBe of marks. ’s name as the input and then Ans. a input username name = input("What is your name?") output "Hello username” print(’Hello" + name) [TGTM: Pseudo-code is a simple and informal way of writing programming code in English. There are no | standard rules to write Pseudo-code. 4.5 WHAT IS COMPUTATIONAL THINKING If we start writing a program without knowing how to solve the problem, we can never write the correct program. This leads us to the concept of Computatioi edia defines Computational Thinking as the thought processes in 1 formulating a problem and expressing its solution(s) in a way that a man or machine can effectively carry out. So, to write any program, first we have to think computationally—about the problem and its solution—and then we have to write the program in a programming languag But every day, in all aspects of our lives, we perform Computational Thinking, Think of the following actions and decisions that go into then * You want to make yourself a cup of tea or coffee * You want to buy a car * You want to change job. * You want to move to another city. * You want to buy a house. * You want to write a book * You want to create an app. aaa Bapeetouehe Processing for finding the be a crucial aspect Computational Thinking allows us to t develop possible solutions. We can the human, or both, can understand. ‘st solution and, thus, ‘ake a complex problem, understand what it is, and N present these solutions in a way that a computel @ Th of th © in ca Le Ieetesttanar thes sence Eaucnces cone ae Fig. 4.6: Computational Thinking The process of planning and reaching the goals involves Computational Thinking of some kind. Computational Thinking involves taking a complex problem and breaking it down into a series of small, more manageable problems (decomposition). Each of these smaller problems can then be looked at individually, considering how similar problems have been solved previously (pattern recognition) and focusing only on the important details, while ignoring irrelevant information (abstraction). Next, simple steps or rules to solve each of the smaller problems can be designed (algorithms) let us discuss the components of Computational Thinking in detail. 4.6 COMPONENTS OF COMPUTATIONAL THINKING Computational Thinking is a technique used to solve problems logically and consists of four key components or pillars described as follows: * Decomposition = Pattern Recognition © Abstraction © Algorithms Erne s stage involves breaking down the problem into smaller components so that they can be tackled easily, The more ‘we can break down a problem, the easier it is to solve. Fig. 4.8: Decomposition ° Some real-life examples of the decomposition process are: ae ee & When we taste an unfamiliar dish and identify several ingredients based on the flavour, are decomposing that dish into its individual ingredients. = When we give someone directions to our house, we are decomposing the Process of getting from one place to another (e,g. city, state, etc.) : ® When we breaka course project into several steps, we are decomposing the task into smaller, more manageable sub-tasks. in Mathematics, we can decompose a number such as 256.37 as follow 2°107+5*10'+6*10°+3*10-+7*107 e Ifwe Letus look ata more specific example—the equation to work out the roots of a quadratic equation ay Fo = We k have (On first look, solving this equation might appear a little scary but if we decompose it, we will cat stand a better chance to solve it: we ca a4 2. pe We | 3. bP- 4ac 4. vb°-4ac situa’ 5. -bsVb? -4ac 6. 2a 7 tis ; x ee 8, repeat for x,=—>— 2a 2a a By noting down the steps to solve a problem, we can often recognize patterns, and by giving = list of steps, we are one step closer to creating an algorithm. Patte This stage also allows us to develop a better understanding of the problem we face by identijii do ye all the components in detail. comy 4.6.2 Pattern Recognition Pattern Recognition is the next process in succession that helps in : Patterns or trends within a problem. These patterns solve the larger problem more effectively. Once we have 'a complex problem into smaller problems, the next step distinguishing attributes (colour, shape, size), extract terns. We look for patterns when we play tain things. Based on experience, we Fi9+4.9: Pattern to arrive at a solution. we want to draw a series of cats, ; sg share common characteristics. Amon; ‘igo like to eat fish and make i other things, they all have eyes, tails and fur. They meowing sounds. Because we know thal s . tall cats have eyes, tails and furs we can pe od attempt at drawing a cat simply by including these common characteristics. In ee ne these characteristics are known as patterns. Once we know how to describe one cat, we can describe others by simply foll things that are different are the specifics: iit | « one cat may have green eyes, a long tail and black fur | « another cat may have yellow eyes, a short tail and striped fur Ifwe want to draw a number of cats, finding a pattern to describe cats in general, for example, they all have eyes, tails and fur, makes this task quicker and easier. We know that all cats follow this pattern, so we don’t have to stop each time we start to draw a new cat to work this out. From the patterns we know cats follow, | - we can quickly draw several cats. Jt in everyday et We experience pattern recognition situations like: © Drivers look for patterns in traffic to decide whether and when to switch lanes. 4 © People look for patterns in stock prices to decide when to buy or sell. © Scientists look for patterns in data to derive theories and models. © We look for patterns and learn from them to avoid repeating the same mistake. Patterns are shared characteristics that occur in each individual problem. What similarities do you observe? Finding these similarities in small decomposed problems can help us solve Started with Pyth complex problems more efficiently. 48.3 Abstraction *Abstraction” refers to focusing on important information only, ignoring irrelevant details. To reach a solution, we need to ignore unnecessary Characteristics in order to focus on relevant details. It helps us identify similarities and differences between similar problems to work a solution. important in! formation that we need to focus on? In ‘on general characteristics that are common, Fig. 4.10: ess are: Common examples of paar oe ar terms of longitude and latitude, helping y action hy of a place. tis an abstraction of th @ Aworld map is an abst describe the location and geograP! items available in that aisle e.g», Walmal @ Asign of anaisle in a store— @ When we write a book report, we summ the book; it is abstraction. arize and discuss only the theme oF key aspects of 0 eate a “model” of the problem; a mod, nce we have the general characteristics, we can nee mod Nl being the : x to solve. ng the general idea of the problem we are trying to solv Once we have a model, we can design an algorithm. 4.6.4 Algorithm Writing We have broken down the big problem into small¢ problems. We have identified similarities between the 1 {ignored anything irrelevant. We have focused on relevant details and ignored anything irrelev pm t solve each of the 2 Now it is time to develop step-by-step instructions to or, easily manageable ese problems 9 follow when solving the problem ; program a computer to help » Fig. 4.11: Algorithm Writing smaller problems, or the ru These simple steps or rules are solve a complex problem in the best poss! hey are alsc called “algorithms Defini jon: An algorithm is a p! used to solve a problem, Writing an algorithm requires tly. The solution thatthe computer offers is as good as the alge m is not good, then o solution will not be good either 4.7 PYTHON PROGRAMMING LANGUAGE When we encounter the word ‘Python i reptile. However, the programming langu: because just as the reptile has a flexible bod: simple and highly flexible. th Python is an open source, object-oriented py ON _ high-level Programming language. It was developed by Guido v 9 at the National Mathematics and Computer Science, the Ne by Python Software Foundation (PSF), nds us of the frightening has been coined ‘Pythor ‘an Rossum in 1991 Research Institute for therlands, lands. It is presently owned Python is based on the ABC language, a teaching langua, janguage the programming language BASIC, which was developed ; ae torepice Sea earlier, Python is a general-purpose programming language th kind of program that does not require an be direct acce: used effectively to build at s to the computer r hardware. es Free and Open Source 9 lar ae ra) a Portable oan » gramming y obje namicaly Oriented Typed Fig. 4.12: Salient Features of Pj Teel g > Python is interpreted, interactive directly executed, with pre-compiled code. This means that it is processed at run-time by the interpr before executing it nd w not compile the program > Itisa loosely typed Obje nted F 1 uage with fe words) and simple Englist \ easy to learn words (reserved It is a free open-source ar ng a large repository of libraries. ® It takes less time to devel thon programs are typically 3-5 times shorter than equivalent Java programs s because It-in high-level data types and its dynamic typing. > Itis extensible/extendable and highly efficient as there is no wastage of time in declaring the types of variables or arguments > It supports GUI (Graphical User Interface) and Garbage collection (better memory management). > Itis easily compatible with other languages like C, C++, Core Java, ete > Python is used for both scientific and non-scientific programming 4.7.2 Advantages of Python Apart from the above salient features, Python offers the following advantages: @ Platform-Independent: It is platform-independent and can run across different platforms like Windows, Linux/Unix, MacOS and other operating systems (6) Readability: Python programs use clear, simple, concise and English-like instructions that are easy to read and understand even by non-programmers or people with no substantial gramming background. Oriented Programming Language: It is an interactive, interpreted and Object- d Programming Language. val Thinking and Getting Started with Python small codes j aoe rage with Bigs : enor: eee a dae than languages like C++ offers higher pro ie packag! c So, you write less and get more done. code, lesser time is req ‘ (e) Less Learning Time: Because of a simple and shorter 4.9 IN understand and learn Python programming. that can be created and porteg python ications ae terst (8 GUI Programming: Python supports GUI appl dows MFC (Mi intera many system es libraries and Windows systems ae: oe Sue ! | Fe Foundation Class Library), Macintosh and the X Window sy: oo i (g) Ample Availability of Libraries: It provides large standard librari ia caning ; t and error : (h) Syntax Highlighting: It allows to distinguish between input, output an messages applica by different colour codes. To We i 4.7.3 Limitations of Python a on. Apart from several advantages that Python offers which make it one of the most popular en Programming languages, it has a few limitations as well. 7 (@) Speed: Python is slower than C or C++. However, Python is a high-level language unlikee 4.9.1 Py or C++; it’s not closer to hardware. WhEGEA (b) Mobile Development: Python is not a very good language for mobile development [p the STAI Seen as a weak language for mobile computing. This is the reason very few mobil mena applications are built in it (Q) Memory Consumption: Python is not a good choice f memory-intensive tasks. Duet the flexibility of the data types, Python’s mem ory consumption is also high. (@) Database Access: Python has limitations with database access As compared to Popular technologies like JDBC (Java Database Co, nnectivity) 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 complet legacy data, Ce) cate rors: en Programmers hav issues with the design of til anguage. Because the language is dynamically typed, it requires more testing and has errors that only show up at run-time. 4.8 INSTALLING PYTHON cited several _ hon distribution comes wi his Pytl es with Pyth E package Manager). Ython IDLE, Python Interpreter and PIP (Python: is a flexible, dynamic, powerf python * Powerful language that can be used i FRE cinch sec lat can be used in different ways. It can be interactively Ply to testa code or a statement line by line or while exploring its interface. s used by Google search e ‘i python z Ris eae Search engine, YouTube, Netflix, Spotify, Dropbox, Instagram, etc. is being : ly us af *ystem programming, GUI programming, Internet Scripting/Web, ext processing, Netw gram ; Gaming, Text p 18, Network program: , Commercial Robots and in Space and Scientific applications. ming, qo write and run Python programs interactive or the IDLE. IDLE is a simple Integrated Deve python. The most important feature of IDI run, browse and d we can either use the command line window lopment Le nent that comes with s that it is a program that allows the user to edit, gram from a single interface ning Enviror bug a Python prog When we first start P, king on its icon created on the desktop or menu item on the START menu ~ ; in the shel bil option, it always starts up Peco '4.13: Starting Python Shell Tr Computational Thinkit ds and the OS. in the same window. It is an interface between Python comman ae we i feython 3.6.5 (v3.6.5:f59¢0932b4, Nar 28 2018, 16 00 32 bit (Intel)] on win32 si Itype "copyright", “credits” or “License ()" for more information. p46) (Msc v.19 As an On opening, Python shell shows a welcome message displaying its version and a copyrigif| 4 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 Use (Fig. 4.14(a)). Python 3.6.5 Shei = Te tong. Cpers Wey Python 3.6.5 (v3.6,5:f59c0s0abs, war 20 2018, 16:07:46 60 32 bit (intel) } on win? Type "copyright", “credits | pes | start ping hare | nen we open Python interactive | mode, Python shell with prompt (>>>) | Gets displayed forthe user to enter the | commands directly in front of it. 1 - wea Fig. 4.14(a): Interactive Python Shell ina ; fee upc This is the Python shell, which is part of Python's Integrated Development Environment. The three greater ff denon ine nee eos teh, than signs (>>>) are called the prompt or Python command (jy dicate that itis waiting pe user command to be ef! prompt. are entered directly in IDLE from th mode. In Interactive mode, type th, and press Enter. See what happens, Keyboard, the Interpreter/IDLE fe command “Hello World” in y Our First Program m begin with our first ; $0, we bes! "st command in Python Interactive mode as illustrated below. practical Implementation-1 fia dt Shek Debug Options Window Hap python 3.6.5 (v3.6.5:159c 60 32 bit, CIntel)) one cog32b4, MAE 26 2018, 1630746) IMC v.19” Type “copyright”, "credits" >>> “Hello World” or “license()" for more information. "Hello World’ — Uns Cote Fig. 4.14(b); Displaying Message in Python Shell {As soon as we press the Enter key after typ As soon as we press the Enter key after typing our first statement, it gets executed immediately and the output is displayed nen and there Alternatively, this can be done using the print() function as shown in Fig. 4.14(c) given below: Python 365 Shel - oe Python 3.6.5 932b4, Mar 2 16207 isc v.1900 tntel)] on win32 Type "copyr ( i mation. Hello World Welcome to Pytho: ri i >>> Example of multiple) statements The multiple statements typed shall soo beege ae be executed immediately and Python >>> print (20) returns the output. This method of fh typing the message in front of >>> ry. (prompt) is termed as Displaying. Displaying Multiple Messages using print() function in Python Shell Inthe above case, we have given two print() statements for displaying two different messages Upon pressing the Enter key. Ithas 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 on the screen, The ‘ed within the parentheses. print() statement without any content (called argument) is spe arguments will simply jump to the next line. Python is a case-sensitive language. This means that Python differentiates between capital 4nd small alphabets. For example, Print (P capital) and print (p small) are two different things for Python, Whereas print isa valid command in Python, Print just word and nota command. ‘can be observed by typing the command Print ("Hello World”). = FS = = a ey ie zs s Fig. 4.14(d); Eror on Typing Print() instead of print) the message or the argument tp "or double “"); the argumeng; ‘We must remember that while using the print() command, th displayed should be placed within quotation marks (single then displayed as it is. If the argument is not placed within quotation marks, then the interpreter tries to evaluate argument and displays the result. This feature is used to perform calculations: IF we give arithmetic expression as an argument, the interpreter shows its value. This is shown in Fig. 4.14(@) Practical Implementation-2 Using IDLE as a Calculator just like text/string messages we have given so far, we can If we use th perform mathematical calculations using the Python command prompt. to be print >>> print x E python (3.6.51£59c093204, MAE 20 2018, 16:07:46) [MSC v1 }900 32 bit (intei)} on winsz type "copyright", "credits" or “License()* for nore information, End Paran 23 Python's p parameter Ss» print (20/4 *546-10) zi aaa string usir S35 pine 22/7) ¢ eaepesviezes714a The print int (2.24*20.8920.8 f 5 For examp >>> prin Python sh Fig. 4.14(e): Evaluating Arithmetic Expre ns In the above-entered statements, we have performed mathematic. ‘statement as well as by directly typing the command without tl either of the cases, these statements are immediately executed the output is displayed within a fraction of a second, al calculations using pti he use of print() command: by the Python interpreter Iso specify some 0 4.14(f). il oe tis the an so In id + ende'\n! inserted between values, ae fui filessys.stdout) dea: StriN8 appended after the last value, default, a new line, ¢; It is optional. By default, fle attribute is used to print objects on the standard on output SSO. syn oa an TERESA 20. 28 emer pcan ena 0-*"20-*=20 Birtnere >>> print (10,20, 90, sep ts sabia {-n (newtne cha separator >> print (10,20,30, sep [bo (tab) as separa Fig. 4.14(f): Use of sep’ with print ase use the sep argument to t Ifwe use the sep argument to specify the separator, then it must be specified after all the values tobe printed. Otherwise, the interpreter shows a syntax error. An example is given below: End Parameter with print( Python's print() functior parameter called ‘end’, By default, the value of this parameter is “\n’, ie., th e can end a print statement with any character/ string using this parameter The print function uses sep parate the arguments and end after the last argument. ment using “end” parameter with the print() function For example, type the following ats ' +) and press the enter key. the output shown below (Fig. 4.14(g)): Python shell will execute it and display St ae erapcabiabl, war 76 2010, 16107: python 3-6-5 1 F m wyton 6 oo ae bit. cimeelb} on WARS x0 me vetoes eredltar or ileanee (96 m0 Wrormtion- ’ Intormnth. 1, scat, "dog", 2apm',! amdn! 110") eau, at cog!! Fig. 4.14(g): Use of end” Parameter with print) , ‘the nee to configure IDLE according to the Soe and wo imple, changing font style of the Python shell window, highlighting s, etc. ovides Python help and documentation. Editor Window (Working in Script Mode) %, we were ‘working with the Interactive mode where there is no provision for holding the commands that we typed at the Python prompt. Moreover, the output is sandwich e command lines as shown in Fig. 4.14(f). All these commands, along with their outpy |as soon as we close the Shell window. This limitation can be o ython script mode where we can save the commands we are typing. This switchover is ca hrough Python shell itself. Working with Python script mode involv options to create a new file, open an exi nodule, save the current module/session. When you click on the “New Fil ‘15(a)), a new window opens, ie, the Python script mode or Python Edita isa simple and standard text editor where you can type or edit your cod 's opening, this file window is named ‘Untitled’ by default, as shown ime can be changed by the user by renaming the file 9c0832b4, Mar 28 2018, 16:07 | tel) a 55 {SC v.1900 32 bit (Intel)} on win32 ight", "credits" or “1icense()* tor more ret fee Pen er print (mis is my first progran’ print ("Using Python script. m print ("It is advantages print ("It saves the statene, active mode") using this mode”| ~ This method of typing the) commands using print) | Stement ts termed os ——$——_ printing Fig. 4.15(c): Type the Commands in New Blank File (Script Mode) step 1(a): Our next step is to save this file by clicking on File menu -> Save As option, followed by typing a proper name for it in lieu of the default name “Untitled” s "aves Sem Opmilebde. ait saves P| | + dhe Pen » Pen : > | | . | | kro i been TB Sonne Ei Rea ps 1 onde eB Homer ae me mane 3 Oey a . Pi ovcames * saename | regener seve ant Pontes 200) a Heft Fig. 4.13(d): Save your File with Extension Py A E= Es = 3S HS td 3 ey eZ 5 2 eB = i fa 3 Id see in the Intera 1 ts we woul Renn dor invoke the ‘we have to run this script an fae tat_ Format in| Optens Wien EP x my first progran”) sexipt mode") dvantageous over Interact! Pprint ("Ie saves the statements typed usin ve mode") ig this mode") Tas Gato] Fig. 4.15(e}: Running the File Eat Se Ceg Often Vndew Hp feython 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [ IMsc v.1900 32 bit (Intel)] on win32 Itype “copyright”, “credits or “license()" for more infor Jnation. Tt is advantageous over Interactive node rt saves the statements typed using this mode >> RESTART: C:/Users/preeti/appData/Local/Programs/Python/P | ] Fig. 4.15(f): Output of the Program Displayed Inside Python Shell red that even if we enter the print() statements in the script mode, the ay in Python shell, Also, all commands are given together in! ram/script and all output lines are dis fers Played t 7 rification of the output obi a takes place, ied and, hence, no more cluttel Berens teers to looking for similarities among and within fBPh thm refers to the rules to follow to solve a problem, eo algorithm is defined as a step-by-step procedure desired result, if followed correctly, > Algorithms have a definite beginning and a definite end, and a finite number of steps. > Agood algorithm, which is precise, unique and finite, receives input and produces an output, > Computational Thinking enables us to work out exactly what to tell the computer to do. Aflow chart is 2 type of diagram that represents the algorithm graphically using boxes of various kinds, in an ‘order connected by arrows, > Analgorithm where all the steps are executed one after the other, is said to execute in sequence. Decision-making involves selection of one of the alternatives based on outcome of a condition. > There can be more than one approach to solve a problem and hence we can have more than one algorithm for particular problem. > The choice of algorithm should be made on the basis of time and space complexity. > Acomplete set of instructions written using a programming language is termed as a Program/Code/Program Code. > Python isa powerful and flexible programming language. It uses concise and easy-to-learn syntax which enables programmers to write more codes and develop more complex programs in a much shorter time. > Python is a platform-independent programming language. > Python interpreter executes one statement (command) at a time > Python provides two different ways to work with—Interactive mode and Script mode, ofa program and the output is placed between commands: s the Enter key after typing one or more commands. > Interactive mode does not save commandsin the form a itis displayed as soon as we pre: © Interactive mode is suitable for testing code. Breen is a case-sensitive'language: Thus, Ram and ram are two different names IniFython: > Python is an interpreted language. Python's interactive interpreter is also called Py programs written in Python are easily readabl Indentation can give rise to syntax errors) te n editors will automatically indent the sta ‘outputs an entire (complete) line and then goes to the next line for subsequent o fal for ereating programs and then running ther later anc geting complete extension. thon Shell. le and understandable. ments. independent language. the command prompt, use the command (i) Python programs are saved using the OF n programming can be done in and eros ai problem. ) (I) There are no standard rules to write . «ww (mm) An. Jsthe process to write step-wise solution of a given problem in English-ike lan 0 (o) Js the process of breaking down a complex problem into smaller problems 59 they can be managed easily. 2, State whether the following statements are True or False. {a) Python is a dynamically typed language. {b) AlteR is used to repeat the last typed command in Python shell (i (c) Print and print are the same in Python. {@) sep argument is used with print() method. W {e) Python is a compiled high-level language {(f) Python is a cross platform language. (@) Computational Thinking refers to the collective thought process involved in formulating problem (Py and solutions ( {h) Abstraction deals with focusing on background details of a problem ti {Python Editor refers to Script mode in Python (i {@) Ctritg shortcut key combination is used to exit Python. tw 3. Multiple Choice Questions (MCQs) (a) Python was developed by....... ‘ SOLVED Q (i) Charles Babbage (i) Guido van Rossum 1. what (iil) Tim Berners Lee (iv) Robert €. Kahn Ans. aia {b) What is Computational Thinking? {) Giving instructions to a computer (il) Working with binary language (Gil) Thinking like a computer {iv) A set of techniques and approaches to solve problems (ii) Open Source (iv) Proprietary il) print("Hello") (iil) print( Hello") following is NOT a Computational Thinking technique? a ii) Decomposition bo Man (iv) Abstraction = 4p Which of the following is not an exa (0) Taking all the requirements into eorsacsor es acne Thinking? {i) Analyzing the bottlenecks into consideration before starting task {ii)_ Allowing any of the team members to take i | {g) Python is a/an language. ces | () Compiled " ii) Compiled & Interpreted (il) Interpreted (iv) None of these {h) The interactive interpreter of Python is termed as () Python shell (ii). Python Editor mode (ii) Python Script mode (iv) Python command line (i) The three greater than signs (>>>) are called the Python fy Pater thy Baking ee {j) Single line comments in Python begin with symbol. 0% cn ii)" (iw) (4) Which of the following codes is correct? (I) Python is a cas f (i) Capital {ii) Python doesn’t care at bet (iii) Python treats capital ai letters differe (iv) Python automatically capitalizes the se r SOLVED QUESTIONS 4. What are the four main parts of Computational Thinking: Ans. * Decomposition * Pattern Recognition Abstraction Algorithm Design 2. Can you spot a pattern in this set of numbers? 0,4, 1, 2,3, 5, 8, 13, 21, 34 i isa Fbons e sequence F, of Fibonacel numbers, ie. th Ans. Yes, This is a Fibonacci sequence. in programming terms, the a rg opis a mbers ke. ti Te dis gum of two previous consecutive numbers ands Geines Oy: Faf +h, Where F, =0, F,=1 With seed (initial or starting) value’: 3. What i 2 ole J, interpreted, dynamic, Object-Oriented Programming Language that supports GUI isa high-level, in , Programming, onal Thinking and Getting Started with Python Ty learly defined syntax. This allows /is Python easy to learn? has relatively few keywords, simple structure and 2 >>) in Python Shell. Python carrie, out the given instructions and shows the result there itself. In Script mode, Python instructions are stored in a file, generally with .py extension, and execu, together in one go as a unit. The saved instructions are known as Python script or Python program, 20. Give the output for the following Ans. 25, Ans - a 26. Ans, 27 Ans. 2a, Ans, 29. Ans. 1 ( (i (i {i ( Wi ‘ans. (i) if A<=20 (i), SUM=SUM+A (iii) A=A+1 (iv) print sum 25. Define the term Computational Thinking. ‘Ans. Computational Thinking allows us to take a complex problem, understand what it is, and develop possible solutions. We can then present these solutions in a way that a computer, a human, or both, can understand. 26. What is Decomposition? ‘Ans. Decomposition is one of the four cornerstones of Computational Thinking. It involves breaking down a complex problem or system into smaller parts that are more manageable and easy to understand. The smaller parts can then be examined and solved, or designed individually, as they are simpler to work with, 27. Why is Decomposition important? ‘Ans. Ifa problem is not decomposed, it is much harder to solve. Dealing with many different stages all at once ismuch more difficult than breaking down a problem into a number of smaller problems and solving each problem one at a time. Breaking down the problem into smaller parts means that each smaller problem “can be examined in more detail Why do we need Pattern Recognition? Recognition is one of the four cornerstones of Computational Thinking, It involves finding the ‘or patterns among small, decomposed problems that can help us solve more complex efficiently. + te n the characteristics of Computational Thinking. are Computational Thinking skills? : n be interpreted inta s ‘are Computational Thinking skills applied in finding solutions that ca applications? Python is free and open source. What do you understand by this feature? 4. Write some limitations of Python. ‘5. What is the difference between script mode and interactive mode in Python? 6. Give an example of Computational Thinking. 7, How can one use Computational Thinking for problem-solving? 8. Differentiate between flow chart and algorithm. 9. Write pseudo-code that reads two numbers and divide one by another and display the quotient, 20. Two friends decide who gets the last slice of a cake by flipping a coin five times. The first person three flips wins the cake. An input of 1 means player 1 wins a flip, and a 2 means player 2 wins Design an algorithm to determine who takes the cake? 42 Write 2 pseudo-code to print all multiples of 5 between 10 and 25 (including both 10 and 25). _ 12. Write pseudo-code that will perform the following: (a) Read the marks of three subjects: Computer Science, Mathematics and Physics out of 100 (b) Calculate the aggregate marks {e) Calculate the percentage of marks Write an algorithm to find the greatest among two different numbers entered by the user. Write an algorithm that performs the following: ‘Ask a user to enter a number. if the number is between is between 15 and 25, write the word BLUE. umber is between 25 and 35, write the word ORANGE. is any other number, write that ALL COLOURS ARE BEAUTIFUL. an algorithm that accepts four numbers as in, 5 and 15, write the word GREEN, If the Data Decision-making 3, Write the pseudo-code to print the bill de GST, which is the bill after adding 5% tax in the total bl When was Python released? 126. Is Python case-sensitive? 27. What is IDLE? 28. Differentiate between displaying and printing method in Python 29. Briefly explain the salient features of Python. 30. What do you understand by cross-platform software with respect to Python? 41, What are the advantages of Python programming language? "32. Inhow many different ways can you work in Python? "33, What are the advantages/disadvantages of working in Interactive mode in Python? Write instructions in Interactive mode for the followin, {a) To display sum of 3, 8.0, 6*12 __ (b) To print sum of 16, 5.0, 44.0 Write instructions to get the following result: thon is easy to learn and write. llows us to work in two modes: Interactive mode an ive mode is also known as Python Shell and S independent language. it interesting to work with Python. in both Interactive mode and Script mode. i code that prints your full name and your birthday as separate strings. st happens when the following statements are executed: id Script mode. ; ‘cript mode is known as Python Editor. It is a ing 2 software analyst, develop 2 solution by decomposing the entire problem and design ae ‘faibway ticket reservation system. using concept of decomposition. a” system can be described and decomposed into various functionalities and subsystems [Reservation information J— booking open or close,| javailable or waiting list, cancellation and refund Information about staff, security, railway infrastructure Railway Reservation System 5.11 In the Intera of def by the Befor define to wr syntay conce In the varia Whate

You might also like