Boolean operator A variable of Boolean type can

Boolean operator • A variable of Boolean type can have one of the two values- True or False. • Similar to other variables, the Boolean variables are also created while we assign a value to them or when we use a relational operator on them.

Boolean operator >>boolean_var = True >>print(boolean_var) True >>20==30 False >> 20!=20 False >>”Python”==“Python 3. 4” False >> 90<=90 True >> 87 == 87. 0 Flase >> 30 >30. 0 False >> 87>=87. 0 True >>”Python”==“Python” True >> 30 > 50 Flase >> 30>50 False >> 87<=87. 0 True

Arithmetic Operators if a=100 and b=200 Operators + (addition) - (subtraction) * (multiplication) / (division) % (modulus) // (floor division) ** (exponent) Example Output print(a+b) 300 Print(a-b) -100 print(a*b) 20000 print(a/b) 2. 0 print(a%b) 0 print(12//5) print(12. 0//5. 0) Print(-19. 5//5) Print(-20. 0//3) 2 2. 0 -4 -7. 0 print(a**b) 100200

Comparison Operators if a=100 and b=200 Operators Example Output == print(a==b) False != Print(a!=b) True > print(a>b) < print(a<b) >= print(a>=b) False <= print(a<=b) True False True

Unary Operators • Unary operators act on single operands. • Python supports unary minus operator. • When an operand is preceded by a minus sign, the unary operator negates its value. • For example, if a number is positive, it becomes negative when preceded with a unary minus operator. Similarly, if the number is negative, it becomes positive after applying the unary minus operator. • b = 10 • a = -(b)

Bitwise Operator AND OR XOR NOT A B A&B A B A|B A B A^B A !A 0 0 0 0 0 1 1 1 0 0 1 1 1 1 1 0

Shift Operators • Python supports two bitwise shift operators. • They are shift left (<<) and shift right (>>). • These operations are used to shift bits to the left or to the right. • X=0001 1101 • X<<1 gives result • 0011 1010 • If we have X=0001 1101 • X>>1 gives the result as • 0000 1110

Logical Operators • LOGICAL OPERATORS: is used to simultaneously evaluate two conditions or expressions with relational operators. • Logical AND (&&) operator If expressions on both the sides (left and right side) of the logical operator are true, then the whole expression is true. • Example: If we have an expression (a>b) && (b>c), then the whole expression is true only if both expressions are true. • Logical OR (||) operator If one or both the expressions of the logical operator is true, then the whole expression is true.

Logical Operators • For example, If we have an expression (a>b) || (b>c), then the whole expression is true if either b is greater than a or b is greater than c. • Logical not (!) operator takes a single expression and negates the value of the expression. It just reverses the value of the expression. • For example, a = 10, b = !a; Now, the value of b = 0. Therefore, !a = 0. The value of !a is assigned to b, hence, the result

Membership Operator Python supports two types of membership operators–in and not in. These operators, test for membership in a sequence such as strings, lists, or tuples. in Operator: The operator returns true if a variable is found in the specified sequence and false otherwise. For example, a in nums returns 1, if a is a member of nums. not in Operator: The operator returns true if a variable is not found in the specified sequence and false otherwise. For example, a not in nums returns 1, if a is not a member of nums.

Identity Operator • is Operator: Returns true if operands or values on both sides of the operator point to the same object and false otherwise. • For example, if a is b returns 1, if id(a) is same as id(b). • is not Operator: Returns true if operands or values on both sides of the operator does not point to the same object and false otherwise. • For example, if a is not b returns 1, if id(a) is not same as id(b).

Control Statements • A control statement is a statement that determines the control flow of a set of instructions, i. e. , it decides the sequence in which the instructions in a program are to be executed. • Types of Control Statements • Sequential Control: A Python program is executed sequentially from the first line of the program to its last line. • Selection Control: To execute only a selected set of statements. • Iterative Control: To execute a set of statements repeatedly.

If Statement Syntax: if test expression: Statement 1 ……. . Statement n Statement X Test expressio n true Statement block Statement x false

If Statement Example: x=10 # initialize if (x>0): #test expression x=x+1 #increment if x >0 print(x) #print the value of x Output: X=11

If-Else Statement if test expression: Statement block 1 else : Statement block 2 Statement X Statement block 1 Statement block 2 Statement X

If-Else Statement Example: age=int(input(“Enter the age : ”)) if(age>=18): print(“you are eligible to vote”) else: yrs=18 -age print(“you have to wait for” + str(yrs) + “to caste your vote”); Output: Enter the age: 10 You have to wait for 8 yrs to caste vote

Nested if Statements • A statement that contains other statements is called a compound statement. • To perform more complex checks, if statements can be nested, that is, can be placed one inside the other. • In such a case, the inner if statement is the statement part of the outer one. • Nested if statements are used to check if more than one conditions are satisfied.

Nested if statements-Example num=int(input(“Enter any number from 0 -30: “)) if(num>=0 and num<10): print(“It is in the range 0 -10”) elif(num>=10 and num<20): print(“It is in the range 10 -20”) elif(num>=20 and num<30): print(“It is in the range 20 -30”) OUTPUT Enter any number from 0 -30: 25 It is in the range 20 -30

if-else Statement • Python supports if-else statements to test additional conditions apart from the initial test expression. • The if-else construct works in the same way as a usual ifelse statement. • If-elif-else construct is also known as nested-if construct.

if-else statement-Example num=int(input(“Enter any number: “)) If(num==0): Print(“The value is equal to zero”) elif(num>0) Print(“The number is positive”) else Print(“The number is negative”) OUTPUT Enter any number: -10 The number is negative

if-else statement True Test Expression 1 True Statement block 1 False Test Expression 2 False Statement block X Statement block 2 Statement block Y

while loop Syntax of while loop while(condition): statement block statement Y Test expression True Statement block False

while loop Example: i=0 while(i<=10): print(i, end=“ ”) i=i+1 Output: 0 1 2 3 4 5 6 7 8 9 10

For Loop • For loop provides a mechanism to repeat a task until a particular condition is True. • It is usually known as a determinate or definite loop because the programmer knows exactly how many times the loop will repeat. • The for. . . in statement is a looping statement used in Python to iterate over a sequence of objects.

For loop Syntax of for loop: for loop_control_var in sequence: Statement block Flow of statements in for loop: Specify the Range False Range of numbers assigned to the loop control variable Statement block Statement Y True

For Loop and Range() Function • The range() function is a built-in function in Python that is used to iterate over a sequence of numbers. • The syntax of range() is range(beg, end, step) • The range() produces a sequence of numbers starting with beg (inclusive) and ending with one less than the number end. • The step argument is option. By default, every number in the range is incremented by 1 but we can specify a different increment using step. It can be both negative and positive, but not zero.

For loop and Range() function for i in range(1, 5): print(i, end=“ “) Output: Print numbers in the same 1234 line beg for i in range(1, 10, 2): print(i, end=“ “) Output: 13579 step end

Range() function for i in range(10): print(i, end=‘ ’) Output: 0123456789 for i in range(1, 10): print(i, end=‘ ’) Output: 123456789 for i in range(1, 20, 3): print(i, end=‘ ’) Output: 1 4 7 10 13 16 19

Nested Loops • Python allows its users to have nested loops, that is, loops that can be placed inside other loops. • Inner for loop can be used to control the number of times a particular set of statements will be executed. • Another outer loop could be used to control the number of times that a whole loop is repeated. • Loops should be properly indented to identify which statements are contained within each for statement.

Nested Loops Example: for i in range(5): print() for j in range(5): print(“*”, end=‘ ’) Output: ********** *****

The break statement • The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. • The break statement is widely used with for loop and while loop. • When compiler encounters a break statement, the control passes to the statement that follows the loop in which the break statement appears.

The break statement while… ……………. if condition: break ………. Transfer control out of for loop for… …………. . for… ………. if condition : Transfer control out of while loop break for… ………. . …………. . if condition: Transfer control out of inner for break loop ……. ………

The break statement - Example i=1 while i<=10: printf(i, end=“ ”) if i==5: break i=i+1 printf(“n Done”) exit Output: 1 2 3 Done Enter the loop Test expression of loop False True Yes Break? No 4 5 Remaining body of a loop Exit loop

The Continue Statement • Like the break statement, the continue statement can only appear in the body of a loop. • When the compiler encounters a continue statement then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loopcontinuation portion of the nearest enclosing loop.

The Continue Statement while(…. ) ……. if condition: continue …… ………… Transfers control to the condition expression of the while loop for(…. ) ……. if condition: continue …… ……… Transfers control to the condition expression of the for loop

The Continue Statement for(………. . ) ……… for(………. . ) if condition: continue ………………… Transfers control to the condition expression of the inner for loop Example: for i in range(1, 11) if(i==5): continue print(i, end=“ ”) print(“n Done”) Output: 1 2 3 4 6 7 8 9 10 Done

The Pass Statement • Pass statement is used when a statement is required syntactically but no command or code has to be executed. • It specified a null operation or simply No Operation (NOP) statement. • Nothing happens when the pass statement is executed.

The Pass Statement Example • for letter in “HELLO”: pass #The statement is doing nothing print(“Pass: ”, letter) print(“Done”) Output: Pass: H Pass: E Pass: L Pass: O Done

The Pass Statement Pass and Comment Difference between comment and pass statements • In Python programming, pass is a null statement. • The difference between a comment and pass statement is that while the interpreter ignores a comment entirely, pass is not ignored. • Comment is not executed but pass statement is executed but nothing happens.

The Else Statement used with Loops • If the else statement is used with a for loop, the else statement is executed when the loop has completed iterating. • But when used with the while loop, the else statement is executed when the condition becomes false.

The Else Statement used with Loops for letter in “HELLO”: print(letter, end=“ ”) else: print(“Done”) Output: HELLO Done i=1 while(i<0): print(i) i=i-1 else print(i, “is not negative so loop did not executed”) Output: 1 is not negative so loop did not executed

Functions and Modules

Functions § Python enables its programmers to break up a program into segments commonly known as functions § Each of which can be written more or less independently of the others. § Every function in the program is supposed to perform a well-defined task.

Need for Functions • Each function to be written and tested separately. • Understanding, coding and testing multiple separate functions is far easier. • Without the use of any function, then there will be countless lines in the code and maintaining it will be a big mess. • Usage of functions will speeds up program development, by allowing the programmer to concentrate only on the code that he has to write.

Function Declaration and Definition • A function, f that uses another function g, is known as the calling function and g is known as the called function. • The inputs that the function takes are known as arguments/parameters. • When a called function returns some result back to the calling function, it is said to return that result. • The calling function may or may not pass parameters to the called function. If the called function accepts arguments, the calling function will pass parameters, else not.

Contd. . • Function declaration is a declaration statement that identifies a function with its name, a list of arguments that it accepts and the type of data it returns. • Function definition consists of a function header that identifies the function, followed by the body of the function containing the executable code for that function

Function Definition Function blocks starts with the keyword def. • The keyword is followed by the function name and parentheses (( )). • After the parentheses a colon (: ) is placed. • Parameters or arguments that the function accept are placed within parentheses. • The code block within the function is properly indented to form the block code. • A function may have a return[expression] statement (optional). That is, the return statement is optional.

Contd. . We can assign the function name to a variable. Doing this will allow you to call same function using the name of that variable def diff(x, y): return x-y a=20 b=10 operation=diff print(operation(a, b)) OUTPUT: 10 #function to subtract two numbers #function name assigned to a variable #function called using variable name

Function Call • The function call statement invokes the function. • When a function is invoked the program control jumps to the called function to execute the statements that are a part of that function. • Once the called function is executed, the program control passes back to the calling function.

Function Parameters • A function can take parameters (some values that are passed to it) so that the function can manipulate them to produce the desired result. • The variables are defined (initialized) when we call the function and are then passed to the function. • Function name and the number and type of arguments in the function call must be same as that given in the function definition. • If the data type of the argument passed does not matches with that expected in function then an error is generated.

Function Call Function Header Syntax: def fn_name(var 1, vari 2, …) documentation string statement block return [expression] Example: def func(): for I in range(4): print(“Hello World”) func() #function call Function body def func(i): print(“Hello World”, i) func(5+2*3) OUTPUT: Hello World 11 OUTPUT: Hello World

Local Variables • A variable which is defined within a function is local to that function. • A local variable can be accessed from the point of its definition until the end of the function in which it is defined. It exists as long as the function is executing. • Function parameters behave like local variables in the function. • Moreover, whenever we use the assignment operator (=) inside a function, a new local variable is created.

Global Variables • Global variables are those variables which are defined in the main body of the program file. • They are visible throughout the program file.

Local and Global Variables – Eg. num 1=10 #global variable print(“Global variable num 1= “, num 1) def func(num 2): # num 2 is function parameter print(“In Function – Local Variable num 2= “, num 2) num 3 =30 #num 3 is a local variable print(“In Function – Local Variable num 3= “, num 3 ) func(20) #20 is passed as an argument to the function print(“num 1 again= “, num 1) #global variable is being accessed #Error-Local variable can’t be used outside the function in which it is defined Print(“num 3 outside function= “, num 3)

Local and Global Variables – Eg. OUTPUT: Global variable num 1=10 In Function – Local Variable num 2=20 In Function – Local Variable num 3=30 Num 1 again=10 Num 3 outside function= Traceback (most recent call last): File “C: Python 34Try. py”, line 12, in <module> print(“num 3 outside function = “, num 3) Name. Error: name ‘num 3’ is not defined

Using the Global Statement • To define a variable defined inside a function as global, you must use the global statement. • This declares the local or the inner variable of the function to have module scope. OUTPUT: var=”Good” In Function var is -Good def show(): Outside function, var 1 I –Morning global var 1 var is -Good var 1=”Morning” print(“In Function var is- ”, var) show() print(“Ountside function, var 1 is- ”, var 1) #accessible as it is global variable print(“var is- ”, var)
![The Return Statement • The syntax of return statement is, • return [expression] • The Return Statement • The syntax of return statement is, • return [expression] •](http://slidetodoc.com/presentation_image_h/9a4279dcfa06735ff28ef52747bd52d4/image-57.jpg)
The Return Statement • The syntax of return statement is, • return [expression] • The expression is written in brackets because it is optional. If the expression is present, it is evaluated and the resultant value is returned to the calling function. However, if no expression is specified then the function will return None. The return statement is used for two things. • Return a value to the caller • To end and exit a function and go back to its caller

The Return Statement def cube(x): return (x*x*x) num=10 result= cube(num) print(‘Cube of ‘, num, ‘ = ’, result) OUTPUT: Cube of 10=1000

Passing the arguments • Four ways to pass the arguments: – Required Arguments – Keyword Arguments – Variable-length Arguments – Default Arguments Required Arguments • In the required arguments, the arguments are passed to a function in correct positional order. • Also, the number of arguments in the function call should exactly match with the number of arguments specified in the function definition

Required Arguments- Eg. def display(): print “Hello” display(“Hi”) OUTPUT: Type. Error: display() takes No argument(1 given) OUTPUT: Type. Error: display() takes Exactly 1 argument(0 given) def display(str): print str=”Hello” display(str) def display(str): print str display() OUTPUT: Hello

Keyword Arguments In keyword arguments the order (or position) of the arguments can be changed. The values are not assigned to arguments according to their position but based on their name (or keyword). Keyword arguments are beneficial in two cases. • First, if you skip arguments. • Second, if in the function call you change the order of parameters.

Keyword Arguments-Eg. def display (str, int_x, float_y): print(“The string is : ”, str) print(“The integer value is : ”, int_x) print(“The floating point value is : ”, float_y) display(float_y=56789. 045, str=”Hello”, int_x=1234) OUTPUT: The string is: Hello The integer value is: 1234 The floating point value is: 56789. 045

Variable-length Arguments • In some situations, it is not known in advance how many arguments will be passed to a function. • In such cases, Python allows programmers to make function calls with arbitrary (or any) number of arguments. • When we use arbitrary arguments or variable length arguments, then the function definition use an asterisk (*) before the parameter name. Syntax: def functionname([arg 1, arg 2, …. . ]*var_args_tuple): function statements return [expression]

Variable Length Arguments-Eg. Example: def func(name, *fav_subjects): print(“n”, name, ” likes to read “) for subjects in fav_subjects: print(subject) func(“Goransh”, “Mathematics”, ”Android Programming”) func (“Richa”, ”C”, ”Data Structures”, ”Design and Analysis of Algorithm”) func(“Krish”) OUTPUT: Goresh likes to read Matematics Android Programming Richa likes to read C Daa Structures Design and Analysis of Algorithms Krish likes to read

Default Arguments • Python allows users to specify function arguments that can have default values. • This means that a function can be called with fewer arguments than it is defined to have. • That is, if the function accepts three parameters, but function call provides only two arguments, then the third parameter will be assigned the default (already specified) value. • The default value to an argument is provided by using the assignment operator (=). • Users can specify a default value for one or more arguments.

Default Arguments-Eg. def display(name, course=”BTech”): print(“Name : “+name) print(“Course : ”+course) display(course=”BCA”, name= “Arav”) #Keyword Arguments display(name= “Reyansh”) #Default Argument for course OUTPUT Name : Arav Course : BCA Name : Reyansh Course : BTech

Documentation Strings • Docstrings (documentation strings) serve the same purpose as that of comments, as they are designed to explain code. Syntax: def functionname(parameters): “’function_docstring’” function statements return [expression]

Documentation Strings-Eg. Example: def func(): “””The program just prints a message. It will display Hello World!!! “”” print(“Hello World !!!”) # Doc string

Recursive Functions A recursive function is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. def fact(n): if(n==1 or n==0): return 1 OUTPUT: Enter the value of n : 6 The factorial of 6 is 720 else: return n*fact(n-1) n=int(input(“Enter the value of n: ”)) print(“The factorial of”, n, ”is”, fact(n))
- Slides: 69