Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Unit-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

UNIT – II NOTES

OPERATORS:

 Operators are the constructs which can manipulate the value of operands.

 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator
Types of Operators:
Python language supports the following types of operators

1. Arithmetic Operators

2. Comparison (Relational) Operators

3. Assignment Operators

4. Logical Operators

5. Bitwise Operators

6. Membership Operators

7. Identity Operators

Arithmetic operators:

 They are used to perform mathematical operations like addition, subtraction,


multiplication etc. Assume, a=10 and b=5
Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

Comparison (Relational) Operators:

 Comparison operators are used to compare values.

 It either returns True or False according to the condition. Assume, a=10 and b=5

Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators:
Assignment operators are used in Python to assign values to variables.

Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators:

 Logical operators are the and, or, not operators.

Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
Output
x and y is False
x or y is True
not x is False

Bitwise Operators:

 A bitwise operation operates on one or more bit patterns at the level of individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.

 Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are
used.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators

 They are used to check if two values (or variables) are located on the same part of the
memory.

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output
False
True
OPERATOR PRECEDENCE:

 When an expression contains more than one operator, the order of


evaluation depends on the order of operations.

 For mathematical operators, Python follows mathematical convention.


 The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division,
Addition, Subtraction) is a useful way to remember the rules:
 Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 *
(3-1)is 4, and (1+1)**(5-2) is 8.
 You can also use parentheses to make an expression easier to read, as in (minute
*100) / 60, even if it doesn’t change the result.
 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2 is
18, not 36.
 Multiplication and Division have higher precedence than Addition and Subtraction. So
2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).
Example 1:
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10

Example 2:
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15
Example 3:
find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1
Example 4:
a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0
Example 5:
a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1

CONDITIONALS

1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else

1. Conditional (if):

 conditional (if) is used to test a condition, if the condition is true the statements inside if
will be executed.
Syntax:
if(condition 1):
Statement 1
Flowchart:
Example 1: Program to provide flat rs 500, if the purchase amount is greater than 2000.
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
Output
enter your purchase
amount
2500
amount to pay
2000

Example 2: Program to provide bonus mark if the category is sports


m=eval(input(“enter ur mark out of 100”))
c=input(“enter ur categery G/S”)
if(c==”S”):
m=m+5
print(“mark is”,m)
Output
enter ur mark out of 100
85
enter ur categery G/S
S
mark is 90

2.alternative (if-else)

 In the alternative the condition must be true or false.


 In this else statement can be combined with if statement.
 The else statement contains the block of code that executes when the condition is false.
 If the condition is true statements inside the if get executed otherwise else part gets
executed.
 The alternatives are called branches, because they are branches in the flow of execution.
Syntax:

Flowchart:

Example 1: Odd or even number


n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")
Output
enter a number4
even number
Example 2: positive or negative number
n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output
enter a number8
positive number
Example 3:leap year or not
y=eval(input("enter a yaer"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output
enter a yaer2000
leap year

Example 4:greatest of two numbers


a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
if(a>b):
print("greatest:",a)
else:
print("greatest:",b)
Output
enter a value:4
enter b value:7
greatest: 7
Example 5:eligibility for voting
age=eval(input("enter ur age:"))
if(age>=18):
print("you are eligible for vote")
else:
print("you are eligible for vote")
Output
enter ur age:78
you are eligible for vote

Chained conditionals(if-elif-else)

 The elif is short for else if.


 This is used to check more than one condition.
 If the condition1 is False, it checks the condition2 of the elif block. If all the conditions
are False, then the else part is executed.
 Among the several if...elif...else part, only one part is executed according to the
condition.
 The if block can have only one else block. But it can have multiple elif blocks.
 The way to express a computation like that is a chained conditional.

Syntax:

Flowchart:
Example 1: student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output
enter ur mark:78
grade:B

Example 2:traffic light system


colour=input("enter colour of light:")
if(colour=="green"):
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
Output
enter colour of light:green
GO
Example 3:compare two numbers
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Output
enter x value:5
enter y value:7
x is less than y

Example 4:Roots of quadratic equation


a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")
Output
enter a value:1
enter b value:0
enter c value:0
same and real roots

Nested conditionals

 One conditional can also be nested within another.


 Any number of condition can be nested inside one another.
 In this, if the condition is true it checks another if condition1.
 If both the conditions are true statement1 get executed otherwise statement2 get execute.
 If the condition is false statement3 gets executed
Syntax:

Flowchart:
Example 1:greatest of three numbers
a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)

Output
enter the value of a 9
enter the value of a 1
enter the value of a 8
the greatest no is 9

Example 2:positive negative or zero


n=eval(input("enter the value of n:"))
if(n==0):
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
Output
enter the value of n:-9
the number is negative

Inline if-else statements

 Python supports a syntax for writing a restricted version of if-else statements in a single
line.
Example:
num = 2
if num >= 0:
sign = "positive"
else:
sign = "negative"
can be written in a single line as:
sign = "positive" if num >=0 else "negative"
This is suggestive of the general underlying syntax for inline if-else statements:
ITERATION/CONTROL STATEMENTS:
Python has two primitive loop commands:

 while
 for

While loop:
 While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true.
 In while loop, test expression is checked first. The body of the loop isentered only if the
test_expression is True. After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.
 In Python, the body of the while loop is determined through indentation.
 The statements inside the while starts with indentation and the first unindented line marks
the end.

Syntax:

Flowchart

Example 1:program to find sum of n numbers


n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)
Output
enter n
10
55

Example 2:Factorial of a numbers


n=eval(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Output
enter n
5
120

Example 3:Sum of digits of a number


n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum+a
n=n//10
print(sum)
Output
enter a number
123
6
Example 4:Reverse the given number
n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
print(sum)
Output
enter a number
123
321
Example 5:Armstrong number or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not
Armstrong number")
Output
enter a number153
The given number is Armstrong number
Example 6:Palindrome or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
Output
enter a number121
The given no is palindrome
For loop:
for in range:

 We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
 In range function have to define the start, stop and step size as range(start,stop,step size).
step size defaults to 1 if not provided.

Syntax
Flowchart:

For in sequence

 The for loop in Python is used to iterate over a sequence (list, tuple, string).
 Iterating over a sequence is called traversal. Loop continues until we reach the last
element in the sequence.
 The body of for loop is separated from the rest of the code using indentation.

Syntax

Sequence can be a list, strings or tuples


Example 1:print nos divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Output
enter a:30
5
15
25
Example 2: Fibonacci series
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output
Enter the number of terms: 6
Fibonacci Series:
01
1
2
3
5
8
Example 3 :find factors of a number
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
if(n%i==0):
print(i)
Output
enter a number:10
1
2
5
10
Example 4: check the no is prime or not
n=eval(input("enter a number"))
for i in range(2,n):
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
Output
enter a no:7
The num is a prime number.

Example 5:check a number is perfect number or not


n=eval(input("enter a number:"))
sum=0
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")

Output
enter a number:6
the number is perfect number
Example 6:Program to print first n prime numbers
number=int(input("enter no of prime
numbers to be displayed:"))
count=1
n=2
while(count<=number):
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1
Output
enter no of prime numbers to be
displayed:5
2
3
5
7
11
Example 7:Program to print prime numbers in range
lower=eval(input("enter a lower range"))
upper=eval(input("enter a upper range"))
for n in range(lower,upper + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)
Output:
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83
89
97
CONTROL STATEMENTS:

Loop Control Structures:

 break
 continue
 pass

BREAK
 Break statements can alter the flow of a loop.
 It terminates the current
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the loop
completely.

Syntax:
break

Flowchart

Example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
w
e
l
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.

Syntax:
continue

Flowchart

Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e
PASS

 It is used when a statement is required syntactically but you don’t want any code to
execute.
 It is a null statement, nothing happens when it is executed.

Syntax:
pass
break

Example
for i in “welcome”:
if (i == “c”):
pass
print(i)

Output
w
e
l
c
o
m
e
Difference between break and continue
else statement in loops:

else in for loop:



If else statement is used in for loop, the else statement is executed when the loop has
reached the limit.
 The statements inside for loop and statements inside else will also execute.
Example
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
Output
1
2
3
4
5
the number greater than 6

else in while loop:

 If else statement is used within while loop , the else part will be executed when the
condition become false.
 The statements inside for loop and statements inside else will also execute.

Example
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
Output
1
2
3
4
5
the number greater than 5
Looping Techniques
1. In python, looping techniques are used in different sequential holders.

2. The main purpose of using different looping techniques is to iterate over a list, set,
dictionary, or another compatible data type in a convenient and efficient manner.

3. Looping techniques provide great help in a variety of scenarios and in different


competitive programming because it uses specific techniques in the code which has
overall structure maintained by the loop.

4. Looping techniques are helpful for the user in situations where we need to access the
elements one at a time and there is no need to manipulate the structure and sequences of
the data.

5. We may classify Looping techniques in two categories:

1. Based on forms

2. Based on data structure


1. Based on various forms

We have some forms of loop that we can implement based on the nature of the loop and also
depends on the location of condition within the loop body.

a) Infinite loop

 Infinite loop refers to the use of while loop with condition always TRUE

 If there are lines below the while loop, they will be executed after the program has dealt
with the full execution or condition check of the while loop.
Example

while True: # we may write while(1)


get_number = int(input("Give me a number input :"))
print("Okay, so it is :", get_number)
Output
Give me a number input :45
Okay, so it is :45
Give me a number input :56
Okay, so it is :56
Give me a number input :78
Okay, so it is :78
Give me a number input :^CTraceback (most recent call last):
File "/Users/hiteshgarg/IdeaProjects/personal/codingeek/Python/infiniteloop.py", line 3, in
get_number = int(input("Give me a number input :"))
KeyboardInterrupt

b) Condition at the top

 It works like a normal while loop (considering the loop has no break statement) but with
the condition to be checked placed at its top.
# An example for while loop
count = 0
while(count <= 6):
count = count + 1
print("Hello", count)

Output
Hello1
Hello2
Hello3
Hello4
Hello5
Hello6

c) Condition at the bottom

 Just like do while loop in other programming languages like C or Java, it ensures the
statement inside the loop runs at least one time. It has the condition to check at the
bottom of the loop.

Example

while(1):
age = input("Tell me your age ")
print("Your age is :", age)
restart = input("Should I ask you again?(Y/N) ")
if restart == "N":
break
Output
Tell me your age 10
Your age is :10
Should I ask you again?(Y/N) Y
Tell me your age 20
Your age is :20
Should I ask you again?(Y/N) N

d) Condition in the middle

 The loop with the condition to be checked is in the middle which means that
the break will be between the statements of the loop. This loop can be implemented as an
infinite loop.

Example:
while(1):
price = input("Enter integer value ")
try:
int(price)
print("Valid input")
except ValueError:
print("Invalid input!!!")
break
Output
Enter integer value 213
Valid input
Enter integer value 2324
Valid input
Enter integer value test
Invalid input!!!

You might also like