Python Chap 2
Python Chap 2
if
if – else
if – elif – else
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
...
else:
Default Action
Anand Komiripalem
Assignment
Write a program to check whether the given number is even or
odd?
Write a Program to Check whether the given Number is in
between 1 and 100?
Write a program to find smallest of given 3 numbers?
Anand Komiripalem
for loop:
If we want to execute some action for every element present in
some sequence (it may be string or collection) then we should go
for - for loop.
Syntax: for x in sequence:
Body
Where sequence can be string or any collection
Body will be executed for every element present in the sequence.
Anand Komiripalem
x=1
while x <= 10:
print(x)
x = x+1
Anand Komiripalem
Eg: Write a program to prompt user to enter some name until entering Your name
name=""
while name!=“anand":
name=input("Enter Name:")
print("Thanks for confirmation")
Anand Komiripalem
Nested Loops:
Loop inside another loop is known as nested loops.
for i in range(4):
for j in range(4):
print("i=",i," j=",j)
Anand Komiripalem
Eg 2:
cart=[10,20,500,700,50,60] 10
for item in cart: 20
if item>=500: cannot process item : 500
print("cannot process item :",item) cannot process item : 700
continue 50
print(item) 60
Anand Komiripalem
numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print(“please wakeup … cannt divide by zero")
continue
print("100/{} = {}".format(n,100/n))
100/10 = 10.0
100/20 = 5.0
please wakeup … cannt divide by zero g
100/5 = 20.0
please wakeup … cannt divide by zero
100/30 = 3.3333333333333335
Anand Komiripalem
for i in range(50):
0
if i%9==0:
9
print(i)
else:pass 18
27
36
45
Anand Komiripalem
cart=[10,20,600,30,40,50]
for item in cart: 10
20
if item>=500:
We cannot process this order
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")
If the loop is terminated using break then else will not be executed.
Anand Komiripalem
10
20
30
40
50
Congrats ...all items processed successfully
Anand Komiripalem
del Statement:
• del is a keyword in Python.
• We can delete variable by using del keyword
x = 10
print(x) #10
del x
print(x) #error
Anand Komiripalem
STRING
DATA TYPE
Anand Komiripalem
Note: In most of other languages like C, C++, Java, a single character with in
single quotes is treated as char data type value. But in Python we are
not having char data type. Hence it is treated as String only.
Note:
If we are not specifying begin index then it will consider from beginning of
the string.
If we are not specifying end index then it will consider up to end of the
string.
The default value for step is 1.
Anand Komiripalem
Note:
To use + operator for Strings, compulsory both arguments should be str
type.
To use * operator for Strings, compulsory one argument should be str and
other argument should be int.
Anand Komiripalem
Eg:
s = ‘anand'
print(len(s)) 5
Anand Komiripalem
s = ‘Anand'
print('d' in s) True
print('z' in s) False
Output:
------------------------------------------
s = input("Enter main string:") Enter main string:
subs = input("Enter sub string:") Advantosoftwaresolutions
if subs in s:
Enter sub string: solution
print(subs,"is found in main string")
Solution is found in main string
else:
print(subs,"is not found in main string")
Anand Komiripalem
Output:
s1=input("Enter first string:")
s2=input("Enter Second string:") Enter First String: anand
if s1==s2: Enter Second String: anand
print("Both strings are equal") Both Strings are equal
-----------------------------------
elif s1<s2:
Enter First String: anand
print("First String is less than Second ") Enter Second String: Ravi
else: First String is less than Second
print("First is greater than Second ")
Anand Komiripalem
Eg:
s="Learning Python is very easy"
print(s.find("Python")) #9
print(s.find("Java")) # -1
print(s.find("r")) #3
print(s.rfind("r")) #21
Note: By default find() method can search total string. We can also
specify the boundaries to search.
Anand Komiripalem
index():
index() method is exactly same as find() method except that if the specified
substring is not available then we will get ValueError.
Consider the same above example and replace find() with index()
Anand Komiripalem
Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1) # Learning Python is very easy
Eg 2:
s = "ababababababab"
s1 = s.replace("a","b")
print(s1) #bbbbbbbbbbbbbb
Anand Komiripalem
Eg:
s = "abab"
s1 = s.replace("a","b")
print(s,"is available at :",id(s)) #abab is available at : 4568672
print(s1,"is available at :",id(s1)) #bbbb is available at : 4568704
Anand Komiripalem
Ex: Output:
s=“Advanto Software Pvt Ltd" Advanto
l=s.split() Software
for x in l: Pvt
print(x) Ltd
Ex:2
Output:
s="22-02-2017"
l=s.split('-') 22
for x in l: 02
print(x) 2017
Anand Komiripalem
Ex:
x='-'.join("Hai how are you")
print(x) #H-a-i- -h-o-w- -a-r-e- -y-o-u
s="how"
t=" ".join(s)
print(t) #h o w
Eg :
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s) #sunny-bunny-chinny
Anand Komiripalem
Ex:
s = 'learning Python is Easy'
print(s.upper()) #LEARNING PYTHON IS EASY
print(s.lower()) #learning python is easy
print(s.swapcase()) #LEARNING pYTHON IS eASY
print(s.title()) #Learning Python Is Easy
print(s.capitalize()) #Learning python is easy
Anand Komiripalem
Ex:
s = 'learning Python is very easy'
print(s.startswith('learning')) #True
print(s.endswith('learning')) #False
print(s.endswith('easy')) #True
Anand Komiripalem
Eg:
Output:
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character") Enter any character: Hai
if s.isalpha(): Alpha Numeric Character
print("Alphabet character")
elif s.islower(): Enter any character: HELLO
print("Lower case alphabet character")
Alpha Numeric Character
elif s.isupper():
print("Upper case alphabet character") Upper case alphabet character
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Anand Komiripalem
Ex:
name = 'anand'
salary = 10000
age = 48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
anand 's salary is 10000 and his age is 48
anand 's salary is 10000 and his age is 48
anand 's salary is 10000 and his age is 48
Anand Komiripalem
Alternate Way:
s = input("Enter Some String:")
print(''.join(reversed(s)))
Alternate Way:
s = input("Enter Some String:")
i=len(s)-1
target=''
while i>=0:
target=target+s[i]
i=i-1
print(target)
Anand Komiripalem
Note:
chr(unicode) The corresponding character
ord(character) The corresponding unicode value
Anand Komiripalem