0% found this document useful (0 votes)
8 views

Intro to Python

The document provides an overview of Python, highlighting its features such as being a high-level, easy-to-learn, and expressive programming language. It discusses Python's role in artificial intelligence, its built-in libraries, and its applications in web development, scientific calculations, and game development. Additionally, it covers Python's installation process, modes of operation, and basic programming concepts including data types, statements, and operators.

Uploaded by

APD Technical
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
8 views

Intro to Python

The document provides an overview of Python, highlighting its features such as being a high-level, easy-to-learn, and expressive programming language. It discusses Python's role in artificial intelligence, its built-in libraries, and its applications in web development, scientific calculations, and game development. Additionally, it covers Python's installation process, modes of operation, and basic programming concepts including data types, statements, and operators.

Uploaded by

APD Technical
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 44
is a general gossum designed Python anc ne famous BBC comedy TV yihon as 2 language suppo saintain, This is one impos Monty Pythanss Flying Circus” te mating it easy f this chapter, we wall learn a few ather important feature: and the basic C30 (<5 Important Features of Python phon is a very popular programming language. Let us study samme of its important feat asans for its popularity: High-Level Language: Python is 2 high-level and general purpose brogra process cf developing a program. The code written in Python + mare close machine language Easy to Learn and Use: Python has simple Eng) can easily get used to its syntax and can expertise in it Expressive Language: Python supports simple code that expresses itsellin a fen line asks. tements which are ree and Open Source: Python code is developed uncer o be downloaded free of cost from its official website hes. istributed further even for commercial purposes. ross Platform Language: Python supports multiple hich means a code written in one platform can easily ru ——— * lnterpreted Language: Python MOY tn Wterpreter where HY SOUKR Cte i erry . PLO! clarsae ane * Obiect Ortented Language: PYRO” sup merts the on able with umportant featules like polymarpsheem + Supports GUL Python sunpoets GNAhical User letertace al OUTTIMeN te design code nae Standard Library: Pythan hos some builtin modules and packages tor 4. {Qmimon tasks These emportant loraries make it popular specially in Al Lares focus mave on its use and now in its core design st ree Ny MAWes Hts Meee eer ¢ =) Role of Python in Artificial Intelligence“! Python is mast popular language fer Artificial Intelligence is based on the facts given 6, . * Built-in Libraries: Many built-in modules and packagos in Python reduce, Bevelopmen design cade for Artificial Intelligence. There are Numpy for scientific computation, p aoe tie a ay Language, Seipy for advances Computing, Pandas for general-purpose dar, analysis any Prthen to * Platform Independence: Python has this versatile hature of funning the code in an, 2 77" MacOS, Linux, Unix, ete, Packages like Pylnstaller can be used to Prepare the code thar Ot MO Wing Piatforms tin ane + Extensible: We can add low-leve| modules to the Python interpreter that helps a ao ™ their tools in an efficient manner. Fe TS nn * Availability of Data Analysis Tools: Librarief like Matplotlib helps data scientists to sf Plots them for easy comparison of data which is important for creating data SNAWYSIs reports wrth ving Toh * Community Support: Python being one of the popular languages has, ttracted a lot of Ma tery Online forums and online tutorials to provide assistance related to different ‘YPES of progr. %S ten This community support has worked to be an important factor for using python ne ne ri a ® Important uses of Python Av Following are some uses of Python: * Used for Web and Internet Application Development: Python has pre-built libra like Pyramid, Django, and Flask, which are used for backend web development pro; leche care = framey, also support content design, database connectivity and many Internet Protocols like HTTP SMIESKS * Scientific and Numeric Calculation: SciPy, Pandas, Ipython are some of the built-in Packages i Mbete are used for scientific and numeric calculations. Sin Python weg * Game Development: PySoy (a 3D game engine that Supports Python 3) and PyGame are libraries used widely for game development. Most of the popular games tke Baitleheld 2 Frew ee Of Tanks, Disneys Toontown Online, etc. are designed using Python game lisa, 9 = em * General-Purpose Software Development: Python is used for all Purpose software development ft ais Supports audio and video files that help in designing multimedia applications = & Installing Python Windows does not come with Python as default installed in it. We need to download from the official web: The steyss to download and install Python are: 1. Open the official website https://www.python.org/downloads. 2. Click on the Download Python 3.9.x button. The installer file will start downloading. Bull charts. store: developers, Vara 280 | Touchpad Artificial intelligence-Ix N AANA, 4 ey Working in Python We can interact with Python in two different modes. * Interactive Mode (Python IDLE-Shell Mode): In this mode, you type one command at a time in front of rhe Python command prompt (>>>) and Python gives you the result based on the command given. It means y fun code directly an shell mode accessed thraugh the terminal of an operating system. This mode will not say your commands and outputs and should be used only when you want to play with small one-line instructis You can also use the print{ ) function to print the messages on the Shell window. For example 29 64 bit. (ne Type *help*, ccapyeione™, ‘erudite’ or “themse(|* for mre sstamm Wearactive ase . + Script Mode (Editor): In this mode, you save all your commands together in any text editor with the extension Py. When we run this text file. py then the output of the commands will be displayed in Shell mode. The stecs to create and run script file in seript mode are: aa ‘SHEQ 1 Click on the File > New File option in Shell mode. A new blank text editor | appears, ‘ ‘Step! 2 Type the commands and then click on the File > Save as option to save the file. ‘The Save As dialog box appears, Step 3 Select the desired location to save the file and type the file name in the File Name box. In this case, we have typed the file name as MyFirstFile py, New File option SIE) 4 Click on the Run > Run Module or press F5 key to run the program. The program will execute and the output will be shown in the Shell window. ype “hele, “copycat”, *erwMlEa* oe “Lice Casey Ms C1 one / RGA ea /PHAEAMAI Pye yh - Pre rym Ao Punewag a serge @> 282 | Touchpad Antificiat Intelligence tx WAN _— es @ AiTask ) ee Colab—2 free Jupyter notebook environment that n tinny in the clon 419 write and execute Python cod; ype itp //cot which Can be simultaneously edited by the m research google com to creas nbers with wham you have shared yout cod | This process is nil to the way you edit decurn in Google Dries, Google theets or Gong Accharacter set can be a set ol valid characters. For example, «© Digit tke 0,1, 2,9 + Letters in upper or lowercase like AtoZ or atoz «+ Special symbols like §, %, *, 8, *, 0, @, | ete + Whitespace lke spacebar, Tab key or Enter key + ASCII or UNICODE characters like emoji symbols or other symbo (S) statements in Python Instructions written in a source code that are executed by a Python interpreter are called statements There amt three types of statements in Python which are simple statements, multiline statements and multiple statements tetus learn about them in detail. Simple Statements fy default, the end of a statement is dane by pressing an Enter key. Each statement is written on a raw line with unique code isa simple statement where variable ‘a’ is created with value 5. +b Multiline Statements We can make a statement that extends over multiple lines by using line continuation character (\) as shawn below: 44544 647 B+9 The main advantage of using multiline is when we need to do long calculations and cannot fit these statements into one fine. Multiple statements represent more than one statement in a singie line. This can be done by separating the Satements using semicoton (), jb = 10;¢ = a + b; print(c) Introduction te Python | 283 Tokens Tokens ate ¢ ‘ ond ate the wnatiest t Keywords Words that have soee eau are rest 8S identifiers We can © command prom False class Finally None continue: fer yy Tue det from we and det globat my as ist * Fld ne assert else umport break acest in ? Identifiers (Names) ‘Identifiers are the user-delined names of vara in Python, les, list, dictionary. tuples. classes etc. They yan Bement Naming the identifiers follows rules a3 given below: © An ident can have tetters in uppercase oF loweress2, numbers of und: « Itcannet begin with a number or an underscore » No special characters like §, periodt), space, ete. are allowed. + Wshould not be a Python keyword. © Uppercase and lowercase letters are different. rscorel) Example of invalid identifiers are Firstname ; Spaces net allowed Last&Name Cannot have special character, _elasstth =; Cannot begin with underscore Sthelass > Cannot begin with number else Keyword not allowed. Example of valid ide rs ate: Myclass, class9. Address, address, frst_name, cay, studemtid datal23, _ctassout Variables = \ Vanable is a name given te memory loca type of data that can be changed fu hold a specific value ter in the program 2 Kea COMaInE! that can Nols a nt variable cn same line, o pera bs 2 = 10 Brainy Fact Python is @ case-sensitive language where upperrase and lowercase characters hawe a meanings. Name and name are two different wana! Data Types Data types specify the kind of 3 value 3 venable can store be performed on that specific data type, Every value in Python has 3 data type. Same of the stangard burton data types of Python are: lps us to identity the kind of operation that can Data Types = t Sequences Sets fetreduction to Py vumntsers, | + Moat tt wun the: + Complen: and 26 a na None: This represented Sequen. can be mutable or non-mutable. There # ‘real umber with Moating pote reprise , exponent notation E For eaemple, 115 #1000" — eis enade up of area! nurnibser anet an lenagina”t nary number ie is special data type wih NULL or nema? * by None isa:collection of data stored undet 8 COMMON OME os fy are theee types of data as 3007 4 8 + String: itis a sequence of UNICODE char on the created using triple quotes (angie or deat empty where we have j jotws with ns sete is an inten + Lists Itis a sequence of heterogeneous values attargied 3 values of these data types can be changed by the user » Tuples: It is a sequence of heterogeneous values eran number, These values are separated by comma and are encioveed im orcs'at as the values of these data types cannat be changed by the user after crea + Boolean: Language ae separated by comma and are enced in square bracheas!) They 00288 after creation For #natr List_of_nanes={*Anit™, "0 Marks=[B9, 92,93, 76,693 class9=[101, "Neha", 89.5, 202, "5h It is a data type with two built-in values: True or False represents 1 while a False represents 0. Data Type Conversion Data of on float (), s e type can be converted into another type by using type conver (0, ete. The process of converting value of one data type t= type casting. For example, >>> float (12) 12.0 >>> int (15.5) 18 = 286 | Touchpad Article igence a Faise You can get the data type of any object by using type ) function For example. >>> type tio) ?>> type ("abo") >>> type (14_5 literals it is defined as any data stored in a variable. This data can be Sting quotes. For example, “Hello” ‘Python’ + Numeric literats: They can bé integer, float or complex, For example, 14 205 245) * Boolean literals: They can be True or False. For exemple, Tue © Special literals: Only None is a special literal. It means something not yet created. Punctuators Punctuators are special symbols used in Python to arganise statements and expressions Most comment used Punctuators in Python are: “#\000@.: Operators Operators are special symbols used to perform mathematical, logical and relational operations on vanadies and values. The variables or values on which the operators work are called operands. Some commoniy uses “perators in Python are arithmetic operatars, relational operators, logical operators and augmented assignment ‘*perators. Arithmetic Operators Arithmetic operators are used to perform mathematical operations on variables and values. Introduction te Pythen 28: a CLL ‘ome Symbol Purpose bearwle ste a4 ‘ dition . to ethos go+4 6-2 ‘ Spication Ne Muylnpies two values 25 Ehisio : Divides two values yan 83 Returns the remainder of a division oak ; Ceiarsaa a Second number raised to the 52 ae power of the first number. & w-2 23 yz 5 Divides the first number with the ; oar inion: second number and returns the “uy2 . st us whole number adjusted left to the a4 3 number line. a a Brainy Fact a * Ifwe use + (Addition) operator with strings, it concatenates two values. , + If we use * (Multiplication) operatar with String and integer value, it repeats string value same number of times. ‘elational Operators elational operators or comparison operators compare the values given an both the side of the operators arg turns the boolean value either True or False. Following relational operators are provided by Python Name Symbol Purpose Example Output a=S Reti Te if both thi i 2 jeturns True if both the values are oul Equal _—~ same otherwise False, gy 788 | Touchpad Artificial Intelligence-D¢ Wa Not equal to Ratuaris Truw of fret a than - than second salut ¢ et vate is 2 poturns True 1 the first value 1 SS teens - than second volue other penne gruestt tha: Reet ee greater than OT gi greatats the or equals to the me — second value,omnennise False sole ; 7 a=5 returns True if the first ee oan or equals to the second value a eat otherwise Fals@- sb Brainy Fact Python uses ASCI/Unicede character set. ASCIE Stands for “american Sande information Interchange. is a character encoding standard that uses fF represent characters in uppercase and lowercase, numbers and punctuation Fy™Do values of capital letters A-Z are 65 to 90. small letters are 97 tO 122 and sumBers 9 10 9 are 1057. Logical Operators 2 used to combine one or more Following logical oper: Logical operators are conditional statements and returns either True ators ate provided by Python: cased on the evaluation of the conditions. Name symbol Purpose Example Returns True if both the operands AND a perands e ia are True otherwise False, Faster Bs Returns True if either the operand: x or perands 5 > 10.0r2 <5 True is True otherwise False. _ segs Sem ang Ter megs Deut Peet rare sce coarse. ocr dwision frst and then assigns the renault 1 Te strand sce coeane Remamuer of a numb . stand then avugne the result to the lef hand site operand bee ated A Exponential of a number first and then assiqas ne 7 the result to the left-hand side op it at * Aji Reboot 1, What is the use of * operator? Deline the relational aperatars. e 3, Give an example to use **= operator? eR ernaeangsmmeneomnens ———— = é) Operator Precedence » expression is made up of values, Variables, operators and functians. For example. x-546 is an expression : is order can be evaluate an expression with multiple operators Python follows an order of precedence. This order tered by writing an expression within parenthesis. he ofder of precedence in the descending order is listed below: Order of Precedence Operators 1 9 2 3 “Pall 4 a 5 <>>= 6 7 iiss 8 not, and, oF an expression contains two or more operators with the same precedence, then order of evaluiation is from lett ta right except for exponential (**} which is always fram right to left. For example, * 10-2 + 3~3 will be evaluated from left to right as + and — has the same order of precedence. So, the answer will be 10 ~ 2 will be 8 + 3 will be 12-3 will be 8 = 23 * 2 will always be evaluated from right to left. It will be calculated as 2 (2** 3) ** 2.So, the answer will be 522, (@ ™ 2) and not as @ aitosk Solve the following expressions using the operator precedence: * 10+20/5-3*2 * 5°(0+5)+10-5 @ ‘Comments in Python Comments are used to increase the readability of the code. We use them to give proper un code in simple English statements, They are completely ignored by the Python interpreter practice to add comments in your code $0 that if anybody in future wish to understand or ‘then through comments it will be easy to interpret the instructions. There are two dif comments in Python, Let us learn about them in deta. Fert waTS OF ie Single Line Comment Single line comment starts with hash symbol F followed by the text to be written as a comment that last il mg end of the line, For example, . F assigning @ value to dhvarable ’ ‘ numl = 10 num2 + 20 # calewlating the verage (num + numa) / 2 Multiple Line Comments ‘When we add up comments which occupy two or more lines then we begin the comment with either 31 single quotes “* or double quotes "*", followed by text on multiple lines and end with single quotes or quotes ‘0 mark the end of the comment. For example, progrem calculates the average of two numbers stored in two different varlabias"*" a= 10 b= 20 2 fet ey ¢ 232 | Touchpad Artificial Intelligence-1x Se a oT The print() Function i 15 into a string before age print U function is used to print an output on the screen, It converts the expressions In q iting to the screen. Syntax to use the print ) function ist tebject (a), sep ~ separator, F end - end) where. 4 object can be one or more separated by camma and It can be a variable, literal, expression. An object v1! converted to string before printed, | sep is Used as a separator if there are more than one objects. end specifies What to print at the end, Default is newline‘ \n" allowing are some of the examples of the print ( ) function Commands Output print (hello) hello te print("hello", "friends") hello friends prtrtqmhello* + “friends") hellofriends (This is concatenation of atring using "4" operator) print(*heilo", "friends", sep-"8") helloStriends print("hello", "friends ‘s, sep="$", end=*!-) hello$friends! brine (hellic’,, Otends's endewiel | eee iiaile fiends! print ("hello") helio peint () friends print{" nda") print (*hello", end="8") hhello%frends print ("friends") print "hello", “friends”, *welcore", se hello#triends#welcome® end="@") print ("2 em in class", 9) Tam in class 9 a-5 b= 10 Sum of two numbers is 15 print ("Sum of two nun 14 is “ + ste(a + bi} age Jam 14 years old print("I am “, age, " years old") (tre input() Function The input { } function is used to take an input from the user, When, this statement executes then the flow of the prooram stops and waits with the cursor blinking for the user te enter a value The input given by the user ig always @ String value in Python. = Introduction te Pythen | 293» Ses i LETS = When the preceding statement executes, it will ask to enter name. Winen you enter th key. entered name will be displayed on the screen race and pene {f we execute the preceding cade and enter 4 and 5 as the values of the first and second numiars answer will be 45 instead of 9, Thisis because Python considers every input vaiue as string, ifwe wane taper: mathematical calculations, then we have to convert the taken input explicitly by using functions. The syntax to convert an input value into an integer oF float type is # to convert inte inte a = int (input (pi pt) sat (input (prompt) # ta convert ifte Roat Lot us create the preceding program again by using the int ( ) function. = intlinput("enter first number")) #line 1 a be #line 2 < print (*the sum is", c) Now, the program will display the correct output as 9. x“ @® Errors in Python w Sometimes, while writing a code we might make mistakes, These mistakes are called errors. There are there ‘of errors which a programmer encounters in Python: syntax error, logical error and runtime error. Let vs ‘ert about them in detail Syntax Error Syntax means writing the cade following the rules of Python language. Syntax errar is occurred when we v2 the rules of Python language. This is the most common type of an error made by a programmer If there is tye error, incorrect indentation, or incorrect a¢guments given in a function then Python will not be able to 19 the instruction and will raise a syntax error, [n IDLE, it will be highlighted by an arrow and then you can 9° that line to rectify the error. Some of the examples of syntax error are: a+bee SyntexErcor: cannot assign to operator myname = “Arshia™ 294 | Touchpad Artificial Intelligence-IX print (PEVENON™ eyntaxtrror: unmatched ")¢ Logical Error this kind of error is difficult to find since the program will run correctly but the desired output is not achieved this happens if we give a wrong formula for the calculation to be done, write wrong logic for the problem to be solved through the code, For example, fo calculate the average: po marks! + marks? / 2 dinstead of (rarkslimarkez) / 2 preceding code produces a wrong output due to the logical error in formula. Let us take another example To find the perimeter of rectangle, *'peei2 fsb . *% Runtime Error Finstead of p = 2 * (1 + b) Runtime error occurs during the execution of a program like wrong input or output errors, undefined odyect errors, division by zero errors. This type of error will halt the program execution unexpectedly fxample of runtime error is: f a = int (input ("enter ‘fi st number")) b= int(imput("enter second number™)) ~ eza/b a= 5 and b = 0, then it will display: ZerobivisionErrer: division by zero ()controt Statements “(> As you know that a program is a set of instructions given to a computer to do a specific task. The order of execution of these instructions controls the flow of a program. There are three important ways to control the flow of a program which are interpreted by any programming language in a structured manner. These are: = Sequential + Selection + herative Let us learn about these in detail. ® Sequential Statements Te A step-by-step process of execution of code is called sequential flow of control. This is the default flow of er on of a mrogram. It means that the computer will run the code one line at a time starting from line 3, followed by line 2 and so on tll it reaches the last line of the program. Let us take an example of making a mango smoothie, The steps will be: 1. Put mango pieces in a Mixer jar 2, Add sugar Intreduction to Python | 295 ne More ¢ © TnpAt First panne and Last name fem the user ancl diaplay fill nartye Algorithm Flowchart start Input FastName Input LastName. vame + LastName MeUT fullName= Firs Lae Display FullName “ = ey Stop £ Source Code: Fuliaenaes Ford Maem Lint Maen a +FullNames" 7 1 : Output: ic "HF ) Enteryour First Name ‘Suzan, Enter your Last Name :Chtistopher sell (Suzan Christopher Welcome to the World of Python , ‘+ Input Length and Breadth of a Rectangle. Calculate the Area and Perimeter Algorithm Flowchart ps Input Length, Breadth Area=Length X Breadth Perimeter= 2(Length X Breadth) Display "Area is", Area *, Perimeter Display “Perimeter Stop Source Code: ength= £ Breadth = int Area= Length*Breadth > 296 | Touchpad Artificial Ineligence-Ik ; ~AO\, ger Breadth 10 i" aa s 50 perimeter is 100 @)AiTosk ah en by TH peters, aay ror ‘Type “import this” in your Python IDLE and you will find a poem weitte by to the Python community. | * Gb ai Task ae Input a radius of a circle. Calculate the area and perimeter of circle. Se Selection Statements ~ . In Python, Selection flow of control is achieved through conditional statements. « In the conditional/selection statements, flow of control is changed based on 3 con condition in the program which evaluates to either True or False. + {if candition is True then the block of statement written for True will be executed and False then the block of statements for False will be executed. + Conditional statements are also called as branching statements as a program decides which sta execute based on the result of the evaluated condition, + Abblock is identified by using an indentation (minimum 1 space). Ensure that all statements in one block are indented at the same level. '* Python mainly provides three types of conditional statements— Let us learn about them in detail. jon. We specify the in case the condition 15 tement to statements. Introduction to Python | 297 LLELLE ee he The i Statement We 00 the i ' Wletnerit to uM GOO aHA Retigtattinang. Carta aH trae | NNR em He a ‘enatas then (1 Suwveree 11 apical uo ee puarOtvenlh. IH Poms 4 Mimsy Chom Fw ag 20 8 ot a Ite ee Mbatannyent TY atten shanmsrunib Kata Kant a 4 BHO) smn HPI 6 Hae be pase Konelinien LN HO. A Matern ltach .. > WRercent h more than #0 then = Display *Congratutauens® 7 Display "Your are awarded Certificats of Uxcellence” Stop Source Code: POLCONt= int finput ("En your paccentane 1) percunt 4d; PEt (MCONGHATULAT LORS") PrLAt (YOU 9E8, ANAL | Samet Cena b? Output: Enter your percentage 49 CONGRATULATIONS You are avarded~ ‘Certificate of Excellence’ NK 4. 298 | Touchpad Artificial Intelligence 1 Nee AN | weoeklay “gobi 1S SAMEAS “SUNDAY then paniay * Reward Point - Checolate Cookie FREE Ir wr source Code: eCeRTE NPT enter day of the week ; SUNDAY seward Point ~ Chocolate Cookie FREE The if...else Statement When the condition is True then the statements indented just below the i: statement wil & executed and if the condition is False then the statements indented just below the «Lae statemen will be executed, The else statement is optional and if required can be only one «ise statement in on 22 block, The syntax to use the {false statement is: Af (condition): Statements for True gise: Statements fox False Where, « Le and alee are keywords, tdon can be any relation or logical expression. + statements are always indented and can be single or a block Tnoduction to Python | 239 a Ltt Program a: Te ingait WO mumble” ana display the bigger Of! Algorithen ' Howehart Stor ' Input Na, Ae ‘ 4811 68 Greater than nathon Display Nias tigger | Otherwise Display “N2 ts bigger Stop Source Cod NU = Ant Clnput (“eames fhe ey) | H2(OUCinput (Meaten 4 Number Nise: PUANCQNL, Le Bigger "9 Print (M2, "L9 ba or Output: Enter first Number :34 tater secend Number 45 STOP 45 is bigger % . Program 4: To input a number and display whether itis even or odd. ‘Aigorithen Flowchart Start Input Num If Num is divisible by 2 then Display “Num is EVEN* Otherwise Display "Num is ODD" Source Code: Num=int (inpul ("™eatee 4 Number 27) Numt2=— print (Wum," ie EVEN ") print (Num, " is opp *) Output: Enter a Number :23 23 is ODD 300 | Touchpad Artificial Intelligence-IX SR, if,..0lif. else ® Statemene there re tit er mip eoadition 6 erent Below it wi caneOR STN ; Senecuted The 570A ef they Hateenacts weitie . es + statement ig ax z teondit seni) aeamere ¢ toon gratenonte + plant grataments: smeared whe where cnn eo LE wpdne 25 f ate cpwees Mabe cn 2 3d on 5% 140 be any sepraccnn 33 re anys sneteriins cae bee os statementes and » Start Input NI, N2, op fap is seme as that of ~’ thaw Display N1+N2 Ctherwise, if op is same at that of ier Display NA-N2 Otherwise, if Op is same as ther of then | Display NI*M2 Otherwise | Display "Wrong operator entaren” = Source Code: Hietnt input (aecer "int tinpu Ste Ge Output: Enter first Number 5 Enter second Number -4 Enter an operator(+,~* only) :* The multipication is 20 Program 6: To input a number and check whether the number is positive of negative, - Algorithm Start Input Num {Num is same as 0: \ Dispay “You entered zero’ Otherwise, If Num is greater than 0; Display “You entered +ve Number" Otherwise Display "You entered -ve Number" Stop Source Code: Num=int (input ("© Num==9 3 print Num >0 Pprint("¥oo 2 print ("You Output: Enter first Number 4 You entered a -ve number 3. 302 | Touchpad Artificial Intelligence-tx ~AARAL Flowchart nested if Statement geting one 2 f stotement can be upto: Statecvent within anotinar 42 is caea nested x6 |, Indentati i statement. Nesting of i ggievet Incentation plays avery important role in identitying the levels. program 7: To input billing amount and gender. tf the billing amount is more than 10600 and gender is jemale. then discounts. 15% otherwise discount Is 0%. Calculate the billing amount accordingly. orm gatt sput Amount, Gender amount is more than 10000 then | if Gender is same as that of “F* then Display “Amount after 15% discount is =, Amount-(0.15"Amount) Otherwise Display "Amount after 10% discount is *, Amount-(0.10*Amount) ctherwise Display "Sorry! No Discount” Sop flowchart Source Code: amount«int (input ("Enter billing Amount: ">) ; zi input (“Gender =") gender=i0P! Intraduction to Python | 303 s LTETT rey! sa ds Output: Enter billing Amount : 12000 Gender :M Amount after 10% Discount is 10800.0 Program &: To input a number and check whether it is multiple of 5 or not. This check is valid only for positive numbers, Algorithm Start Input Num if Num is greater than zero then if Num Is divisible by 5 then Display “It is multiple of S* Omerwise Display "Not divisible by S* Otherwise Display "Sorry! Invalid Number” Stop = Source Code: Numsint (input ("Enter a number 2" Num>0+ Numts==0: print (Num," is multiple of 5%) print(Num,” is not multiple of 5%) print ("Sorzy! Invalid Humber") Output: Enter a number : 34 34 is not multiple of 5 304 | Touchpad Artificial Intelligence-tX \ NARA. Flowchart START , ¥ Brainy Fact ~ True meane NON-zer0 numIser oF non-empty object and False means rero number or empty object ve (e)terative Statements ton, the Process of repeating a set of instructions based on @ condition is called Joop. There are two types ucopsin Python—tor loop and white loop. Let us lea about them in detail, he for Loop be Cor foop 15 used to repeat a set of instructions for a fixed number of times, It means the number of gations are known/ definite before we start with the execution of a loop. Therefore, the for loop is also known defile loop, Indentation of statements is must Lo specity the block ot statements to be repeated using the or logp: There are commonly two different Ways of using the fox loop: Using Sequence: In this type of tor loop, 4 Sequence of values is used on which the loop iterate, The syntax to use the £01 loop with a sequence is; for in : Statements Where, » for Bakeyword, + counter variable is any lentifier that keeps a count of the loop. sequance Is any values like integer, string, list, etc. Statements are always indented can be single or a block. Different examples of for loop are: Commands Output for 4 in [1,2,3,4]: 1 print (1) 2 3 4 for words in ("hello", "friends", how are you 2*}: hello print (words) friends how are you? for alphabets in "hello!™: h print (alphabets) ; 1 ° Introduction to Python | 305 3 {> ene vatse=1 fl lop value becomes 1 by ont eras Q and Stan banumen 1 by cota tio output given enter starting ¥3 5 enter ending wal 10.5,7.9, and logic ‘operators (3nd, ar) retums tue oy the while Loop = lo0p is used to reps sumber of iterations ate not fixe definite loop. Indentation 2 leop at a set of instruc GVincefinite before we start with the ons as tong 95 the condition i true. tt me: Sxecution of aloop. tts th block of statements to be aR when the Of statements is must to specity th ca Ths loop is also called an entry-controlied loo coniiion is tue then the bedy of the loop wit rpemer within the loop and it stops, {or the concltion in the begin \ ing only is false then it wit IL nat be allay is a keyword. ditt ions @ criterion fa repeat the instructions. The ing the conditions Felss, the control ets fo structions repeat til 1m the loop. Ithe condition is True, AS soon as "its are always indented can be single ora block and are fepeated tithe condition is True: Brainy Fact When there is no change of condition in while leop then it becomes infinite loop, For example, aot whlie i 310 | Touchpad Artificial intelligance-tx ‘ WA, F -_ pryeTrHrorn® print print (indexno, end: Using + Operator with List The + operator is used to concatenate the list with another list, Remember that b the a piyiTiHTornl e Mivalent tot Ba Lists Tt}; u(2j, weir eer ty 1ayst se orat2i3! index hunbéer of each element in & © THe, THE, Not, THE exno in range (len (hl) oth the operands on either side of the + operator have to be a list only otherwise it gives an error, For example, A= (1; 2 B= 14, 5, crate print (¢) A» (1, 2 B- (4, 5 Bt A print (B) A= (1, 2, B= (4, 5, C= (ty 8, Cor 3] 6) 3) 6) 3) 6) 9} D=A+tBHC print (D) Ae [l, 2, 3) B=A+ [10, print (B) A= (1, 2, 3) B= A+ "abe" print (B) mmands Outpue (1,2, 3,4, 5, 6) 14, 5,6,1, 2, 3] (1.2, 3,4,5, 6, 7,8, 9] {2 2, 3, 10, 20) 20] Typetrror: can only concatenate list (not “str*) to list Introduction to Python | 311 ALLA LA OE Se tea, d (12,345 67.891 = 1% By 9) Mewlist = at 4 44, 5, 6) + 13 Print (newlisty Using * Operator with List The * operator is used to replicate a list by # specific number of times. With * operator list and the other shoutd only be an integers, otherwise it will give an effOr. For exam Or one operand hat to Commands Output Ae, 2,3) 123,1232231 Pea as print (B) a 155.5) Ae (x74 3 print (A) Commands Output nane > "hit" [Amit ‘Amit, ‘Amit, Amit] Zt= [name] "4 print (za , nilne - "Amit" — Typefrror: cant multiply sequence by non-int of type ‘st 1 ~ [name] * ma" Comparing the Lists The comparison of the lists is done using comparison operators >, <. > and ==, These operat ‘compare the elements in lexicographical order. For example, if corresponding elements are same, it goes to next element, and so on until it finds elements that differ. For example, i= [1, 2, 3] z= f 1 @ 3] 13+ (, 2 13 dd = 11.0, 2.0, 3,0] print (it == 12) #True print(11 > 12) false print (1? == 13) aPalse print(1l == 14) s¥alse print((l, 2, 6] < {1, 2, 5]) #False 312 | Touchpad Artificial Intelligence-1X I, id eet alist mmper, end index number with colon in between. We can ure bath forwa | det range of slicing a list, Some important points to consider to do slicing In oe means accessing a specific portion of a list. This can he done by using a rac a ants from beginning to a range -list{: Index| oF {: index) eens trom specific Index til the end -Istfindex) Mo Tents wit 2 Tange list{start index end index} geet within range using step value - list{start index: end index : step value] Bogor Hen forward order lat =] |, whole list in reverse order - list :: forexample, yord =U" Examples Jo display the whole list or word[ or word[ 02] or word{=92] Displays the alternate elements print (word (2721 of the given list y To display ('E', 'D’, 'U'] from the word (0:31 above list ee | word|:3} or word[-9:-6) or word{:-61] Introduction to Python | 313 AEETTT Jo display (OT, 1] from the sora! above list TNO. T Tow cu, Oey To display the ils Task ‘WT, TON] E.'D', Us, 'C What will be the output of the following instructions: © print(word[:1:-2}) © printwword(-1:)) © print(word{:-1}) Adding New Elements to a List There are three different functions used to add elements in an existing list which are af extend ( ) and insert ( ). Let us learn about them in detail. The append( ) Function The append ( ) Function appends @ single element with the given value(any datatype) at the end of tm We use this function in a loop for adding multiple elements. With the single appendt } function, the of the list will increase by 1. Syntax of the append ( } function is: list. append (item) 2 ne, 2 ia ee | ee: ae The insert( ) Function Examples: Removing Elements from a List ions used to remove elements There are two different learn about these functions in The remove( ) Function ( ) function removes the The remo one value can be removed values then this function can be used within 2 loop wi the remove } function is: time the POP() Function the PP ( ) function mow returns the di esan mt wet es Vale. case ng net om the a Dumber which ac jo list based on the index number 5 is given then by 4 es not exist ther Commands Ter, 4g Val=vowels pop (2) Vowels=[15) Output Print (val) val=vowels pop) print (val) vw val=vowels po, *Pop (6) print (val) Indexrror: pop index out of range ist=[] Ist.pop() IndexError: pop from empty list Some other Functions Used with List There a ong eae functions also available to use with the list which are as follows: » lenQ: This function returns the length of a list, For example, marks = [10, 34, 42, 21, 45] print (len (marks) ) Output will be 5 clear exists in Python which can be used later to fill the values. For example, city=["Delhi", “Mumbai", "Kolkata", "Chennai") city.clear() print (city) Output will be: (] ~ reverse(): This function reverses the content of the list in place’. For example, alpha = (eae oueere ct, 27) alpha. reverse () ™ his function removes all the elements of the list in one go. It empties the lst but the empty list st Nt ut wal + S08: This 16 bist ww Linetion sorts the th value 8 of the ay mat Cutput will be: ennai’, "Dethi*. *Kolkata’, “Muna eity,s “iy rae-true) teorts t Output will be, P Mumbai, Kotla © Indexd: It returns the index numbe *, “Dethis, “Chery 1c of the value given in the function, For example sitye ("Delis city, index ("Kolkata") Output will be: 2 city. index ("Pune") Output will be: ValueEtror returns ValueBrror exception if the valve is not found in the list ‘count(): This function counts the number of occurences of the specified value ip the given Ht Fahey doesn't exist, then the function retus 0. For example, : marks = { marks count (28) ¥ Output will be: 2 marks.count (10) Output will be: 0 # 10 does not exist in the list, © At a Glance + Approgram is written in any programming language which the computer 9 understand anc execute ‘* Control structures are a set of instructions that controls the flow of instructions 9 a program + Analgorithm is a step-by-step approach to identify and solve a problem ina fvte tine ‘+ A flowchart is a graphical representation of an algorthm. + Python is a general-purpose, object oriented, easy to leamn and high level programowng language + Instructions written in a source cade that are executed by a Python interpreter are calies statements + Tokens are the smallest meaningful unit of a program. + Identifiers are the user defined names of variables ist dictionary, tuples, classes ete + Variable is a name given to a memory location to hal a specie valve * List is a collection of heterogeneous data arranged in a sequence + The elements of alist can be accessed by using its inde number starts with 0 ere) + The + operator is used to concatenate the list with another list. + The * operator is used to replicate alist specific number of times » The comparison of the lists is done using comparison operators >< >= and «The append( ) Function appends a single element with the given valueany datatype! at the end of IM st 2. 318 | Touchpad Artificial intelligence IX eeu 97 Oe ~ A Whi Nh Of the following isa sequence of UN x Zerodivisin a usontrror eros» as b. Logical t © Runtime g ston ror crabet on Error OO «Bo CODE characters? lean, a) b. Numbers © String oO d. Float 10. Which of ti ; bs Of the following is a data type that has two builtin values True or False? rin a oO b, Boolean © Integer Oo Flot 1. Which of Fi ~ oF the following conditional statements is used to test multiple conditions? a i ( b. it.elif.else © if. if.else © d, All of these X12, What will be the output ofthe following code? i€ (true): Print ("Hello") else: print ("Hi") ; a. Hello ©) b. Hello Hi ¢ Hi O d. Nothing will print 13. FLL =o, R, ',‘G',"E, then what will be the output of the following statement? print (21) _ a. ‘ORANGE’ © b, (OW'R "ANY "6, "29 OF 'RYAY NY Gh ie) , None of these yi Consider the following code: A= ["Orange")] B= ("Education") C=A+B print (¢) Which of the following will be the output of the preceding code? a, Orange’, Education’) Oo b, [Orange Education’) eoreneeveten oO d, Orange + Education yas, ‘E] then which of the following will be the output of the given statement? print (L1[::-1]) a, Prints the list as it is ‘© b. Prints the list in reverse order cc. Prints the last element of the list @ d, Prints the first element of the list B, Fill in the blanks, De Aine 2 In 1 RAAAANO OU: « . sun is written in any programming language. uuu flow statements are placed one after the other. 320 | Touchpad Artificial Intelligence-IX Zy OO OOo COO ” times") e Unsolved Questions 5 SECTION A (Objective Type Questions) Ai@viz A. Tick (v) the correct option. Which of the following is not the conditional statement in Python? a. if Statement oO ¢. ifelse Statement S b. if. lif.else Statement d. None of these 2. Which of the following is a looping statement in Python? 4 4 torstatement '@ bb, while statement « Bothaandb er d, None of these > Introduction to Python | 329 a PRAT a veh FOP A Views sienben a vie (e 1b otoe state ) y “otement : ¢ J@yrvenre © 4. continue statement ) following can be a port Of a ticte 4 String values bs Cc ae CG b Integer valans e) = 2 4. All ofthese Oo alist name, : His : “11 contains 4 elements, then which ofthe following can be used to access the last element ofthe UI lot? a ul

You might also like