You are on page 1of 65

Control Statements

and Strings
Unit III
Conditional (if), alternative (if-else), chained conditional
(if-elif-else). Iteration-while, for, infinite loop, break,
continue, pass, else. Strings-String slices, immutability,
string methods and operations.
Conditional statement or decision making
statement or selection statement

• If statement
• If-else statement
• elif statement
Conditional (if)
if statement
• if is a decision making statement or control
statement
• It is used to control the flow of execution, also to test
logically whether the condition is true or false.
Syntax:
if (condition is true) :
False
true statements Condition

True
True
Statement
a = 33
b = 200
if b > a:
print("b is greater than a")
O/P:
b is greater than a

Homework:
Write a program to determine whether a person is
eligible to vote.
Short Hand If
• If you have only one statement to execute, you can put
it on the same line as the if statement.

E.g.
a=10;b=12;
if a > b: print("a is greater than b")
Multiple if
value = input("Press any key: ")
if (value.isalpha()):
print("User entered a character")
if (value.isdigit()):
print("User entered a digit")
if(value.isspace()):
print("User entered a white space")
Alternative (if-else)
If Else
• The else keyword catches anything which isn't caught
by the preceding conditions.
Syntax:
if(condition) : False
Condition
true statement
else: True
false statement True False
Statement Statement
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
Write a program to enter any character. If the entered
character is in lowercase then convert it into uppercase
and if it is an uppercase character, then convert it into
lowercase.

ch = input("Enter a character: ")


if (ch >= 'A' and ch <="Z"):
ch = ch.lower()
print("The Character is upper, Its Lower case is: ", ch)
else:
ch = ch.upper()
print("The Character is Lower, Its upper case is: ", ch)
Short Hand If ... Else
• If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:

E.G
a = 2
b = 330
print("A") if a > b else print("B")
#True Stmt01 if condition else False stmt

• This technique is known as Ternary Operators, or


Conditional Expressions.
Homework:
• Write a program to determine whether a person is
eligible to vote or not. If not eligible, display how many
years are left to be eligible.
• Write a program to find whether the given number is
even or odd.
• Write a program to find whether a given year is leap
year or not.
Nested If
Nested If
• Nested if Statements are used to check if more than
one condition is satisfied.
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Chained conditional
(if-elif-else)
if-elif-else
• The if-elif-else construct works in the same way as a usual
if-else statement.
• Syntax:
If (condi-1):
stmt-1
Elif (condi-2):
stmt-2
Elif (condi-3):
stmt-3
Else:
stmt-4
Example

a=13
if(a==11):
print(‘cricket’)
elif(a==12):
print(‘hockey’)
elif(a==13):
print(‘running’)
else:
print(‘tennis’)
• A company decides to give bonus to all its employees
on Diwali, A 5% bonus on salary is given to the male
workers and 10% bonus on salary to the female
workers. Write a program to enter the salary of the
employee and Gender of the employee. If the salary of
the employee is less than 10,000 then the employee
gets an extra 2% bonus on salary. Calculate the bonus
that has to be given to the employee and display the
salary that the employee will get.
• Homework
1. Write a Python program to check if a number is
positive, negative or zero.
2. Write a program to find the greatest number from
three numbers.
3. Write a program that prompts the user to enter a
number between 1 - 7 and then display the
corresponding day of the week.
4. Write a Program to Check Vowel or Consonant.
Iteration /Looping statement
 The loop is defined as the block of statements which
are repeatedly executed for a certain number of time.
Types:
1. while statement
2. for statement.
Iteration-while
Iteration-while
• The while loop is an entry controlled loop statement,
means the condition as evaluated first, if it is true then
body of the loop is executed.
Syntax:
while(condition):
body of the loop
Example:
a=0
while(a<=5):
print(a)
a+=1
For
for loop statement
This is another one control structure, and it is
execute set of instructions repeatedly until the
condition become false.
Syntax:
for i in sequence:
body of loop
• With the for loop we can execute a set of
statements, once for each item in a list,
tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
• Looping Through a String

for x in "banana":
print(x)
• With the for loop we can execute a set of
statements, once for each item in a list,
tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
for y in x:
print(y)
print(x)
Range() function
The python has the built-in function range() that
generates a list of values starting from start to
stop-1 by step.
The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
Syntax:
range(start, stop-1, step)
>>> for i in range(0,10,2):
print(i)

O/P:
0
2
4
6
8
E.g.01:
for x in range(6):
print(x)
o/p:
0 E.g. 02:
1 for x in range(2, 30, 3):
print(x)
2
3 O/P: ?
4
5
break Statement
• With the break statement we can stop the
loop before it has looped through all the
items:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
continue Statement
• With the continue statement we can stop
the current iteration of the loop, and
continue with the next:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)
pass Statement
• The pass statement is used as a placeholder for future
code.
• When the pass statement is executed, nothing
happens, but you avoid getting an error when empty
code is not allowed.
E.g.01:
a = 33
b = 200

if b > a:
pass
-----------------------------------
E.g.02:
for x in [0, 1, 2]:
pass
Infinite loop
Infinite loop
• We can create an infinite loop using while statement. If
the condition of while loop is always True, we get an
infinite loop.

E.g.
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
Homework
While:
• Write a program to read the numbers until -1 is
encountered. Also count the negative, positives, and
zeros entered by user.
• Write a program to print the reverse of a number.
• Write a program to find GCD for two numbers.
Homework
For:
• Write a program using for loop to print all the numbers
ranging from m to n, thereby classifying them as even
or odd.
• Write a program using while or for loop to read the
numbers until -1 is encountered. Also, count the
number of prime numbers entered by the user.
• Write a program to sum the series - 1 + 1/2 + 1/3 + ... +
1/n.
Strings-String slices
String slices
• Subsets of strings can be taken using slice operator ([],
[:],[::]) with indexing started at 0 in the beginning of
the string
• Working their way from -1 at the end
Eg: >>>Str=‘windows’
>>>Print(str)
windows
E.g.
MyString = "abcdef"
print(MyString)
print(MyString[0:3])
print(MyString[3::])
print(MyString[0:6:2])
print(MyString[-1:-7:-1])
print(MyString[0:-2])
Concatenating Strings
• Concatenate means join together. Python allows
Concatenate two strings using the + operator.
• * operator is used to repeat the string for a specified
number of times.
• E.g.
first = “Hello"
second = “Python"
third = print( (first + second) * 2)
O/P
HelloPythonHelloPython
Append
• Append mean to add something at the end. In python
it can be done at the end of another string using +=
operator.
• E.g.
val1= "Hello "
name = input("\nEnter the name: ")
val1 += name
val1 += ". welcome to programming"
print(val1)
Immutability
Strings are immutable
• Python strings are immutable which means that once
created they cannot be changed.
String methods and
operations
String Formatting Operator
• The % operator takes a format string on the left (that
has %d, %s, etc..)
• E.g.
name = "Sona"
Pincode = 636054
print("Name = %s and Pincode = %d" %(name, Pincode))

O/P
Format Symbol Purpose
%c Character
%d or %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%f Floating point
Built-in String Methods and
Functions

• Python supports many built-in methods to manipulate


strings.
• A method is just like a function.
• The only difference between a function and method is
that a method is invoked or called on an object.
• The below functions are used to change the case of the
strings.

• lower(): Converts all uppercase characters in a string


into lowercase
• upper(): Converts all lowercase characters in a string
into uppercase
• title(): Convert string to title case
text = 'Case chanGING python'

print("\nConverted String:")
print(text.upper())

print("\nConverted String:")
print(text.lower())

print("\nConverted String:")
print(text.title())

print("\nOriginal String")
print(text)
https://www.geeksforgeeks.org/python-string-methods/
count() - Returns the number of occurrences of a substring
in the string.
E.g.
string = "geeks for geeks"
print(string.count("geeks"))

O/p
2
https://www.geeksforgeeks.org/python-string-methods/
center() - Pad the string with the specified character.
E.g.
string = "geeks for geeks"
new_string = string.center(24)

print("After padding String is: ", new_string)


https://www.geeksforgeeks.org/python-string-methods/
isdigit() - Returns “True” if all characters in the string are
digits
E.g.
string = '15460'
print(string.isdigit())

string = '154ayush60'
print(string.isdigit())
https://www.geeksforgeeks.org/python-string-methods/
zfill() - Returns a copy of the string with ‘0’ characters
padded to the left side of the string
E.g.
text = "geeks for geeks"
print(text.zfill(25))
print(text.zfill(20))

print(text.zfill(10))
ord() and chr() functions
• The ord() returns the ASCII Code of the character and
chr() returns character represented by ASCII number.
• E.g.
Comparing Strings
• Method 1: Using Relational Operators
print("Python" == "python")
print("Python" < "python")
print("Python" > "python")
print("Python" != "python")
Method 2: Iterating String
• String can be iterated by using for or while loop.
• E.g.
msg = "Welcome to python"
index = 0
while (index < len(msg) ):
letter = msg[index]
print(letter, end = ' ')
index +=1

You might also like