Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Unit-2 Python

python notes

Uploaded by

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

Unit-2 Python

python notes

Uploaded by

Syeda Tasmiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 46
"nal nates nea ae TYPES, OPERATORS AND EXPRESSIONS o & Variables can hold values, and every value has a data type. Python is a dynamically typed languagei hence we do not need to define the type ofthe variable while pene si declaring it, The interpreter implicitly binds the value Python ate with its type. data types o . By 1S — a + The variable a holds integer value five and we did not define its type. Python interpreter will automatically ‘ype. interpret variables a as an integer tyPe + Python enables us to check the type of the vars fcr used in the program. Python provides us the type( eovildae ef introduction of the See Reece sed: | ite. cteniaresee aay Consider the following example to define the values of (gnuneeers maine OS ee e Number stores numeric values. ‘The integer, float, and ee complex values belong to 2 Python Numbers data- ation 2 type. Python provides the typeO function to know the = 105: data-type of the variable. Similarly, the isinstanceQ) print(type(a)) function is used to check an object belongs to 4 print(type(b)) particular class. print(type(e)) Python creates Number objects when a number is assigned to a variable. For example; one ee type 'st’> print("The type of a", type(a)) b= 405 Standard Data Types * A variable can hold different types of values. For ‘example, a person's name must be stored as a string whereas its id must be stored as an integer. © Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below. 1. Numbers 2) Sequence Type 3. Boolean 4, Set Dictionary 1 of numeric data. bbe any length such as integers ae spatatsn ce yin has eticon onthe Jenatn of an integer Its value belong 12 Float - Float is used to store floating-point numbers Ike 19, 9.902, 152, ete. It is accurate upto 15 decimal Ean ymplex number contains an ordered imaginary parts, respectively. The complex numbers like 2.14), 2.0 + 23}, ete (6) Strings + The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use single, double, or triple quotes to define a string. * String handling in Python is a straightforward task since Python provides built-in functions and operators to perform operations in the string, *+ In the case of string handling, the operator + is used to concatenate two strings as the operation “hello'+* python” returns “hello python”. + The operator * is known as a repetition operator as the operation “Python” *2 returns 'Python Python’ The following example illustrates the string in Python. Example 1: StF = "String Using double quotes" print(str) 3=!""""A multiline string’”" print(s) Output: string using double quotes A multiline | string Consider the following example of string handling, Example 2: ‘strl= ‘hello pythonpoint’ #string strt supports three tYPes 1. int Integer value can (Stri[0'2)) #printing first two character using ae atest Drint (str4[4)) #printing 4th character of the string Print (str1%2) #printing the string twice trl + str2) #printing the ‘concatenation of trl output: he hellopythonpeinthellopythonpoint hellopythonpoint how are You (© Booleans + Boolean type P' rovides two built-in values} d to determine Ise, These values are use rae nt re. denotes by the True can be represented by any non-zero whereas false can be represented by the Consider the following example. +# ython program to check the boolean type print(type(True)) print(type(False)) print( false) Output : Nametrror: name ‘false’ is not defined + The truth values of an expression is stored a5} data type called bool. There are only two such} this data type. True and False, Boolean Data Types In the below program we find out the data and False Boolean values. print(True) print(type(True)) print(False) rint(type(False)) Output: False Boolean Expression 3 sit “TYPES, OPERATORS AND EXPRESSIONS PYTHON PROGRAMMING (DBATU) 23) Example RATORS ‘Syntxbool (el) , The operator can be defined as a symbel which 1 ReturnsTrucif X evoluates to trveelsefalse. responsible. for particular operation, between M0 Without parameters it returns false. peands. Operators are the plas of» program on we Below we nave examples which use numbers seams and | the logic is bull in a specie. progremrind, Cae Senter tee ee roraetan tothe boo! function. The | Python provides a variety of operators: whch are results come out us tre or fale depending on the | as follows. parameter 1. Arithmetic operators ample 2. Comparison operators bata 3. Assignment Operators print(booKa)) 4, Logical Operators = + Check folse 5. Bitwise Operators _ 6. Membership Operators | 7. Identity Operators ) 1. Arithmetic Operators "4 Arithmetic operators are used to perform arithmetic p= operations between two operands. It includes + (addition), | “eubtraction) * (multiplication, / (divide), % (reminder), // | itor divsion, and exponent (operator i Consider the following table for a detailed explanation of | |_ arithmetic operators. | ieee), Table 2.1 y # Check None. | [Operator Description t a:None . | printtoro() | + (Asin) tis used oad wo operands, For example, # Check an empty sequence Ls a=20, e ubtacton) | tis used to subtract the second of aed sub perand from air agones the frst operand, ifthe fst operand is less than, a mopping the second operand, the vale results negative, ie For example ifa=20,b=10=>a-b= 10 Fic on ony ing 7) le returns the quotient after dividing the frst @="Tutorilepoint” operand by the second operand For . rint(bocl(a)) =20,b=10=>ab=20 eanee. iL eres * (Mutipicaton) | Wis used Running the above code gives us the flloning resuk ~ | 8 sed to mutpy one operand with theater True For example, ifa=20,b=10=>a*b=200 False % reminder) | Wet ES ms the reminder after dividing the fist Opt bye sein cpr Far Tue a=20,b= oa We b= 10 =>9%b =o fe jase * (Exponent a false ") | Its an exponent operator represented es False Calas the fs operand False i SPREE 00 a ll Te een) st PYTHON PROGRAMMING (DBATU) ‘Comparison (Relational) Operators ep following table. Table 2.2 Comparison operators are used to comparing the value of the two operands and returns Boolean true or falce ‘accordingly. The comparison operators are described in the Operator Description condition becomes true If the value of two operands is equal, then the ie ‘Alsb vill be equal toa ab tr b=3, alleb wll assign 4 condition becomes tue ‘second operand, then the contion becomes re, Wie frst operand is greater than or equal fo the second operand, then the codon becomes tue. Whe frst operand is greater than the second ‘operand, then the condition becomes tue. Ifthe value of two operands is not equal, then the Ifthe first operand ls less than or equal fo the evaluation to 4. Logical Operators The logical operators are used primarily in the make a decision. Python st following logical operators. sextevanmbonss tin | rentwcritnisonests 3) Asclonment Operators operators are described in the following table. Table 2.3 Description 2 ofthe right expression tothe lft Ht inreases the value ofthe left operand by the Walle of the right operand and assigns the modified Value back to lft operand. For example, if a = 10, b= 20 => at = b will be equal to a = a+ b and therefore, a= 30 | lt decreases the value ofthe lft operand by the | Value of the right operand and assigns the modified walue back to left operand. For example, if a = 20, b= 10 => a= b wil be equal to a= & b and therefore, a= 10, | It mulipies the value of the lett operand by the Value ofthe right operand and assigns the modified Value back to then he left operand. For example, if a= 10, b= 20=>a*= bwillbe equal to a=atb and therefore, a= 200, Ite st operand is less than the second operand, The assignment operators are used to assign the value of the right expression to the left operand, The assignment Table 2.4 Y ante Description ‘aed | it both tre exresion are te, then the o be tue. a and b are the to expression, a = tue = a and b te. or | fone ofthe expressions iste, then te cong . be tue. I’ and bare the two expression, a. ee | = false => aor — te. Tot | fan expression ae tue, then not (a) willbe d vice versa, le : 5, Bitwise Operators oe ae ‘The bitwise operators perform bit by bit operation @nifl element certal values of the two operands. Consider the fell example. For Example, c ifa=7 eee ‘isnot then, binary (a) binary (b) = Expressions 8. Operat hence, a & b = 0011 ‘The preced a|b= 0111 since it en evaluated | a%b=0100 ~a=1000 Python Table 2.5 & (binary and) | If both the bits at the same place int ‘are 1, then 1 is copied to the O is copied. ‘4 | (binary of) ‘The resulting bit will be 0 if both the bi ctherwise, the resulting bit willbe 1 fas, Pres nts se an} 1 on low See : , “TVPES, OPERATORS AND EXPRESSIONS PYTHON PROGRAMMING (OBATU) os) aaa Binary ps, and mies neal Loti and ight ti | * a [uenanin and gitar (binary x0") | The resulting bt wil bo 1 i bo the Bis F erent tert, the resling bt ib 0. Bina be Binary xo, and oF ~(nepaton) | eaeules the neaton of each i lf operand, # be bs 0, bers Bt WP ‘Comparison operators (ess than fess than equal : 1 and ve versa, to, gostor tan, greater then equa) S ~<(et shit) | The lett operand vave is moved lef by He avy operators. ube of is presentn tera operand ‘Assignment operators > (ight sit) | The et operand is moved rgb he number of tis rosea inte rah operand | 6. Membership Operators Python membership operators are usec membership of value inside a Python data structure. If the value is present in the data structure, then the resulting d to check the | found inthe second operand (stun, o ctona). 7. Identity Operators The identity operators are used to decide whether an element certain class or type Table 2.7 Operator Description is | itis erabated to be we fhe reerence present at | | * | both sides point othe same obec. isnot | iis evaluated tobe tue if the reference present at bath sides do not pont othe same objec. | Expressions and order of evaluations ‘Operator Precedence The precedence of the operators is essential to find out since it enables us to know which operator should be evaluated first. The precedence table of the operators in aaa ryoperate” | Sh | 5 Innotin totorand vemberstip operators Logial operators value is true otherwise it returns false. Consider this expression Table 26 a Operator Deseiton Ty | 5 >>20+470 in| itis evaluated tbe tue he fist operandi found in| | 60 the second operand (st ple, or cctiona) There is ambiguity here. Should Python perform the retin | I's evauated to be tue Ihe fst operand is ro jdcition 20 + 4 frst and then multiply the sum by 10? Or should the multiplication 4 * 10 be performed first and the addition of 20 second? Clearly, since the result is 60, Python has chosen the er i it had chosen the former, the result would be found 0. This is standard algebraic procedure Universally in virtually all programming languages. All operators that the language supports are assigned a precedence. In an expression, all operators of highest precedence are performed first. Once those results are obtained, operators of the next highest precedence are. performed. So it continues, until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order. Here is the order of precedence of the Python ‘operators you have seen so far, from lowest to highest: | — Python is given below. Ae Table 28 Operator Description cee + | The exponent operaioris given prioty over a rocevonee the others used in he expression == |The negation, unary ps, and minus */%i1 | The multiplication, divide, modules, reminder, and floor dion =Conti. bitwise XOR, bovis AND bishits aon, subtraction ‘mutipleaion, division, oor division, modvlo ‘unary postive, unary negation, bitwise negation Highest precedence jee oles aes] ‘exponentiation * Operators at the top of the table have the lowest precedence, and those at the bottom of the table have the highest. Any operators in the same row of the table have equal precedence. * It is clear why multiplication is performed first in the example above: multiplication has a higher precedence than addition, + Similary, in the example below, 3 is raised to the power of 4 first. which equals 81, and then the multiplications are carried out in order from left to Fright (2 81*5 = 810) >>oz3a's 810 Operator precedence can Parentheses. Expressions in parentheses are always Performed first, before expressions that are not Perenthesized, Thus, the following happens: >>>20+4410 60 >>>(20+4)"10 240 >>> p>o2034'5 #10 >>>293"(445) 6973568802 In the first example, 20 + 4 is com ‘result is multiplied by 10. In the s is calculated first, then 3 is raised to the results multiplied by 2. be overridden using puted first, then the econd example, 4 * 5 that power, then oe wo a evaluation. In fact, it is coq anne best ye the order of Shara ase hen ete ae cakes te cadet of reat ar edence OM. EMO folowns + Here the rereparson operators re pe would have been be ane oes rome might consider the anton and warion more immediate ob this version without parentheses: ane os certain ¢ ‘ad Oandb>30 cen «On the other hand, there are probably would prefer the latter, its a matter of preference, The point is, you can at parentheses if you feel it makes the code readable, even if they aren't necessary to order of evaluation. Control Flow «A program's control flow is the order in program's code executes. ‘+The control flow of a Python program is conditional statements, loops, and function calls Python has three types of control structures: 1, Sequential - default mode 2. Selection - used for decisions and br 3. Repetition - used for looping, i piece of code multiple times. 1. Sequential Sequential statements are a set of state with sequential statements is that if the logi any one of the lines, then the compl execution will break. ‘ @ PYTHON PROGRAMMING (OBATU) “ The selection statement allows 8 several conditions and execute Instruction which condtion is tre. + Some Decision Conta Statements ae: program to test is based on the (2) Simple if the (©) if-else than (© nested if are contro! flow statements fag] Sl coe ben we Certain condition is met or satisfied. A simple if only ad has one condition to check who nal Use fore the iteandtion's | tfeondons | | a false the by Fig, 22 n=10 Ja, ifnm Print(’nis an even number") (b) if-else: The if-else statement evaluates the condition 3s@| 2d will execute the body of if if the test condition is m| True, but ifthe condition is False, then the body of else | isexecuted. print('n is odd") (@ nested if: Nested if statements are an if statement inside another if statement. Cnt [ Execute ett Execute else Fo.24 a5 b=10 F165 ifa>b: ifarc: print(“a value is big") else: rint("c value is big) elif b> es sae Print("b value is else: coiiuil (@) if-elif-else: The ifelif-else elif x>y: rint(*x is greater than y") else: print("x is smaller than y") Tf and if-elif-else * Decision making is the most important aspect of almost all the programming languages. As the name implies, decision making allows us to run a particular block of code for a particular decision. + Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making, + In python, decision making is performed by the following statements. Table 2.10 oT Statement Description {f Statement The if statement is used to lest a specific condition, I the condition iste, a block of code (bleh willbe exceed The itelse statement is similar to statement except the fact thal, it also Provides the bock of he code forthe fase ase ofthe condition to be checked. If the condition provided inthe f statements ase, then the els statement il be executed. Nested if statements enable us fo use if else stalementinsde an outer if taement If- else Statement Nested if Statement For the es of programing and 6 shove hon doesnt allow the use of parentheses Pee ea code In Pinon indetation i devlare a block If two statements are at t indentation level, then they are the Part of the, block wt Generally, four spaces are given to i Statements which are a typical amount of in in python Indentation is the most used part of the language since it declares the block of code, statements of one block are intended at the sa indentation. We will see how the actual inde takes place in decision making and other python The if statement The statement is used to tet a particular condition and the condition is true, it executes a block of cade known ifblock. The condition of if statement can be any valid logical expression which can be ether evaluated to true false Enter b? 120 Enter ¢? 130 cis largest ‘The if-else stat + The if-else ohare wie 6 : ra.28 The syntax of the if-statement is given below. if expression: Be statement. Example 1: ; rum = int(input(“enter the! if num%e =: print("Number is e Output : enter the number?10 Number is even output: Enter a? 1 Condition and code known as n be any valig | =18 ss print("You are eligible to vote I): else! oa print(*Sorry! you have to wait i): Output : Enter your age? 90 You are eligible to vote !! Example 2: Program to check whether a number is even or pan int ipa enter the number?) if num%2 == 0: print("Number is even.) else: print("Number is odd...") Output: enter the number?10 | Number is The elif statement TF elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. We can have any number of elif statements in ‘ur program depending upon our need. However, using elf is optional The elif statement works like an if-else-t ladder statement in C It must be succeeded by an if statement, The syntax ofthe elif statement is given below. if expression 1: 4 # block of statements Next statement Fig. 2.8 Example 1 umber = int(input(“Enter the number>")) if rumber==10: Print(rumber is equals to 10") elif number==50: Print number is equal to 50"): elif number==100; print(*number is equal to 100"): else: Print(‘number is not equal to 10, 50 or 100"), Output : Enter the number?15 number is not equal to 10, 50 or 100 Example 2 ‘marks = int(input("Enter the marks? *)) F marks > 85 and marks <= 100; Print('Congrats | you scored grade A .,") lif marks > 60 and marks <= 85: print("You scored grade B lif marks > 40 and marks <= 60: | print("You scored grade 8 ..") ‘A repetition statement is used to repeat ag \cnming instructions. n Python, two loops/repetitve statements: 1. for loop 2. while loop : 1. for loop: A for loop is used to iterate g that is either a list, tuple, dictionary, execute a set of statements once for: tuple, or dictionary. is false Fig. 29 2. while loop: In Python, while loops are @ block of statements repeatedly unt Condition is satisfied. Then, the expression again and, if itis still true, the body is exe This continues until the expression becomes f Why we u The loopin ones. Iten instead of repeat the example, then, inst print insid Advantag There are = Itpro + Using again = Using struct There PrTHON PROGRAMING (OBATU? e toms me Oe ee es te cy to execs a ge is cheat ted agit false mes. For ite number of t Advantages of loops | There are the following advantages of loops in Pythor * Ktprovides code re-usabilty eens 4| * Using loops, we do not need to write the sa again ar * Using loops, we can travers structures the elements of data There are the following loop statemen n Python Table 2.11 Loop Statement Donation 2 foraop | The fo iop is used in the case where we need loerecte sme par of the cade unl he given | | ‘ondlion i satisfied. The fr lop is aio caled | 8 persed loop. tis bai to use for fop he nano iteration i tronn in advan The while 1op isto be used in the scenario hare we dort know the number of erations in ‘évance, The block of statements is executed {nthe while loop untl the condition specified in the while loop i sae. is aso called a pre- teste -* ‘onal a gen ne do-whte loop eantrne ron sn It a el post aed to I's used when ts necenary execute the op at ast once (mosty menu driven (ON FOR LOOP ed to erate the statements oF eral times tis frequently used to like list tuple, or dictionary in python is given below. for iterating_var in sequence: statement(s) ters oft in the Example 1: iterating string using for loop str = “Python for iin str: print(i) Output x= ifs elif else pr Ife * The step size is used to skip the s 45 50s Example 4: Program to print the sum of the given list. list = (10,30,23,43,65,12) sum =0 for jin list: ‘sum = sumsi Print("The sum is:',sum) Output: The sum is: 183 For loop Using range() function The range() function The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is given below, Syntax: rrange(start,stop step size) * The start represents the beginning of the iteration, * The stop represents thatthe oop will iterate til stop-1, The range(1,5) will generate numbers 1 to 4 iterations Itis optional cific numbers from the iteration. It is optional to use. By default, the step size is 1. Itis optional. Consider the following examples: Example 1: Program to print numbers in sequence, 0123456789 it: ait number 10 jo*1=10 10*2= 20 10*3 = 30 10*4=40 10*5 = 50 10*6 = 60 10*7=70 10*8 = 80 10*9=90 10* 10 = 100 Example 3: Program to print even in range() a n= int(input(Enter the for iin range(2,n,2): print(i) Output: Enter the number 20 2 4 6 8 10 R Nested for loop in python _ python allows us to nest any number ot For. ha ine loop Is eecuted 8 PURER pe eration ofthe outer lop, The ymax oops inside @ of times for below. F seating_varin sequence: outer oP Hor iterating_var? in sequence: #inner loop. fblock of statements ‘statements Example 3: Nested for looP User input for number of rows 7) ows = int(input(’Enter the rows") | eee a for loop completely exhausted, since there is no break: iin range(0: ely exhausted, since there is no break. ie os ime ep wil pit ruber of Ate eee age for i in range(0.5): The for loop complete print(*end print(i) break: else:print("for loop is exhausted"); ) print(’The loop is broken due to break statement...came cout of the loop") In the above example, the loop is broken due to the break statement; therefore, the else statement will not be executed. The statement present immediate next to else block will be executed Output : o The loop is broken due to the break statement..came out of the loop. while break + The Python while loop allows a part of the code t executed until the given condition returns false: also known as a pre-tested loop. ~ saute It can be viewed as a repeating if st don't know the number of iterations then th loop is most effective to use. The syntax is given below. Output: Enter the rows 55555, Using else statement with for loop Unlike other languages ike C, C++, or Java, Python allows ‘must notice that if the loop contains tement then theese statement not be suertens ot be executed. (2) Continue Statement - is encountered, the conti the loop. Let's understan: Example: When the continue statement rol transfer to the beginning of d the following example, # prints all letters except ‘a’ and 't' i=0 ‘Str = ‘pythonpoint' while i< len(strt): if strifi} == ‘a’ or strtfi) it continue Print(‘Current Letter ;', afi) jet Output : Current Letter :j Current Letter : y Current Letter : p Current Letter : 0 Current Letter : Current Letter: n ie ‘break Output : Example: while i In the above example, we have created the lists which Consist of the employee and department details and vrinted the corresponding details. Observe the above code to understand the concept of the list better. Operations (2) List indexing and splitting © The g is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [}. The index starts from 0 and goes to length - 1. The first element of the list is stored at the Oth index the second element of the list is stored at the 1st index, ind and so on. 0 1 List(o] = 0 List{0:] = List(1 Listf] = 10.1.2.3.4,5] Listi2}= 2 List(2s4] = [2.3] Listig] = 3 List{1:3) = [1.2] List{a] = 4 List(5) = 5 ae SHATNER +) The star denotes the starting index posit ‘+The stop denotes the last index position + The step is used to skip the nth ele startstop Consider the following example: list = 11.2, of the list Print(ist{3}) # Slicing the elements Print(list[0:6}) ‘# By default the index ‘an get the sub-lst of the lst using the folowing We can ion of the list Ment within a (220) 5 B45) 02.3.4) 84) ‘As we discussed above, we can get an Using negative indexing. In the above print statement returned the rightmost list. The second print statement returned and so on. (b) Updating List values * Lists are the most versatile data structures since they are mutable, and their values updated by using the slice and assignment op + Prthon also provides append) and insert Oth element end een te #0 s0its start from te |” Can be used to add values to thelist ¢lement and go for index -1 : Consider the following example to update the value pemrtstD thelist. premiere) list = 1, 2, 3,4, 5/6] 7" Print(list[is6:2)) Output : her languages, Py to use the negative indexin, thon provides the flexibility 19 also. The negative indices fae coed from: the’ right The’ tast’"elamert (ahtmost) ofthe list has the index -1: is adjacent left clement is present at the index -2 and so on until the left-most elements are encountered, Fema 4g gd CEEPETE 65 4 ~1— Backward direction ere we will the list Let's have a look at the following example whe use negative indexing to access the elements of list = (12,345) print(list[-1]) print(list[-3:]) print(list{:-1)) print(list[-3:-1]) print(list) Print(lst) # Adding multiple-element list {3} = 89, 78) print(list) # Tt will add value at the end of 1 listl-1]= 25 Print(list) Output: 11,2,3,4,5,6) (1, 2, 10,4, 5,6] 1, 89, 78, 4,5, 6) (1, 89, 78, 4, 5,25) The list elements can also be deleted by keyword, Python also provides us the if we do not know which element is to b the lis. : Consider the following example to delete thel list = (1, 2, 3, 4)5)6y print(list) a : 1.2345 2,104, 0, 89, 78, 4 (2, 89, 78,4 Python Lis © The work i strings Let's see he Consider a perform of 1,210.45.6) (189,784.56) (89,784 5,251 python List Operations strings. Let's see how the list Consider a lists 11 = [1, 2, 3, 4], and [2 = The concatenation (+) and work in the same way as th perform operation. Table 2.12 sey were working with the ‘esponds to various operators. repetition (*) operators 5 67, 8) to Operator Description Example Repetition The repetition ‘operator enables thelist elements to be repeated multiple tines. L42=[1,2,3,4,1,2,3,4) Concatenation Itconcatenaes the list mentioned on either side ofthe operator. He2=[1,2,3,4,5,6,7,8] Membership At retums tue ia pertalar item xsi ina paricular list otherise false Print2in I) prints True, eration The for loop is used to terate over the list elements foriinit Print) Output 1 23) “TYPES, OPERATORS AND (©) Rerating a List A be iterated by using a for containing four strings, which can be iterated as follows. list = "ohn", "David", "Tames", "Tona for iin i # The i variable will iterate List and contains each element i print(i) Output: John David James Jonathan (d) Adding elements to the list «Python provides append() function which is Used! to ‘add an element to the list. However, the append) function can only add value to the end of the list. Consider the following example in which, we are taking the elements of the list from the user and printing the: list on the console. ‘#Declaring the empty list I=) #Number of elements will be entered by the user n= int(input("Enter the number of elements in the lists")) # for loop to take the input for i in range(O,n): ; +# The input is taken from the user and added to the list as the item i \append(input("Enter the item:!)) i print("printing the list items") # traversal loop to print the list for i in|: ae Enter the number of elements in the list5 Enter the item:25 hel , Enter the item:46 Enter the item:12_ from the list joving elements eRe ObaG UNTeete0 eter ich wuses remove the element from the list. Consider the following example to understand this concept Example : list.remove(2) Brint("Anprinting the list after the removal of first element..." Printing original list: 01234 Printing the list after the removal 0134 Python List Built-in functions * Python provides the followin can be used with the lists, Table 2.13 of first element, 19 built-in functions, which Example Cmpist,ist2) | iteompares the | This method s not elements of both | used inthe Python 3 thelist. | and the above | versions len(ist) Itis used to caloulate the length of thelist Itretums the 1=[1,2,3.456,7.8] | nen) 8 t max(ist) maximum 112,34,26,48,72) element ofthe | print(max(L1)) list. 72 [4 min(lst) | itretuns the l= minimum element | [12,34,26 48,72) ofthe lis Print(min(L) 12 5 | listseq) | ttconverts any | str= *Johnson* sequence fo the | ¢= lists) list print(type(s)) (2.22) ‘TYPES, OPERAT Let's have a look at the few list exarnph Example 1: Write the program to element of the lst. é| + Oe for iinlistt: if {not in ist2: list2.append(i) print(list2) Output: (0, 2,3, 55, 98, 65, 13, 29) Example 2 : Write a program to find the element in the list. listl = (3.459101 247 sum for in listt: Sum = sumsi_ print("The sum is:",sum) Output: The sum is: 67 Example 3 : Write the program to find the lists cons at least one common element. listt = (1.2.3,45,6) list2 = [7.8.9,2,10) for x in list: for y in list2: ifx=zy: print('The common element Output : The common element is: 2 (d) Slicing * Python sliced function is used to. get elements from the collection of provides two overloaded slice get first two elements from the | slice can be used, The signature given below. Bs | parameters rant: Starting index of slicing stop’ End index of the slice sep: The number of steps fo JUmP- Return + Iereturns asic object Lets see some exemple understand it’s functionality py sice() Function Exomle 1 # Python slice) function example +# Calling function | cenit sce) # returns 5 1) pesutt2 = slice(0,5,3) # refurt # Displaying result peint(resuit) prin(cesult2) ‘Output slceyNone, 5, None) sicel0,5, 3) Python sliceQ Function Example 2 # Python dlice() function example | # Calling function ! -Javatpoint* slic = sice(010,3) # returns slice object sic2 = sice(-10-3) # returns slice object | # We canuse this slice object to get elements | str2= strifsic] str3 = strifsic2] # returns elements in reverse order | Displaying result | print(str2) print(str3) Output : Jaot p= Python slice() Function Example 3 # Python slice() function example # Calling function ‘Tup = (45,68,955,1214 41,558 636,66) slic slice(0,10,3) # returns slice object ee lice(-1,0-3) # returns slice object fecan use this slice object to get elements ae ‘S103 = tuplslic2] # returns elements in reverse order of sliced function *° ice object ns slice object +# Displaying result print(str2) print(str3) output (as, 1214, 636) (65, 41, 68) python sliced Function Example 4 python slice() function exemple # Calling function tup + 45,68,958,1214 41,950,636 66) ie = slige(0.10,3) # returns slice oBlest lie? = tup[0:10:3] # fetch the some elements ie we can use this slice object to Sek elias str2 = tuptslic] # Displaying result print(str2) print(slic2) important aspect of an n be defined as the organized can be called whenever block of reusable code, whi required. ython allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by (A function can be called multiple times to provide reusability and modularity to the Python program. + The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized. + Python provide us various inbuilt funetions like range or print). Although, the user can create its functions, which can be called user-defined functions; © 7 There are mainly two types of functions. % 1, User-define functions - The user-defined «pen tutorial we wl discuss the user define functions Advantage of Functions in Python There are the following advantages of Python functions + Using functions, we can avoid rewriting the same Jogie/code again and again ina program, + We can call Python functions multiple times in a program and anywhere in program, ‘+ We can track a large Python program easily when ite | divided into multiple functions, Reusability is the main achievement of Python functions. * However, Function calling is always overhead in a Python program, 2.7.1 Creating a Function Python provides the def Keyword to define the function The syntax of the define function is given below. Syntax: ef imy_Finction(parameters): function_block return expression Let's understand the syntax of functions definition. * The def keyword, along with the function name is used to define the function, * The identifier rule must follow the function name. * A function accepts the parameter (argument), and they can be optional * The function block is started with the colon (), and block statements must be at the same indentation. * The return statement is used to return the value. A function can have only one return 2.7.2 Function Calling * An Python, after the function is created, we can call it from another function. A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses, Consider the following example of a simple example that prints the message "Hello World #function definition def hello_world(): print(‘hello world") # function calling hello_world() Dutput : ello world 224) ‘The return statement The return statement is used at the e ‘and returns the result of the function. function execution and transfers the function is called, The return statement ca ‘outside of the function. Syntax. return fexpression jist] It can contain the expression which gets value is returned to the caller function, statement has no expression or does not the function then it returns the None object, Consider the following example: Example 1 # Defining function’ def sum(): a=10 b=20 Fab ‘return € # calling sum() function in print statement print(*The sum is:",sum0) ij Output: The sum is: 30 + In the above code, we have defined # by the return statement to the caller function, Example 2 : Creating function without retumn stater # Defining function def sum(): a=10 b=20 c= orb. ieee # calling sum() print(sumQ) ‘s Output : None * In the above code, we have defined the without the return statement as sum() function returned the Not ‘Arguments in Function. 1 of infor gumen ss any fe them with & 273 The arguments are tyP' the function. The 2 theses, We can Pas: t be separat passed into in the paren arguments, but they must comma. Consider the following example. whe thot accepts a string as the argument Example 1 ‘defining the funtion def func (name): print(“Hi*name) ‘ealing the function fune(Devansh") Output: Hi Devansh example 2 function to calcul ‘#defining the Function def sum (2.0): return arb; Jr contains a function late the sum of two variables ‘#toking values from ‘the user b= int(input (Enter @:)) be int(input(*Enter b:")) Nt) ritng the sum ofa and b red) mt’Sum =" sun(a)) Output: enter 10 Enter b: 20 ‘Sum = 30 Call by reference in Python * In Python, call by reference means passing the actual value as an argument in the function. All the functions are called by reference, ie, all the changes made to the reference inside the function revert back to the ‘original value referred by the reference. Example 1 : Passing Immutable Object (List) ‘#defining the function #calling the function change_list(list!) print(list outside function = ‘output: list inside function side function = assing Muti 11 = (10, 30, 40, 50, 20, 30) {10, 30, 40, 50, 20, 301 list outs jable Object (String) Example #defining the function def change_string (str): " Hows you" strestrt eg ¢ string inside function :" str) print( "printing th stringi = "Hi Zam there” #calling the function change_string(string!) print(printing the string outside function * string!) Output : printing the string inside function ; Hi am there Hows you printing the string outside function : Hil am there: Types of Arguments There may be several types of arguments which can be passed at the time of function call 1. Required arguments 2. Keyword arguments 3. Default arguments 4, Variable-length arguments 1. Required Arguments Python. However, time of the function call. As far as the arguments are concemed, these are the which are required to be passed at the calling with the exaet match of their pasitio ef change_list(listt): ee re Print(list inside function = "listl) ‘ebuton thie function call and function definition. If ‘argument: 'b’ 2. Default Arguments Enter the name: John Hi John Example 2 return (p*t*r)/100 P= Float(input(“Enter the Principle amount? *)) = float(input("Enter the rate of interest? ")) Enter the principle amount: 5000 Enter the rate of interest: § Enter the time in years: 3 Simple Interest: 750.0 Example 3 #the function calculate ‘arguments a and b def calculate(a,b): return arb calculate(10) # this causes required arguments b. Output: Typetrror: calculate ‘eturns the sum of two an error as we are missing a missing 1 required positional Python allows us to initialize the arguments at the function definition. Ifthe value of any of the arguments '5 not provided at the time of function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call. ‘My name is john and age is 22 My name is David and age is 10 3. Variable-length Arguments (‘args) * In large projects, sometimes we may not umber of arguments to be passed in advance. j Cases, Python provides us the flexibility to 9 comma-separated values which are internall 2s tuples at the function call. By using the length arguments, we can pass any nur nl arguments, However, at the function definition, we d Warible-length argument using the *args ( *. Consider the following example, Example def printme(*names): Bioeet Print('type of passed argument i Print("printing the passed for name in names: rint(name) a Printme(*john""David® smith ticks) Output : ‘type of passed argument is ill cause an error since a local his TYPES, 0 Creating a tuple ad ion | A tuple can be writen as the collect separated () values enclosed with the small ¢ parentheses are optional but it is good Pn with the two types brint(type(T3)) Output : Note: The tuple which is created Parentheses js also known as tuple packing. * Creating @ tuple with single element is different. We will need to put comma after the el to declare the tuple. tup! = ("JavaTpoint") Print(type(tupi)) Output: A tuple is indexed in the same way as the items in the tuple can be accessed by specific index value. Consider the following example of tuple; Example 1: tuplet = (10, 20, 30) 40 print(tuplet) count = 0 (10, 20, 30, 40, 50, 60) ‘ple Ca tuple cannot be changed. hiple.cannol.be changed) °si=- aerate) tuplen(aj =20 sah ck ig PYTHON PROGRAMMING (BATU) tuplel[2] = 30 > wupletl3) ‘upledfa) = 50 tuplen(S} = 60 inpitC*Enter the tuple elements »")) F ple index out of range a the above code, the tuple has 7 elements which Re 6. We tried to access an element outside , denote 0 to (%d} = %es"e(count, i)) of tuple that raised an IndexError. aed count = counted fuple = (12,345.67) ep re Output: #element 1 to end eer : ae mtr the tuple elements 123456 ieee 1, 2,314, 5,8) #element 0 to 3 element 4 tuplel(0] = 2 print(tuplef:4]) t Using) UPI = 2 #element 1 to 4 element m0) ple = 3 print(tuplef1:51) slightly # element 0 to 6 and take step of 2 element print(tuple[0:6:2]) Output: Tuple Indexing and Slicing fe A Bae The indexing and slicing inthe tuple are similar to list. aS The indexing and slicing ple are page The indexing in the tuple starts from 0 and goes to lengthtupl) -1 .2:3,4) +The items in the tuple can be accessed by using the | 1, 3,5) index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple. ND ht tele Consider the following image to understand the indexing | * The tuple element can also access by using negative 2.8.2 Negative Indexing and slicing in detail indexing. The index of -1 denotes the rightmost Tuple = (0,1.2.34.5) element and -2 to the second last item and so on, ther} [Co [7 2 3 4 e * The elements from left to right are traversed using the _ negative indexing. Consider the following example: Tuple(O]=0. Tuple(0} = (0,1,2:34,5) tuplel = (1, 2,3, 4, 5) a Tule] Pec “is print(tuplei[-1)) print(tuple1{-4)) print(tuplei-3:-1) y print(tuplet(-1)) Tilt=4 Tata (0129) print(tuplei(-2)) Output : Tuplels}= 5 5 a Consider the following example: 2 : sath 4) ,2,3,4) 45) (0.1.2, Tuplel2]=2 _ Tuple(2:4] = (2,3) Tuple]=3° Type) = lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable. To delete an entire tuple, we can use the del keyword with the tuple nam Consider the following example, 1,2, 3,4,5,6) Output: 2,345.6) Traceback (most recent call last: File “tuple.py’, line 4, in print(tuple1) Name€rror: name ‘tuplel' is not defined Basic Tuple operations The operators like concatenation (+), repetition (+, Membership (in) works in the same way as they work with the list. Consider the following table for more detail Let's say Tuple t = (1, 2,3, 4, 5) and Tuple tl = (6, 7, 8 9) are declared. Table 2.14 Operator Description Repetion | The repetition operator enables the tuple elements to be repeated multiple times, Itconcatenates the tuple mentioned on either side of the operator. Itretums true ifa Particular item exists in the tuple otherwise false The for loop is used toiterate over the tuple elements, Example ] TH2=(1,2.3,4,5, 1,2, 34,5) ‘Concatenation |TH12=(1,2.3,4,5.6 | 7.8.9) Membership print (2 in TA) prints True, Iteration foriin Tt print) Output : a len(T1)=5 Length itis used to get the Python Tuple inbuilt functions Table 2.15 Using 2 Ty [a01, " Wo, | + | emp(tuplet, tuple2) 2 | Nen(tuple) 3 | max(upe) Itretums the maximum the tuple 4 | min(tuple) Itreturns the minimum, tuple. 5 | tuple(seq) Itconverts the specified: the tuple. Where use tuple? 1. Using tuple instead of list gives us a cleat i the following nested structure, which can be usee dictionary. tuple instead of ist is used in the following se ple can simulate a dictionary without keys. Ca "John", 22), (102, "Mike 28), (103, "Dustin", 30 length of the tuple. st vs. Tuple Table 2:16 Sr List : No. 1._| The literal syntax oflistis | The literal syntax shown by the [) is shown by the 2_| The Listis mutable The tuple is immutab 3_| The Listhas the a variable length length. 4 | The list provides more ‘The tuple provid functionality than a tuple. i 5 | The lists used in the The tuple is scenario in which we need to | cases where store the simple collections _| store the read with no constraints where the | colections value of the items can be the items changed. changed, the key ir 6 | The ists ae ess memory efficent than a tuple, jered items. the collection of the unord immutable, | + APython set is st must be unique, ach element in the se and the sets remove the dU mutable which means we ¢2r creation. ‘+ Unlike other coll attached to the elements Girectly access any element of th fer, we can print them all together of the set, hes Howev the listof el The set can be creat immutable items with the ¢ provides the set method, which can Ps fet by the passed sequence Example 4: Using curly braces : Monday’. "Tuesday", “Wednesday”. rrhursday*,*Friday’, "Saturday", “Sunday") e used to create the for | ‘we cannot | loopini etter by the index | Friday ror we can 9et | wednesday lements by looping through the set ts by looping through the ervey 29.1 Creating a Set saturday ed by encosing the comma-seP2"ated | Monday rly braces). Python also surly braces (. Pyt qessy sunday of element such as integer, # Creating a set which hav 1g through the set elements it can contain any *yPe ote, But mutable elements (ist, dictionary, of set. Consider the following float, tuple set) can't be a member example. ¢ immutable elements print(Days) print(type(Days)) rClaning through te set elements") sett = (12.3, "JavaTpoint”, 20.5, 14) fori in Days: print(type(set1)) pein) #Creating a set which have mutable element Output: set2 = (1.2.3 ["Javatpoint’ 4D) 359M print(type(set2)) 639 Output : History of Java {Friday, ‘Tuesday, ‘Monday’, ‘Saturday’, ‘Thursday’ Traceback (most recent call last) ‘Sunday, Wednesday’) < with the sets by using which we can ccheck whether a set is to other set The boolean true or false is returned depending upon the items present inside the sets. a subset, superset, or equivalent P Consider the following example. Dayst = ("Monday “Tuesday”, Wednesday", *Thursday"} Days2 = {"Monday”, "Tuesday") Days3 = ("Monday", "Tuesday", "Friday") #Dayst is the superset of true. print (Dayst»Days2) Days2 hence it will print | Fi At Hprints false since Days! is not the subset of Days2 print (Dayst Traceback (most recent call last): Frozenset.add(6) #gives an error since we Content of Frozenset after creation Frozenset for the dictionary aaa Example 2: Pe seti = set(] net cutee Example 3 rinting the content of frozen set. ile "set py’, line 6, in tributeError: rozenset’ object has no IF we pass the dictionary as the seque frozenset() method, it will take only the! dictionary and Teturns a frozenset of the dictionary as its elements, ny) aan “TYPES, OPERATORS AND EXPRESSIONS, [PROGRAMMING (DBA eS PYTHON PROG! ‘output: Consider the folowing example aes | (eats Diconary = CNemeN'Tohnt, "COUMIYTUSAS | er. wyite the program to add element to the poHnon frozenset. Ban Greer sot will | sett = (23445667 9045,"Javatpeint') Fratanset = frozensen(leionay) #7F02 get2 = (13:28,56,76,"Sochin") ee etd = setLintersection(set2) rtrpetProzenset)) print(set3) fori Frozenset: ee 2% Piimeror trozenset’ object does not support item eae se frozensets are eee, + Above code raed an vor becuse fez roca ees amutable and can't be changed after ci county set ae issubset an D f= ‘et Programming Example sett: Peri n set. | ample 1: Write a program to remove the given number | set((Pete chy "Dona fromthe set | set2 =set(t"camroon’ Washington" Peter"D) : set =(12,3,4,5,6,12.24) set3 = set({"Peter"}) Pimnpur'Enter the number you want Yo remove")) msetiscard(o) issubset = seti>= set2 print*AFter Removing" my_set) print(isubéet) cae, owe issuperset = setl <= set2 Enter the number you want to remove:l2 After Removing: {1, 2, 3, 4, 5, 6, 24) Example 2: Wie @ program to add multiple elements to the set. Setl = set([1,2,4"John","CS"]) ninfliesuberset dethapdetel Ape Mere Srpee) tiuleaestasth | Prnicety sau | print(issuperset) issubset = set < set2 print(issubset) issuperset = set2 >= set3 False Output i Pl False {1,24 ‘Apple’ ‘John’ 'CS', Mango, Grapes’) Example 3: Write 2 program to find the union between | \U° True Seth = Set({'Peter" Joseph", 65 59,96)) Pylon ulin sot aia ised with the Lee rnimisr ae Python contains the following methods to be used witht s2f9 = set! nion(set2) a 5 Table 2.37 get) output. {96,65,2, Joseph, 1, Peter, 59) = eons 1 | edo) tea # prowam to fd the intersect between two sets. oa Set] = (23,44,5667,90 45, 'Javatpoint") se12 = (13,23,56,76 "Sact ‘$13 = set! intersection(set2) Print(set3) ofthese Itmodifis this set by Femovng all he items ‘hat ar aso presentin the specitog sos fates a! ‘ttetums a shatow copy 6 | update) Itremoves the specified itm from the st returns @ new sot that contains oly the | common lomens of both the sets, al the ses ifmore than two are specified 7 | intersection update...) | Itremoves the tems ftom i | | teopelseitae rsneent nine | sn (olthe set ne juno | hencne specie, | 8 | tsdisioin..) | Return True iftwo sets | have a nullintersecton | Report whether an contains this [2 essary fee | 10 | issuperset ) | her pond) rbtary set element that | i the lest element of the lal | set Ralses KeyErorif | tesetisempty. | 12 | remove(item) | Remove an element from | | aset it mstbe a | member. Ifthe element is | nota member, raise a KeyEror. symmetio_ditference..) Remove an element from a setyit must bea member. Ifthe element is hot amember, raise a KeyEnor Update a set with the symmettic difference of itself and another, [2.11 DICTIONARIES ‘© Python Dictionary is used to store the data vvalue pair format. The dictionary is the data. Python, which can simulate the realife: arrangement where some specific value exists fg particular key. It is the mutable data-str dictionary is defined into element Keys and. Keys must be a single element Value can be any type such as lis, tuple, integer In other words, we can say that a dictionary’ collection of key-value pairs where the value e ‘any Python object. In contrast, the keys immutable Python object, ie, Numbers, tuple 2.11.1 Creating the Dictionary The dictionary can be created by using multiple value pairs enclosed with the curly brackets {}, each key is separated fom its value by the colon syntax to define the dictionary fe given below Syntax ai 753 ‘Java Try Catch Dict = (’Name: "Tom", "Age": 22} % In the above dictionary Dict, The keys Name and the string that is an immutable object. Let's see an: to create a dictionary and print its content. Employee *salary":25000,'Co print(type(Employee)) print("printing Employ Output : Printing Employee data {Name’: ‘John’, ‘Age! 'GOOGLE) Create Die savas a3 Dictionan (2: "Devar 241.2 | We have and tuple However Using the The dict pyTHON PROGRAMMING (BATU) ins hinenonatewor Tete python provides the built ret which is also used to create dictionary. braces 0 is used to create empty diction2 # Creating an empty Dictionary pict =O print Empty Dictionary print(Dict) NY Bete cocimer y= | gewith dict method 4 in| picts det ‘Teva 2:7, 3:Peint )) ta | print("\nGreate Dictionary by using dict0:") | print) | creating a Dictionary | HwitheachitemasaPoir n fe | Dict dent, *Devansh’), (2, Sharma'))) ve | print\nbietionary with each item as a pair’ ") ne | _rint(Diet) or Output | Empty Dictionary: s o y-| id | Greate Dictionary by using dit: 1€ {Java', 2:'T, 3:'Point'} Dictionary with each iter as a par: {1Devansh’, 2:'Sharma} 2.11.2 Accessing the Dictionary Values We have discussed how the data can be accessed in the list and tuple by using the indexing 2 | However, the values can be accessed in the dictionary by 2 | using the keys as keys are unique in the dictionary. The dictionary values can be accessed in the following way. / Employee = ['Name": "John", “Age's 29, 'salary":25000,"Company":"GOOGLE") Print(type(Employee)) | Print("printing Employee data.....") Print(’Name : Yas" Employeet*Name"]) print(“Age : Yd Employee(" Age") Print(*Salary: Yad” %Employee[ salary") brint(*Company : %s" %Employee["Company"]) Output : (239) printing Employee data Name: John Age :29 Salary : 25000 pany ;GOOGLE com des usw an aenntve oust 0 aod to access the dictionary values, t would Traome result as given by the indexing 2.11.3 Adding Dictionary Values 2:17 gicionary is» routable data type, and IS VSHiGs veated by using the specific Keys. The vale

You might also like