0% found this document useful (0 votes)
4 views54 pages

Python Notes

The document provides an overview of programming languages, focusing on Python, which is an object-oriented, high-level, and versatile language suitable for various applications. It discusses Python's history, features, types of errors, and its structure, emphasizing its ease of use and dynamic typing. Additionally, it covers Python's applications in fields like machine learning, web development, and scientific computing.

Uploaded by

tasmiyatehreen.r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views54 pages

Python Notes

The document provides an overview of programming languages, focusing on Python, which is an object-oriented, high-level, and versatile language suitable for various applications. It discusses Python's history, features, types of errors, and its structure, emphasizing its ease of use and dynamic typing. Additionally, it covers Python's applications in fields like machine learning, web development, and scientific computing.

Uploaded by

tasmiyatehreen.r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
I. OVERVIEW OF PROGRAMMING A programming language is a formal computer language or constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs to control the behaviour of a machine or to express algorithms. INTRODUCTION OF PYTHON Python is an object-oriented, high level language, language. Python is easy to learn yet powerful and versatile scripting language which makes it attractive for Application Development. Python's syntax and dynamic typing with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas. Python supports multiple programming patter, including abject oriented programming, imperative and functional programming or procedural styles Python is not intended to work on special area such as web programming. That is why itis known as multipurpose because it can be used with wed, enterprise, 3D CAD ete, We don't need to use data types to declare variable because itis dynamically typed so we ean write 0 to declare an integer value in avaiable Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fst It is used for GUI and database programming, client- and server-side web programming, and application testing. Itis used by scientists writing applications forthe world's fastest supercomputers and by children first learning to program. erpreted, dynamic and multipurpose programming HISTORY OF PYTHON Python was conceptualized by Guido Van Rossum in the late 1980s. Rossum published the fist version of Python code (0.9.0) in February 1991 at the CWI (Centrum Wiskunde & Informatica) in the Netherlands, Amsterdam. Python is derived from ABC programming language, which is a general purpose programming language that had been developed al the CWI. Rossum chose the name "Python since he was a big fan of Monty Python's Flying Circus. Python is now maintained by a core evelopment team at the institute, although Rossum still holds a vital role in directing its progress. (COMPILER vs INTERPRETER ‘An interpreter is @ program that reads and executes code. This includes source code, pre-compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl, Python, and Ruby code respectively. Interpreters und compilers are similar, since they both recognize and process souree code. However, a compiler does not execute the code like and interpreter does. Instead, a compiler simply converts the source code into machine code, which can be run directly by the operating system as an «executable program. Interpreters bypass the compilation process and execute the code directly. 2 Interpreters are commonly installed on Web servers, which allows developers to run executable scripts ‘within their webpages. These serpts can be easily edited and saved without the need to recompile the code, Without an interpreter, the source code serves as a plain text file rather than an executable program. ® | compmen INTERPRETER + | geben msene | inp rremem see Entre prosram s!iapir Statement ata time inp 2 | SSRPRREESSm Tease | Rimmsmcessne are machine code. thachine code. 0 gonstruct: faster than slower: inicebrotee Seve anccony Saree + | Brsannonnae Banat seled raga are Ee as Eee niece 5 | SSmpied program aaerNorneca | interpreted Rneiby ine every time tobe compiied every rn they are un. « | Srarsersgpeneg shee... | SSSI ENE SREP SLES program Wallet be cheated une > | asgepinsaangyese moe | RIRSERIRE SEPARA rors corapaer goes nox ners ern ce progeera Rem ‘| aoe Panomone re > | compurasenguagesecemore | SEER SSIDAGPESE ns SSIORRPEWUIATL AS 20S, Heer nue anguages an leat ee aa 10 | ERR ARUE CEE < | RINE Se ee. PYTHON VERSIONS + Python LO «Python 2.0 Python 3.0 PYTHON FEATURES, 4+ Easy to ear, easy to read and easy to maintain, + Portable: It can run on various hardware platforms and has the same interface om all pilatfooms, + Extendable: You can add low-level modules to the Python interpreter. ‘© Scalable: Python provides a good structure and support for large programs, Python has support for an interactive mode of testing and debugging. ‘© Python has & broad standard library cross-platform. Everything in Python is an object: variables, functions, even code. Every object has an ID, 8 type, and a value, Python provides interfaces to all major commercial databases. Python supports functional and structured programming methods as well as OOP. Python provides very high-level dynamic data types and supports dynamic type checking, Python supports GUT applications Python supports automatic garbage collection, Python can be easly integrated with C, C1, and Java, APPLICATIONS OF PYTHON © Machine Learning ‘© GUI Applications (like Kivy, Tkinter, PyQt etc. ) ‘+ Web fiameworks like Django (used by YouTube, Instagram, Dropbox) + Image processing (like OpenCV, Pillow) Web scraping (ike Serapy, BeautifulSoup, Selenium) Test frameworks © Mukimedia ‘Scientific computing ‘Text processing ‘TYPES OF PROGRAM ERRORS ‘We distinguish between the following types of errors: 1. Syntax errors: errors due tothe fact that the syntax ofthe language is not respected. 2. Semantic errors: errors due to an improper use of program statements. 3. Logical erors: errors due to the fact that the specification isnot respected, From the point of view of when errors are detected, we distinguish 1. Compile time errors: syntax errors and static semantic errors indicated by the compiler. 2. Runtime errors: dynamic semantic errors, and logial erors, that cannot be detected by the compiler (debugging). Syntax errors ‘Syntax errors are due tothe fact that the syntax ofthe Java language is not respected, Let us see some examples of syntax errors. Example I: Missing semicolon: {nt a ~ 5 1/ semicolon is missing Compiler message: Example java:20; expected in a= 5 Example 2: Erors in expressions: X= (3+ 5) Il missing closing parenthesis 'Y y=3+S; // missing argument between ‘and ‘Semantic errors indicate an improper use of Java statements Let us see some examples of semantic erors. Example I: Use ofa non- initialized variable in is iets // the variable iis not initialized Example 2: Type incompatibility int a~ "hello; / the types String and int are not compatible Example 3: Ettors in expressions: String $="..": int a= Ss; the - operator does not support arguments of type String Example 4: Unknown references Stein x; 11 Strin isnot defined system out printhn("hello"); system isnot defined String s; Sprinting; 1 printn is not a method of the class String ‘Example 5; Array index out of range (dynamic semantic error) int{] v= new int{10};, ¥{10] = 100; 10 isnot a legal index for an array of 10 elements ‘The array v has been created with 10 elements (with indexes ranging ftom D to 9), and we are trying to access the element with index 10, which does not exist. This type of eror is not caught during compilation, but causes an exception to be thrown at runtime. Logical errors Logical exors are caused by the fact thatthe software specification is nat respected, The program is compiled and executed without eors, but doesnot generate the requested resul Let us see some examples of logical errors: Example I: Erors inthe performed computation: public static int sunt a, intB) ( retumab5 ) this method retums the wrong value wet the specification that requires ‘to sum two integers Example 2: Noa tezmination String s= brreadLineO; while (= ml) { System out prints); Vth loop does nt terminate Errors detected by the compiler and runtime errors Al syntax errors and some of the semantic errors (the static semantic errors) are detected by the ‘compiler, which generates a message indicating the type of error and the postion in the Java source file where the errar occurred (notice thatthe actual errar could have occurred before the position signaled by the compile) (Other semantic errors (the dynamic semantic errors) and the logical errors eannot be detected by the compiler, and hence they are detected only when the program is executed, Let us see some examples of errors detected at runtime: Example I: Division by zero: int a bx; a=10, b= Integer parselnt{[Link] ine); x=a/b; ERROR if b= 0 This error occurs only for a certain configuration ofthe input (b= 0) Example 2: File docs not exist: FileReader f= new FileReades("[Link] ‘The error occurs only i the file pippo.4xt does not exist on the harddisk. Example 3: Dereferencing of a null reference: Strings, s= null; t= swoncat("a") The concat() method cannot be applied to a reference whose value is mull, Not thatthe above code is syntactically correct, since the concat() method is correctly applied to a reference of type String, but it contains # dynamic semantic error due the fact that a method cannot be applied to a reference whose value is mull Il, STRUCTURE OF A PYTHON PROGRAM Python Statements {In general, the interpreter reads and executes the statements line by line ie. sequentially. Though, there are some statements that can alter this behaviour like conditional statements Mostly, python statements are written in such a format that one statement is only written in a single line, The interpreter considers the ‘new line character’ as the terminator of one instruction, Example L: print(Welcome to Geeks for Geeks’) Instructions thot a Python interpreter can execute are called statements For example, a~ 1 is an assignment statement, ifstatement while statement etc, 3wexe {In Python, end of a statement is marked by a newline character. But we can make a statement extend ‘over multiple ines with te line continuation character (\). For example: 142434) 4454644 74849 ‘This is explicit line continuation. In Python, line continvation i implied inside parentheses ( ), brackets [and braces { }. For instance, we ean implement the above multiline statement as, 142434 4546+ 74819) Here, the surrounding parentheses () do the line continuation implicitly. Same isthe ease with [] and (). For example: colors = [red “blue, ‘green'] ‘We could also put multiple statements ina single line using semicolons, as follows: ‘Most ofthe programming languages like C, C+, Java use braces { } to define a block of code, Python uses indentation, ‘[Link] block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. Generally four whitespaces are used for indentation and is prefered over tabs. Here isan example, {or iin range(1,11) princi) ifi break ‘The enforcement of indentation in Python makes the code look neat and clean. Ths results into Python programs that look similar and consistent Indentation can be ignored in line continuation. But isa good idea to always indent. It makes the code _more readable, For example: if True: print(Hello’) ans and if True: print(Hello); a both are valid and do the same thing. But the former style is clearer. Incorrect indentation will esult into IndeatationError. ents Comments are very important while writing a program. It deseribes what's going on inside a program so that a person looking a the source code does not have a hard time figuring it out, You might forget the key details of the program you just wrote in 2 months time. So taking time to explain these concepts inform of comments i always fruitful. In Python, we use the hash (i) symbol to start writing a comment. I extends up to the newline character. Comments are for programmers for better understanding of a program. Python Interpreter ignores comment, {#This is a comment ‘print out Hello print(Hello’) Mul Ifwe have comments that extend multiple lines, one way of doing it sto use hash (#) inthe beginning of cach line. For example: This is a long comment and it extends ‘ito multiple lines Another way of doing this is fo use triple quotes, either "or "™". 8 “These triple quotes are generally used for multi-line stings. But they can be used as multi-line comment swell Unless they are not docstrings, they do not generate any extra code. wwThis is also 9 perfect example of | ‘multi-line comments"™" Python Variables {A variable i a named location used to store data in the memory. Is belpfil to think of variables a a container that holds data which canbe change later thoughout programming Example 1: NI=10 08 "same" # assign the same value to multiple variables at once Print (8) print) Print @) Constants A constant isa type of variable whose value cannot be changed. Its helpful to think of constants as Containers that hold information which cannot be changed later. Example | PI=3.14 GRAVITY = 9.8 Literals Litera is a raw data given ina variable or constant, In Python, there are various types of literals they are as follows: Example L: (051010 #Binary Literals 100 #Decimal Literal c= 00310 #Octa Literal d= Ox12e #Hexedecimal Literal ‘#Ploat Literal Doat_1 = 10.5 oat_2 ~ 1.5e2 Complex Literal x=3.14) Python Operators Operators are special symbols in Python that carry out arithmetic or logical computation. The value thatthe operator operates on is called the operand. Operators are used to perform operations on variables and values. Arithmetic operators Relational operators Logical operators Bitwise operators Assignment operators Special operators ¥ Identity operators ¥ Membership operators Example: # Python Program to find the area of triangle # Uncomment below to take inputs ffom the user a= float(input(Enter first side: ) # b= float(input(Enter second side: )) #¢= float(input(Eater third side: )) # calculate the semi-perimeter fa+b-o)/2 ‘ caloulate the area area = (st(s-a)"(5-b)*(5-0)) ** 0.5 print(The area ofthe triangle is %60.20 %area) Output ‘The area ofthe triangle is 14.70 Ill, ELEMENTS OF PYTHON ‘+ A Python program, sometimes called a scrip, is a sequence of definitions and commands. ‘+ These definitions are evaluated and the commands are executed by the Python interpreter in something called the sbell ‘+ Typically, a new shell is created whenever execution of a program begins. In mast cases, a window is associated withthe shell 10 = [Link], often called a statement, instructs the interpreter to do something. ‘The basic elements of Python are: |. Keywords: and, assert, break, class, continue, defiel, elif, else, except, exe, finally, f fiom, global, if, import in, is, lambda, not or, pass, print, raise retura, ry, while, with yield Operators: +=" /% 8 > & |*= > F Deimiters: (1 (}o"=4 Jam Yom em fu => Datatypes: Numeric, Ditionary, Boolean, Set, Strings, List, Tuple Python - Data Types dat ‘+ Example for mutable datatypes are: List, Set and Dictionary ‘+ Example for Immutable datatypes are: Strings, tuple, int, float, boolUnicode, Numeric In Python, numeric data type represent the data which has numeric value, Numeric value can he interger, floating number or even complex. numbers. These values are defined int, float and complex class in Python, + Integers This value is represented by int class. It contains postive or negative whole numbers (without fiaetion or decimal). In Python there is no limit to how long an integer value can be. + Float — This value is represented by float class. It is @ real number with floating point representation, Its specified by a decimal point. Optionally, the character e or E fallowed by a Positive or negative integer may be appended to specify scientific notation. + Complex Numbers — Complex number is represented by complex class. It 8 specified as (real ‘parl) + (imaginary part). For exansple — 213} 1 Pythoa program to demonstrate numeric value print("Type of a", typet@)) =5.0 u print("inType of bs" typetb)) +4) print("inType of e "stype(e)) ourpur: Type of a ‘Type of e: Strings In Python, Updation or deletion of characters from a String isnot allowed. This will cause an error because item assignment or item deletion from a String is nt supporsed. This is because Strings are ‘immutable, hence elements ofa String cannot be changed once it has been assigned. Program: String] = "IIBSC STUDENTS" print("nitial String: ") print(String!) # Printing First cheracter prin("inFirst character of String is: ") print String1[0)) 4 Printing Last character print("inLast character of String is: print(Stringl[-1]) print("in8th char: ") print(String!(8]) # Updation or deletion of characters ftom a String is not allowed Output: Initial String IIBSC STUDENTS: Fitst character of String is 1 Last character of String is s 8th char: T Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerfol tool in Python, A single list may contain DataTypes lke Integers, Strings, as well as Objects. 2 Lists are mutable, and hence, they ean be altered even after thei ereaton, List in Python are ordered and have a definite count ‘The elements in a lst are indexed according to a definite sequence and the indexing of alist is done with Oeing the first index, Each element in the list has its definite place in the list, which allows duplicating of elements inthe list, with each element having its own distnet place and credibility Is represented by list class. Creating alist Lists in Python ean be ereated by just placing the sequence inside the square brackets[] ‘4Python program to demonstrate Creation of List # Creating a List List {] print("ntial bank List: ") print(List) # Creating a List with the use ofa String List= [IIBSCSTUDENTS'] print("inList with the use of String: ") print(List) # Creating a List with the use of multiple values List = ["HI", "BSC", “STUDENTS"] print("inList containing multiple values: °) print(Lis{0))| primtList{2)) # Creating a Multi-Dimensional List (By Nesting a list inside a List) List=[('P, BSC}, [STUDENTS] prin(("snMuli-Dimensional List") print(List) ‘Methods used in a List ‘#Append an element (ADD an element) [Link](4) print("inList aller Adding ¢ number: " primtList) # Addition of Element at specifie Position (using Insert Method) List insert(2, 12) print(List) Listinsert(0, Geeks’) print("inList after performing Insert Operation: ") Drint(List) B # Addition of multiple elements tothe List atthe end (using Extend Method) Listextend([8, ‘Geeks, ‘Always! print("inList ater performing Extend Operation: ") print(List) # accessing a element from the lis using index number print("Accessing element from the list") prin(List(0)) print List{2)) # accessing a element using negative indexing print("Accessing element using negative indexing") # print the last element of lst prinu(List-1) # print the thid last element of ist print List) List112345628] print*Original List) printList) # Removing elements from List using Remove() method [Link](S) print("iList after Removal of element: ") print(List1) List! pop() print("iList ater popping an element: ") print(Listi) # Removing element at a specific location fiom the set using the pop() method Listl-pop(2) prin(("nList eter popping a specific element PrintList!) Output Ital blank List: 0 List with the use of String [UIBSCSTUDENTS'] List containing multipfe values: mL STUDENTS. 4 Multi-Dimensiozal Li (C1, BSC], [STUDENTS] List ater Adding a number: [CIM BSC}, STUDENTS}, 4] [(M, ‘BSC}, [STUDENTS', 12, 41 List afte performing Insert Operation: (Geeks',[111, BSC}, (STUDENTS'}, 12, 4) List after performing Extend Operation: ((Gecks',[, BSC), [STUDENTS}}, 12, 4, 8, ‘Aceessing element froma the list, Geeks (STUDENTS) Accessing element using negative indexing Always 8 Original List 11,2,3,4,5,67.8] ‘Geeks, ‘Always List ater Removal of element: 11,234,678] List after popping an element 11,2,3,4,6, 7) List after popping a specific element: 01,2,4,6,71 ‘Adding Elements to 4 List Elements can be added tothe List by using built-in append) function (Only one element at a time can be added to the list by using append() method, For addition of element atthe desired position, insert() method is used. Other than append() and insert) methods, cextend() method is used to add multiple elements atthe same time atthe end of the lis. ‘Removing Elements from the List Elements can be removed from the List by using built-in remove() function. Pop() funetion can also be used to remove and return an element from the set, but by default it removes only the last element ofthe set, to remove element from a specific postion of the Lis, index of the clement is passed as an argument o the pop() method. Remove method in List will only remove the first occurrence of the searched element, 6 ‘Tuple “uple is an ordered colletion of Python objects much like @ list. The sequence of values stored in a tuple ean be of any’ type, and they re indexed by integers. The important difference between and a tuple is that tuples are immutable. Also, Tuples ate hashable whereas lists are not. I is represented by tuple clas. Creating a Tuple ‘In Python, tuples are ereated by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list etc.) Tuples can also be created witha single element, but itis abit tricky, Having one clement in the parentheses isnot sufficient, there mast be a trailing “comma” tomuke ita tuple, In python, deletion or updation of a tuple isnot allowed, + Python program to demonstrate creation of Tuple # Creating an empty tuple ‘Tuplet =O) print("Initial empty Tuple: ") print (Tuple}) # Creating a Tuple with the use of Strings ‘Tuple1 = (Geeks; For’) print("inTuple with the use of String: print(Tuple1) # Creating a Tuple withthe use of list list) = [1, 2,4, 5, 6] print("wiTuple using List: ") printtuple(ist)) # Creating a Tuple with the use of built-in function Tuple! = tuple(‘Geeks’) print("wTuple with the use of function: ") print(Tuplel) # Creating a Tuple with nested tuples Tuple! = (0,1,2,3) ‘Tuple2 = (python ‘geek’ ‘Tuple3 = (Tuplel, Tuple2) print("inTuple with nested tuples: print(Tuple3) # Accessing element using indexing print("Frist element of tuple") print(Tuplei [op # Accessing clement ffom last ~ negative indexing prin(("inLast element of tuple") 16 print(Tuplet 1) print("inThird last element of tuple") print(Tuplel[-3]) oureur: Initial empty Tuple: 0 Tuple with the use of String (Geeks', For’) ‘Tuple using List (1,2,4,5,6) Tuple withthe use of funetion: (Gee, &,'8) ‘Tuple with nested tuples: (G, 1, 2,3), (python, 'geek’)) Frist clement of tuple 0 Last element of tuple 3 ‘Third last clement of tuple 1 Boo Data type with one ofthe two builtsin values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be tue or false. Iis denoted by the class bool # Python program to demonstrate boolean type printtype(True)) primttype(False)) print(typettrue)) # Error, Small for tru is wrong et In Python, Set is an unordered collection of data type that is iterable, mutable and bas no duplicate clements. The order of elements in a set is undefined though it may consist of various elements. The ‘major advantage of using ast, as opposed toa list, s that it asa highly optimized method for checking whether a specific element is contained inthe set. v Creating a set ‘Seis can be created by using the built-in set() fianetion with an iterable objector a sequence by placing the sequence inside eurly braces, separated by “comma. A set contains only unique elements but at the time of set creation, multiple duplicate values can also be passed. The order of elements in a set is undefined and is unchangeable. Type of elements ina set need not be the same, various mixed-up data type values can also be passed to the set Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. 1 Python program to demonstrate Creation of Set in Python | 4 Creating a Set sotl = set) print("Intial blank Set: ") printsetl) 4 Creating a Set with the use ofa String set] = set("GeeksForGeeks") print("inSet withthe use of String: ") print(setl) 1 Creating a Sot withthe use ofa List setl = sc(("Gecks’, "For, "Gecks")) Print with the use of List") rinse) Creating a Sot with a mixed type of values (Having numbers and strings) sotl = set([1, 2, Geeks', 4, For, 6, ‘Geeks! print("inSet with the use of Mixed Values" printsetl) Methods used [Link](9) print("inSetafler Addition of Tare elements: ") printsetl) # Addition of elements tothe Set using Update function sotl update((10, 11)) prin(("inSetafler Addition of elements using Update printset1) # Removing elements from Set using Remove() method set] remove(9) print("inSet after Removal of two elements: ") print(setl) # Removing elements ftom Set using Discard) method sot] diseard(4) print("inSet after Discarding two elements: ") 18 printseti) ## Removing clement from the Set using the pop( method [Link]) prin(*nSet after popping an element ") print set) # Removing all the elements from Set using clear() method [Link]() print("inSet after clearing al the elements: ") print(set!) Output: ial blank Se: set) ‘Set with the use of (5,8, 80, Set with the use of List: Geeks’ For) Set with the use of Mixed Values 11,2, 4, "Geeks, 6, For) Set after Addition of Three elements: 11,2, 4, 'Gooks' 6, For, 9} Set after Addition of elements using Update: 11,2,4, "Geeks, 6, For’, 9, 10, 11) Set after Removal of two elements: 11,2, 4, "Geeks, 6, For, 10, 11} Set after Disearding two elements: (1,2, "Geeks, 6, 'For, 10, 11) Set after popping an element: 12, 'Geoks, 6, For, 10, 11} Set after clearing all the elements: set) Removing elements from a set Elements can be removed from the Set by using built-in remove() function but a KeyError arses if clement doesn't exist in the sel. To remove elements from a set without KeyError, use discard). PopQ) function ean also be used to remove and retum an element from the set, but it removes only the last clement of the set. To remove all the elements from the set, clear( function is 18 Dictionary Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single’ value as an element, Dictionary holds key-value pair. Key-value is provided in the dictionary to make it more optimized. Each key- value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. Creating a dictionary In Python, a Dictionary ean be created by placing a sequence of elements within curly () braces, separated by ‘comma’, Dictionary holds par of values, one being the Key and the other corresponding pair element being its Key-value. Values ina dictionary can be of any datatype and can be duplicated, ‘whereas keys can't be repeated and must be immutable. Dictionary ean also be ereated by the built-in function diel. An emply dictionary can be ereated by {ust placing to curly braces) [Note ~ Dictionary keys are case semsitive, same name but different cases of Key will be treated distinctly, #4 Python Program (Creating an empty Dietionary Dict= () print("Empty Dictionary: ") print(Dies) Creating a Dictionary with Integer Keys Diet = (1: Geeks’, 2: 'For, 3: Geeks’) prin(("inDietionary with the use of Integer Keys: print(Diet) i Creating a Dictionary with Mixed keys Diet = (‘Name' ‘Geeks, 1: [1, 2,3, 4]} print("inDictionary with the use of Mixed Keys: ") print(Diet) # Creating a Dictionary with diet() method Diet = dict({1: ‘Geeks, 2:'For, 3°Geeks'}) print("inDietionary with the use of dit():") primt(Diet) # Creating a Dictionary with each item as a Pait Diet = dict((1, ‘Geeks, (2, For) print("inDietionary with each item as a pair: ") print(Diet) # Adding elements one ats time Dict{0] = "Geeks? Dict[2] = 'For’ Diet[3] =1 prin(("inDictionary after adding 3 elements: print(Diet) 20 ## Updating existing Key's Value Dict[2] ="Weleome’ print("ntipdated key value: ") print(Diet) Methods used ## Python program to demonstrate for accessing elements from a Dictionary # Creating a Dictionary Diet = (1:'Geeks’, name’ ‘For, 3: Geeks") # accessing a element using key print("Accessing a element using key:") print(Diei{name'} # accessing a element using get() method print("Accessing a element using get") print([Link])) 4 Initial Dictionary Dict = (5: Welcome, 6: To', 7: ‘Geeks, YAU: {1 "Geeks, 2: For, 3:'Gecks'}, Be (1: 'Geeks’ 2: Lite} print("Initial Dietionary: ") print(Diet) # Deleting a Key value del Diet(6) print("inDeleting a specific key: ") print(Diet) 4 Deleting a Key using pop) [Link](5) print("nPopping specific element: ") print(Diet) # Deleting an arbitrary Key-value pair using popiter() Dict popitem) print("inPops an arbitrary key-value par: ") print(Dies) Deleting entice Dictionary Dictclear() print("inDeleting Entire Dictionary: ") primt(Diet) 2 Output: Empty Dictionary Dictionary with the use of Integer Keys: {1s Geeks, 2: For, 3:"Geeks') Dictionary with the use of Mixed Keys (Name ‘Geeks’ 1 (1,23, 4)) Dictionary with the use of dict) {1:'Geeks, 2: "For, 3: Geeks!) Dictionary with each item as a pair {15 "Geeks, 2: For} Dictionary after adding 3 elements: {1s "Geeks, 2: For, 0: "Geeks, 3:1} Updated key value: (1: "Geeks, 2: Welcome’, 0: Geeks', 3:1) Accessing a clement using key For Accessing a element using get Geeks Initial Dictionary: {5: Welcome’, 6: To, 7: Geeks’ 'A': (1: ‘Geeks, 2: For, 3:'Geeks'), 'B' {1: Geeks, 2: ‘Life Deleting a specific key (5:'Welcome’, 7: Geeks (1: "Geeks, 2: For, 3: Geeks) (1: "Geeks, 2:"Lifey} Popping specific clement: (7: "Gooks, "Al (1: ‘Geeks, 2: For, 3: ‘Geeks’, "B' (1: Geeks! 2: Li ” Pops an arbitrary key-value pair (7: "Geeks, "A' (1: Geeks’, 2: For, 3: ‘Geeks'}} Deleting Entire Dictionary: 6 References: ‘tps slideshave,neti143/pvhonebv- 2 UNIT I~ Question Bank PART-A 8 9. 10. 1 12. 13 14, 15. 16. i. 18. 19, 20, 1s Python a compiler or an imerpreter? Write the features of python List few Applications of Python. Compare and Contrast: Syntax Error, Somatic Error. Explain Run time Errors. Find out the use of. type (10), Find the output of a type(“I7) . type(“BSC Students”) Differentiate: Seript mode and Interactive mode. Give examples of Mutable and Immutable objects in Python. Indentation gains mach importance in Python. State True or False List out the various dats types used in python. Write few keywords employed in python. Compare and contrast: Mutable versus Immutable. What is @ Boolean value? Differentiate: Tuples and Lists in Python Create a dictionary with 4 Key-Value Pais. Mention few methods that are employed over Python List. Comment on indexing and negative indexing used in List. What are the buit-in functions tet are used in Tuple? State the purpose of pop() method. PART-B 10. Explain the Structure ofa Python Program with an example, List the Elements of Python and give a detailed note on it Write a meni-driven program, using user-defined functions to find the area of rectangle, square, circle and triangle by accepting suitable input parameters fFom user, What is the difference between lists, tuples and dictionaries? Give an example for ther usage What are the basic list operations that ean be performed in Python’? Write a menu driven program to convert the given temperature from Fabrenheit to Celsius and vice versa depending upon user's choice. Create @ Simple Calculator using a python code. How to create a dictionary? What are the methods employed over it Read the Student Name, ID, Department and marks of five subjects and find the percentage. ‘8. Write @ python code to read an integer, oat, complex values and display their data type. b, Find the Simple Interest and Compound Interest using a python code. 2 1. PYTHON INTERPRETER FEATURES OF PYTHON INTERPRETER Python interpreter offers some pretty cool features + Interactive editing + History substitution ‘+ Code completion on systems with support for readline INVOKING THE PYTHON INTERPRETER (On your machine, you can find your interpreter at an address like C:APython36 (Or it may reside om the location you selected at the time of installation. Add path using this command set path-"epathY4:C:\python36 INTERACTIVE MODE Python interpreter is in an interactive mode when it reads commands fiom a ty. The primary prompt is the following: ‘When it shows this prompt, it means it prompts the developer forthe next command. This isthe REPL. Before it prints the first prompt, Python interpreter prints a weleome message that also states its version number and a copyright noti This is the secondary prompt: 1 ‘This prompt denotes continuation lines S python3.7 Python 3.7 (default, Jul 16 2018, 04:38:07 GCC 4.8.2) on Windows license” for more information ‘You will find continuation lines when working with a muki-line construct: >>> it_ rains “True => ifit_sains: The produce will be good” ‘The produce will be good 8 ‘We can also use the Python. interpreter asa calculator: po e7 4 pop ain 20 HOW DOES PYTHON INTERPRETER WORKS? Four things happen in a REPL: i. Lexinge The lexer breaks the line of eode into tokens. ii, Parsing- The parser uses these tokens o generate a structure, hee, an Abstract Syntax “Tree, o depict the relationship between these tokens. iit, Compiting- The compiler turns this AST into code objects) iv. Interpreting- The interpreter executes each code object. USING PYTHON AS A CALCULATOR ‘Start with simple Python commands. Start the interpreter and wait forthe primary prompt, >>>. ‘The interpreter acts as a simple calculator: you can type an expression att and it will write the value, Expression syntax is straightforward: the operators *,-, * and / work just like in most other languages (or example, Pascal or C); parentheses (()) can be used for grouping. For example: ‘The integer numbers (eg. 2,4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. Division () always returns a float, To do floor division and get an integer result (discarding any fractional resut) you can use the i operator; to calculate the remainder you can use %: 5 >>> 17%3 Hthe % operator returns the remainder of the division 2 Doe $4342 H result * divisor + remainder 7 ‘With Python, its possible to use the ** operator to calculate powers | Do> 592 45 squared 25 >>>2**7 #2 tothe power of 7 128 ‘The equal sign (=) is used to assign a value toa variable, Afterwards, no result is displayed before the next interactive prompt >>> width = 20 >>> height =5*9 >>> width * height 900 | Strings [Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They «ean be enclosed in single quotes ('.) or double quotes (".") with the same result 2. \can be used to ceseape quotes Bl ‘spam eggs! >>> s~ First line \nSecond line.” # In means newline >>> # without print), in is included in the output "First line inSecond line” >>> print() # with print), n produces a new line First line Second line >>> #3 mes ‘un’ followed by ‘ium’ >o>3 + un' + Sum! | 2 Lists Python knows a number of compound data types, used 10 group together other values. The most versatile is the lst, which can be written asa list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usualy the items all have the same type. >>> squares ~[1, 4,9, 16, 25] >>> squares 11,4,9, 16,25] Like strings (ang all other built-in sequence types) ists eam be indexed and sliced: >>> squares[0] # indexing returns the item 1 >>> squares{-1] >>> squares[-3:] # slicing returns a new list (9, 16, 25] All slice operations return a new lst containing the requested elements >>> squaresl:) 11,4,9, 16, 25] Lists also support operations like concatenation: >>> squares + [36, 49, 64, 81, 100] 11, 4,9, 16,25, 36, 49, 64, 81, 100] ur strings, which are immutable, lists are a mutable type, ie. iti possible to change their content >>> eubes =[1, 8, 27, 65, 125] # something's wrong here Do>d 493 Hthe cube of is 64, not 65! 64 >>> eubesl3] = 64 tf replace the wrong value >>> cues 11, 8,27, 64, 125] >>> print("The value of iis’, i) “The value of iis 65536 28 Program 2: > a,b=0,1 >>> while a < 1000: printa, end='") b=b,at 0,1,1,2,3,5,8.13,21,34,55,89,144,233,377,610,987, py ON JL (NTERPRET Python is an interpreter language. It means it executes the code line by line, Python provides @ Python Shell also known as Python Interactive Shell) which is used to execute a single Python command and get the result. Python Shell waits forthe input command from the user. As soon as the user enters the command, it executes it and displays the result eS een aa ee Python Shell [As you can see, a Python Prompt comprising of three Greater Than symbols (>>>) appears. Now, you ‘can enter a single statement and get the result. For example, enter a simple expression like 3-+ 2, press center and it will display the result inthe next line 28 Bid C\Winciows\system32\emeiexe - python eT rrr Ey eit arcs) ero eeesortny oer ron mC ee Eee eters Cetera tr amoee tee (Command Execution on Python Shell Execute Pythor ipt Python Shell executes 2 single statement. To execute multiple statements, create a Python file with extension py, and write Python seripts (multiple statements). For example, enter the following statement in a text editor such as Notepad. Example: [Link] prin print This is Python Serip.") ‘Welcome to Python Tutorial by [Link] Save it as myPythonScript py, navigate command prompt tothe folder where you have saved this file and execute the python [Link] command, as shown below, IBS CWindowjtemiacndane Python Shell Thus, you can execute Python expressions and commands using Python Shell PYTHON - IDLE IDLE (Integrated Development and Learning Environment) is an integrated development environment (IDE) for Python, The Python installer for Windows contains the IDLE module by default, IDLE can be used to execute a single statement just like Python Shell and also to create, modily and ‘execute Python scripts, IDLE provides a fully-featured text editor to create Python serips that includes 30 {Features like syntax highlighting, autocompletion and smart indent. I also has a debugger with stepping and breakpoints features Goto File->New File and open a new Script page and enter multiple statements and then save the file with extension py using File -> Save. For example, save the following code as [Link]. i Fle Edt Fama fim Optent Window Hep prise (Welle Wosia") ree rial by TucortaiaTeacnercon*)] Python Seript in IDLE Now, press P5 to run the script inthe editor window. The IDLE shell will show the output (UB Pron 65a _ | ie foe Shel Geog Qos inde ep 2) os wins Type "copyragne™, toreaite* RESTART? C+\usera\den2\Arpbaza\Locai\ Programs\Fyshen\Pyenons6-sa\[Link] = Nelasee t= Eythen Toreetal ny TorsrssleTeacher com >>I 2018, 16:07:46) [HSC v.1900 $2 Bit (In fof "iicense()" for mare informacion. Python Script Execution Result in IDLE ‘Thus, itis easy to write, test and run Pythoa scripts in IDLE. PYTHON INDENTATION ‘Most ofthe programming languages like C, C+, Java use braves { } 10 define a block of code, Python uses indentation, ‘A code block (body ofa function, loop etc. starts with indentation and ends with th first unindented line. The amount of indentation is upto you, but it must be consistent throughout that block. Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example, for iin range(1,11): princi) iti break ‘The enforcement of indentation in Python makes the code look neat and clean. This results into Python programs that look similar and consistent a Indentation can be ignored in line continuation, But it’s a good idea to always indent. It makes the code more readable. For example: if True: print(Hello’) ans and if True: prin Hello); @ both are valid and do the same thing, But the former style is clearer. Incorrect indentation will result into IndentationError. Atoms ‘Atoms are the most basic elements of expressions, The simplest atoms are identifiers or literals. Forms fenclosed in reverse quotes or in parentheses, brackets or braces are algo categorized syntactically as atoms. The syntax for atoms is ‘stom: identifier |iteral | enclosure enclosure: parenth_formlist_display|dict_displaylstring_conversion PYTHON IDENTIFIERS ‘An identifier isa name given to entities like class functions, variables, ete. It helps to differentiate one entity fFom another. Rules for writing identifiers 1. Identifiers can be a combination of letters in lowercase (a to 2) or uppercase (A to Z) or digits (0 to 9)or an underscore .Names like myClass, var 1 and print this to sereen, all are valid example, 2. An identifier cannot start with a digit. Ivariable is invalid, but variable] is perfectly fine 3. Keywords cannot be used as identifiers. >>> global File "", line 1 slobal = 1 SymtaxEror: invalid syntax 4, We cannot use special symbols like !, @, #, $, % etc. inthe identifier 32 >>> a@=0 interactive input>", line 1 a@-0 Syntaxtror: invalid syntax 5. Identifier can be of any length, PYTHON KEYWorDS Keywords are the reserved words in Python, We cannot use « keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. There are 33 keywords in Python 3,7, This number can vary slightly in the course of time. All the keywords except True, False and None are in lowercase and they must be written as it is. The list of all the keywords is given below. keywords in Python ALS. Literal is a raw data given ina variable or constant In Python, there are vatious types of literals they are a follows: 33 Example |: = Ob1010 Binary Literals b= 100 #Decimal Literal = 00310 #0ctal Literal d= OxI2c #Hexadecimal Literal ‘Float Literal ooat_! = 10.5 Moat? ~ 1 5e2 Complex Literal x=3.14) STRINGS In Python, Updation or deletion of characters fiom a String is not allowed. This will cause an error ‘because item assignment or item deletion from a String is not supported. This is because Strings are ‘immutable, hence elements of a String eannot be changed once it has been assigned. Programs: String] = "IIBSC STUDENTS" print"Initial String: ") print(String!) # Printing First character print("inFist character of Sting is: ") print(String!{0]) # Printing Last character print("inast character of String is: print(String![-1]) print("inth char: ") print Sting! [8]) # Updation or deletion of characters ftom a String is not allowed Output: Tatil Sting IIIBSC STUDENTS. First character of String is: 1 Last character of String is s Sth char: T 34 Il, OPERATORS IN PYTHON Operators are special symbols in Python that carry out arithmetic or logical computation, The value thatthe operator operates on is called the operand Operators are used to perform operations on variables and values. Arithmetic operators Relational operators Logical operators Bitwise operators Assignment operators Special operators ¥ Identity operators ¥ Membership operators 1. Arithmetie operators: Aithmetic operators are used to perform mathematical operations like ation, subtraction, multitcation and division, + Acco: ads two operands ay - ‘Subtraction: subtracts two operands wy . Mutioeation: mutes two operands ety ' Division (oat): vides the first operand by the second xy 11 Divison (loo ances the fst operand by the second xy % Modulus tums the remainder when st operands vided by the second xy # Examples of Arlimetie Operator ano bd # Addition of numbers # Multiplication of umber *b # Division(foat) of number divi=a/d # Division(foor) of number diva 35 7 Modulo of both nuraber mod=a%b 4 pit resus printada) prin(sub) prin prinivl) print(aiv2) prini(mod) output 3 5 36 225 2 1 2, Relational Operators: Relational opetors compares the values, tether returns Tue or False according to the conton > Greater than: True left operand is grater than the ight wy < Less than: True tet operand sles han theright wey Not equal o- Tue if operands are not equal xky Greater than or equal: True'f lft operand i reater than or equal tothe right Lese than or equate: True et operand isles than ar equal 10 ‘an Key Program, 7 Examples of Relational Operators 3 3 #a>bis False print(a> b) #a= is False print(a >=) #a<=bis Tue print(a <=) output False Te False True False ‘Te 3 Logical operators: Logical operators perform Logical AND, Logical OR anc Logical NOT operations. and Logical AND: Tus fboth the operands are true randy or Logical OR Tru ifthe ofthe operands is tue xey a Logical NOT: True foperand is false nat Print a and b is False print(a and b) # Print aor is True print(a or b) 4 Print not ais False printinot a) Output False ‘Te 37 False 4. Biwise operators: Biwse operators acts on hits and performs bit bt operation & Bie AND xay ' Braise oR xly - Biwi NOT ~ a Bis XOR es > Buise night st we a 60 #60= 0011 1100 b= 13 #13=0000 1101 ond a&b; — #12= 00001100 print "Line 1 - Value of es", € e=alb; _#61=0011 1101 print "Line 2- Value of is", Sb; #49=0011 0001 print "Line 3 - Value of i" © #-61= 11000011 print "Line 4 - Value of es", a<<2; #240= 1111 0000 print "Line 5 - Value of es", € em a>=2; #150000 1111 print "Line 6 - Value of¢ is Output Line 1 - Value of is 12 Line 2 - Value of is 61 Line 3 = Value of is 49 Line 4 - Value of is -61 Line 5 - Value of is 240 Line 6 - Value of is 15 38 5. Asclgnment operators: Assignment operators are used io assign values tothe varables Assign value of right sie of expression tet se operand ‘Ad AND: Ada ht side operand ith left sie operand end then sign t et eparana = Swotiget AND: Suotact right operand trom let operand end then ab asad sign tet operand += Multpy AND: Mutipiy right operandwith lett aperand and then assign at=b asa tolettoperand /= Divide AND: Divide let operand with right operand and then assign to wale + Mogulus AND:Takas modulus using let and toh operana and assign ati-b a-ab result er operand (= Dlude(Reot) AND: Divide let operand with ight operand and then eae ‘assign the yaue( oor to left operand “= Exponent AND: Caleulate exponent(ase pow) value using operands Performs Bhwise AND on operands and assign value to lett operand Ie Performs Btwise OR on operands and assign valve o lft operand e-aib ‘= Performs BtwisexOR on operands and assign valet left operand atab arat >= Performs Btwise ight shift on operands andl assign value left operas Performs Bhwise eft shift on operands and assign value to et eran 6, Special operators: There are some special type of operator ks * Identity operators- {i and is nt ate me enty opeators bot) are used to check tf two valves ae located on the ‘Same part of the memory. Two vanables that are equal doesnot mpl that they are identical 39 Program: [7 Examples of Identity operators al=3 bl=3 a2 = "GecksforGeeks’ bd = GeeksforGeeks a3 (1,23) b3= [123] print(al is not bl) print(a2is 62) 4 Output is False, since lists are mutable, rint(a is b3) Output False ‘Te False + Membership operators Inand not in ae the membership operators; usedto test whether @ value or variables in 2 sequence, an Tove 4f value 4s found én the sequence not in Tove 4f value 4s not found An the sequence Program: 7 Examples of Membership operator x= 'Geoks for Geoks' yo Bab) print’ in x) print(geeks’ not in x) print( Geeks! not in x) print( in y) print’ in) apple", "banana" Po rint("banana” in) returns True because a sequence with the value "banana” is inthe list print("pineapple” not in x) a yt in the list, urns True because a sequence with the value "pins Output Tue ‘Tne False Tue False Te ‘True Ternary operator TTemary operators also known as conditional expressions are operators that evaluate something based on a condition being tue or false, It was added to Python inversion 2. It simply allows to test a condition in @ single line repiscing the multiline ifselse making the code compact, Syntax: {on true] if fexpression] else [on_ false] ‘Example 1: Simple Method to use temary operator + Program to demonstrate conditional operator a,b= 10,20 4 Copy value ofa in min ifa >2, PART-B 1. Give an example of how Python can be used asa caleulatr. 2, How Python Operates over Strings? 53. Explain string slicing with examples 'b. How to split strings. Explain with examples. 4. List out the various operators used in python and explain them, 5. Give a detailed note on: a. Ideatity operators 'b. Membership operators © Boolean operators 6. Given A=60, B=I3. Using A and B, explain all the bitwise operators used in python. I. INPUT AND OUTPUT STATEMENTS Input Statement; Input means the data entered by the user ofthe program. In python, we have input() and raw_input( ) function available for Input LL inputo function Syntax: input (expression) 1fprompt is present, itis displayed on monitor, after which the user can provide data from keyboard, Input takes whatever is typed ffom the keyboard and evaluates it. As the input provided is evaluated, it expects valid python expression, If the input provided is not correct then either syntax error oF exception is raised by python, Example 1: ter any value Print "Entered value is: ", x) Output Example 2: print (input ()) x = inpu! Print ("Your inpu: is: ", x 2iraw_input{) function This int method fairly works in older versions (like 2. Syntax: aw_input (expression) i prompt is present, itis dxplayed on the monitor aller which wer ean provide the data from keyboard, The function takes exactly what is typed from keyboard, convert ito string and then retura ito the variable on LHS of =. Example: In interactive mode xis a variable which will get the string (ABC), typed by user during the execution of program. ‘Typing of data for the raw_input function is terminated by enter key We can use raw_input() to enter numeric data also, In that case we typecast, i, change the data type using fimetion, the string data accepted from user to appropriate Numerie type Example: 6 Soy-int (zaw_input ("Enter your It will convert the accepted string i.e., 5 to integer before assigning it to ‘y'. Output Statement: 1. print) function/statement print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent outpt (3), To print more than one item on a single line, comma (,) may be used, print (expression/constantivariable) Example 1 print print print ("Hel io!” BEANE ("iow axe you! print Print . print Output a Example 2: print print Print print print print Print. Print print print print Print. print print print rinting direct values 1G, 20, 10, 20, 30, 30, 40, 40, 50} 10, 20, ‘rinting variables 2) variables 1b) I. CONTROL STATEMENTS BRANCHING, LOOPING, CONDITIONAL STATEMENT, EXIT FUNCTION, DIFFERENCE BETWEEN BREAK, CONTINUE AND PASS) ‘The ifstatement if'statement isthe most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not ie if certain condition is true then a block of statement is executed otherwise not Syntax: if condition: 4 Statements to execute if # condition is true Exh x= evallinput("Enter x: ")) ‘The if else statement with multiple statements ‘The if statement alone tells us that if a condition is true it will execute a block of statements and ifthe condition is false it won't. But what ifwe want to do something else ifthe condition is false. Here comes the elte statement, We ean use the else statement with if statement to execute a block of code when the condition is false. Syntax if (condition): + Executes this block if # condition is true ose: 4 Executes this block if # condition is false ry print ‘Hi spar’ print "Nice weather we print Have a nice day!" le: print not spam ‘an if statement within another if statement) nested-if A nested ifs an if statement that i the target of another if statement, Nested if statements means an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. ie, we can place an if statement inside another if statement. Syntax: if (condition) # Executes when condition! is true if condition?) Executes when con # if Block is end here # i Block is end here ond is true xl: score=int(Score) if'score>-80: sgrade=A" cle: if score>=70: ‘grade~! else ade='C print "Grade ig:”-tgrade ‘A neited ifexampie's using iielse score = raw_input("Enter score: ") score = int(Score) if score > 80: if'score >= 70: ‘grade olse if'score >= 55: grade olse if score >= 50: 50 rade = Pass else ‘grade ~ Fail print "ninGrade is: "+ grade litelse ladder Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controling the if is true, the statement associated with that i is ‘executed, and the rest of the ladder is bypassed. If none ofthe conditions is true, then the final else statement will be executed, Syntax if (condition) statement elif condition): statement svore = raw_input("Enter score: ") score = int(Score) score >~ 80: clifscore >= 55: rade =" lif score >= $0: grade = Pass! lee grade Syntax while expression: st statement(s) Example. x= While x<= 5 print om spam’) print (T love spam’) print (dons) print (one) Output: Hispam {ove spam Hispam Tove spam HHispam Tove spam Hi spam Tove spam Hi spam Tove spam done gone Examples Python supports to have an l ‘+ Ifthe else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the lst + If the else statement is used with a while loop, the else statement is executed when the condition becomes false Ex count = 0 while count <5: print (count, "is tess than count = count ~ 1 cle: print (count, "i not les than 5") Output: (O is less than 5 1 is less than § 2 is less than 5 3 is less than S 4 is ess than 5 5 is not less than $ 52 Examples of while loops - the infinite lop xo while x print Hi spam xextl print Tove spam print Press the Ctrl key and the C key together’ print to interupt this program.” print ‘done’ while 1 print ‘Span’ ifanswer == 5) print Fries with that?” break print Have a" Example: use inue in sloop. while 1 print ‘Spam’ ifanswer print Large fies with spam, mmmm, yummy" continue answer = raw_inpul(Tlad enough yet?) ifanswer break sut(Press y for large fies") print Have a" Example: the counter-controlled for loop For Loop Syniax {or iterator_var in sequence statements(s) 33 sxample: the counterscontrolled for loop fore in range (5,10): print © # Note: range (5,10) is 5 through 9 Output: 5 6 7 8 8 "ikampie: how to use's for loop in computing s=0 for val in m shal Example: For loop wih sirings for letter in'Python': # First Example print (Current Letter’, leter) fruits = [banana ‘apple, ‘mango for tuit in fruits’ # Second Example Print (Current fut rit print ("Good bye!") ‘Ouro ‘Current Letter : P (Current Letter: y Current Letter 11 Current Letter :h Current Letter: Current Letter !n (Current fruit: banane Current uit: apple Current fruit : mango Good bye! for ein range (1,6): ife—=3) break print © Output 1 sa ‘Example: how to use a loop within a loop a nested for loop, print ("This is the stat of the program") for iin range (1 for jin range (1,3) for kin range (1,3) str) + este) "ke" + str) Pl print ("Hi Output This isthe start ofthe program iif lke inlp lk ilp2k inj 2k ii2h- 1k ii2f1k cxit() is defined in sitepy and it works only ifthe site module is imported so it should be used in the interpreter only. Its like a synonym of quit( to make the Python more user-fiendly. It too gives a message when printed: Example. 4 Python program to demonstrate exit) for iin range(10): 4 Ifthe value of i becomes #5 then the program is forced Ho exit iti 5: 4 prints the exit message print(exit) exit) princi) Output: grenee 55 DIFFERENCE BETWEEN BREAK, CONTINUE AND PASS Break statement ‘The break statement is used to terminate the loop or statement in which itis present. Afler that, the control will pass to the statements that are present after the break statement, ifavailabl. If the break statement is present in the nested loop, then it terminates only those loops which ‘contains break statement Syntax: break Continue statement ‘This statement is used to skip over the execution part of the loop on a certain condition, After that, it transfers the control tothe beginning of the loop. Basically it skips its following statements and continues wit the next iteration ofthe loop. Syntax: continue Pass statement {As the name suggests pass statement simply docs nothing, We use pass statement to write empty loops. Pass is also used for empty control statements, funetions and classes, Syntax: pass Example: 4 Python program to demonstrate 4 difference between pass and # continue statements = "geeks" 4 Pass statement far ins: ifim= print(Pass executed’) pass print(i) print) # Continue statement foriins 56 iti: print(Continue executed’) continne princi) ours ass executed ‘ontinue executed 1 geen Break Statement: It brings control out ofthe loop ass Statement: ‘We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes Continue statement: forces the loop to continue or execute the next iteration, 37

You might also like