[go: up one dir, main page]

0% found this document useful (0 votes)
15 views33 pages

Input Output & Control Flow Statements

The document provides an overview of control flow in Python, detailing input and output statements, control statements, and looping constructs. It explains how to use the input function for various data types and the print function for displaying outputs, along with examples of conditional and looping statements. Additionally, it covers the use of functions like eval(), ord(), and chr(), and the range function for generating sequences.

Uploaded by

vedantb062
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views33 pages

Input Output & Control Flow Statements

The document provides an overview of control flow in Python, detailing input and output statements, control statements, and looping constructs. It explains how to use the input function for various data types and the print function for displaying outputs, along with examples of conditional and looping statements. Additionally, it covers the use of functions like eval(), ord(), and chr(), and the range function for generating sequences.

Uploaded by

vedantb062
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Control flow

Input statement: input()


●​ in Python input function is used to get input from user
●​ syntax : variable =input ('message')
●​ input function will take string input by default.
●​ to get the require data type, type casting is required.
●​ it is not possible to get input from collection datatypes like list, set, tuple and
dictionary using Type casting, therefore we use eval() function.
●​ ( evaluate function )using eval() function, we can take input for all data types.

Example:
For int: a=int(input('Enter value:'))
For float: a=float(input('Enter value:'))
For complex: a=complex(input('Enter value:'))
For bool: a=bool(input('Enter value:'))
For string: a=input('Enter value:')
For list, tuple, set, dict: a=eval(input('Enter value:'))

Output Statements: print()


●​ In Python print function is used to display the output on the screen.
●​ syntax : print( value1, value2,..., val n, sep= ' ', end='\n')
●​ where separator and end are default arguments.
●​ using print function, n number of values can be printed at a time.
●​ separator and end values could be modified other than that of space(' ') or next
line('\n')

Example: Create a File -> enter input -> Run Module -> She'll output
Input Output
>>>print(10,20,30) 10 20 30
>>>print(10,20,30, sep=',') 10,20,30
>>>print(7, 5, sep='#') 7#5
>>>print(10,20,30, sep=',', end='@') 10,20,30@7#5
print(7, 5, sep='#')
1. Write a program to find product of two integer numbers.
a= int(input('Enter a:'))
b= int(input('Enter b:'))
print('Product of a and b : ', a*b)

Note: to format input value in output statement, we used f and { }.


print (f'product of {a} and {b} is: ',a*b)

2. Print number of characters in a string


a=input('enter a string:')
print(len(a))

3. Print rivers of a given string as output.


a=input('enter a string:')
print(a[::-1])

4. Print cube of an integer


a= int(input('Enter a number:'))
print(a**3)

Control statements:
These are the statements used to control the flow of execution of a program.
Control statements are of two types:
1. Conditional/decisional statement
2. Looping statement
Conditional statement
It controls the flow of execution based on some condition.
Types:
★​ Simple if
★​ if else
★​ elif
★​ nested if

Looping statements:
it controls flow of execution by repeating the same instruction execution for n number of
times.
Types:
●​ While loop
●​ for loop

Simple if:
●​ If is a keyword.
●​ it's used to check condition .
●​ if condition is true, then control will execute true statement block.
●​ if condition is False, then control will ignore executing true statement block.
●​ Syntax and flow diagram

# Create a File------>Enter inputs----->Run Module----->Shell Output

#Program, find Product of 2 int.


a=int(input('Enter a value:'))
b=int(input('Enter another value:'))
print(a*b)
print('Product of a and b is=', a*b)
print(f'Product of {a} and {b} is=', a*b)

#Pr, Print number of char in a string.


s=input('Enter a str:')
print(len(s))
print(len(s), 'are the no. of char present in the str')
print(len(s), f'are the no. of char present in the str called {s}')
print(len(s), f'are the no. of char present in the str called "{s}" ')

#Pr, Check if string has <=5 characters


s=input('Enter:')
if len(s)<=5:
print(f'{s} has <=5 characters')

#Pr, check if the int is 2 digit number.


n=int(input('Enter:'))
if n>9 and n<100:
print('2 digit number')
#if n>=10 and n<=99:
#if 9<n<100:
#if 10<=n<=99:

#Pr, Check if the char is Upper case


char=input( )
if 'A'<=char<='Z':
print(' Upper case')

#Pr, Check if the char is Vowel

char=input( 'Enter a character:')


#if char in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:
#if char=='a' or char=='e' or char=='i' or..........

if char in 'aeiouAEIOU':
print('Vowel')

1. Write a program to check if int is greater than 100


n= int(input("enter number'))
if n>100:
print (' n is greater than 100')
print('Done')

2. Write a program to check if integer is even.


n= int(input("enter number'))
if n%2==0:
print (f' {n} is even')

3. Write a program to check given input is of the type float


n = eval(input('enter the data:'))
if type(n)==float:
print("Float Data type")

4. Write a program to check if the character is uppercase alphabet.


char=input('Enter a character:')
if 'A'<=char'<='Z':
print ('uppercase')

5. Write a program to check whether the given data is of single value data type
n = eval(input('enter the data:'))
if type(n)==int or type(n)==float or type(n)==complex or type(n)==bool:
#or
if type(n) in [int, float, complex, bool]:
#or
if type(n) not in [str, list, tuple, set, dict]
print('single value data type')

If else :
For a single condition when we have two set of statements we use if else condition.
★​ In this case if condition is true , then true statement block will be executed.
★​ if condition is false , then false statement block will be executed.
★​ Else is a default block and writing condition for else is not required.
★​ Syntax and flow diagram

1. Write a program to check if the character is uppercase alphabet or not?


char=input('Enter a character:')
if 'A'<=char'<='Z':
print ('uppercase')
else:
print('Not an uppercase alphabet ')

2. Write a program to check if the given string palindrome or not.


s=input('enter a string :')
if s[::1]==s[::-1]:
print ('String is palindrome ')
else:
print ('Not a Palindrome ')

3. Write a program to check if the given character is special symbol or not.


char=input('Enter a character:')
if 'A'<=char'<='Z' or 'a'<=char'<='z' or '0'<=char'<='9' :
print ('not a special character')
else:
print('it is a special character')

#Pr, check if char is lower case or not


char=input('Enter char:')
if 'a'<=char<='z':
print('Lower case')
else:
print('Not Lower case')

#pr, Print square of a No. if it is even, else print cube of No.


n=int(input('Enter:'))
if n%2==0:
print('Square of ', n, '=', n**2)
else:
print(f'Cube of {n}=', n**3)

#Pr, check if the string is Palindrome


s=input('String input:')
if s==s[::-1]:
print('Palindrome')
else:
print('Not Palindrome')

#Pr, Check if the input is Complex or Not


data=eval(input('Enter any data'))
if type(data)==complex:
print('Complex type')
else:
print('Not')

#pr, check if the given char is Alphabet / not


char=input('Enter a char:')
if 'a'<=char<='z' or 'A'<=char<='Z':
print('Alphabet')
else:
print('Not')

#Pr, check if str is a Keyword/not


import keyword
a=keyword.kwlist
b=input('Enter a string')
if b in a:
#if b in keyword.kwlist:
print('Keyword')
else:
print('Not Keyword')
find Relation between 2 integer

Elif Statement:
●​ Whenever there are multiple conditions and a set of statements for each and every
condition, then elif statement should be used.
●​ this will start from if and end with else block
●​ in this case, control will check other condition only if condition 1 is False ; and same
for all.
●​ Is none of the conditions are true, then else block will get executed by default .
●​ in this statement, writing else block is optional.

. .

Ex: Write a program to find relationship between two integer numbers.


x=int(input ('enter a value '))
y=int(input ('enter 2nd value:'))
if x>y:
print(f'{x} is greater'}
elif x<y:
print(f'{y} is greater'}
elif x==y:
print('Both are same')

2. Write a program to check the type of the character


char=input('Enter a character:')
if 'A'<=char'<='Z' :
print ('Upper case character')
if '0'<=char'<='9' :
print ('Numerical character')
else:
print('it is a special character')

Nested if:
Writing if condition inside another if condition is called as nested if.
Note: here the nested if will be executed only if the 1st condition is true.
Syntax and flow diagram:

. .
Ex: Write a program to check if the given integer is multiple of 5 only if it is an even number.
n=int(input ('Enter'))
if n%2==0:
if n%5==0:
print(n,' Is an even multiple of 5 ')
else:
print(n,' Is even , but not a multiple of 5 ')
else:
print(n, 'is not an even number ')

2. Write a program to check greater among three numbers using nested if.
a,b,c=int(input (()), int(input (()), int(input (())
if a>b:
if a>c:
print (a)
else:
print(c)
else:
if b>c:
print (b)
else:
print(c)
#Pr, check if the user can login to instagram by entering proper credentials

oun='ABC'
opwd='123'

un=input('Enter Username:')
pwd=input('Enter Password:')

if un==oun:
if pwd==opwd:
print('Logged in Successfully')
else:
print('Incorrect Password')
else:
print('User does not exist')

Looping statements
While loop:
●​ It is a looping statement which is used to execute the same set of instruction
repeatedly until the given condition becomes False.
●​ In while loop , initialisation and updation of looping variable is mandatory.
●​ Using while loop, efficiency of program can be increased by reducing code repetition
(or code redundancy)
●​ Syntax and flow diagram:
(TBS: true statement block)
. .
Example:write a program to print "Python" 5 times
i=0
while i<=5:
print ('Python')
i=i+1 #i+=1

2. Write a program to print n natural numbers


n= int(input ('enter a number:'))
i=1
while i<=n:
print ('i')
i=i+1 #i+=1

#Pr, print 'n' natural numbers, reverse order


n=int(input('Enter:'))
i=n
while i>=1:
print(i)
i=i-1 #i-=1

#Pr, Print all even no. between 1 to 100

i=1
while i<=100:
if i%2==0:
print(i)
i=i+1

Write a program to reverse the given in teacher without using slicing or Type casting.
(Here to get the last digit we can use modulus)
(Two eliminate the last decimal digit we can use floor division)
n= int(input ('enter a number:'))
rev=0
while n!=0
ld=n%10
rev=rev*10+ld
n=n//10
print (rev)

Write a program to print table for the given number


n= int(input ('enter a number:'))
i=1
while i<=10:
print (n, 'x', i, '=', n*i, sep='')
i=i+1 #i+=1

#Pr, Find Sum of 'n' natural nos.


n=int(input('Enter a no. :'))
out=0
i=1
while i<=n:
out=out+i
i+=1
print(out)
#Pr, Find Factorial of 'n' natural no.
n=int(input('Enter a no. :'))
out=1
i=1
while i<=n:
out=out*i
i+=1
print(out)

#Pr, extract all uppercase from a string

s=input('Enter')
out=''
i=0
while i<len(s):
if 'A'<=s[i]<='Z':
out=out+s[i]
i+=1
print(out)

Write a program to extract all special characters from the given string.
s=input ('Enter a string ')
out=''
i=0
while i< len(s):
if not('A'<=s[i]<='Z' or 'a'<=s[i]<='z' or '0'<=s[i]<='9' ):
out+=s[i]
i+=1
print (out)

Note :
ord():
Is a function which is used to get ASCII value for a particular character.
Syntax: ord(character)
>>>ord('A')
65

chr():
It is a function which is used to get character of the mentioned ASCII value.
Syntax: chr(value)
>>>chr(65)
'A'

abs():
This function is used to convert any negative integer to positive integer.
>>>n=-23
>>>abs(n)
23

Example: upper to lower case and vice versa


>>>chr(ord('A')+32)
'a'
>>>chr(ord('a')-32)
'A'

Write a program to convert all the uppercase to lowercase.


s=input ()
out=''
i=0
while i<len(s):
if 'A'<=char'<='Z' :
out+=chr(ord(s[i])+32)
else:
out+=s[i]
i+=1
print(out)

Range function: range()


It is an inbuilt function which is used to create sequence of integer numbers between the
specified limit.
Syntax: range(starting value , ending value +/-1, updation)
range(sv, ev-1/+1, up)
●​ if sv==0; and up==1
range(ev+/-1)
●​ if up==1
range(sv, ev+/-1)

Note: range function works only on integer.


Range function itself does not have the capacity ,therefore we have to type caste it, and then
use in looping statements.
Use ev+1: when numbers are ascending(LHS to RHS)
Use ev-1: when numbers are descending(RHS to LHS)

Ex:
>>>tuple(range(10,1-1,-1))
(10,9,8,7,6,5,4,3,2,1)
>>>tuple(range(10,0,-1))
(10,9,8,7,6,5,4,3,2,1)
>>>list(range(0,5+1,1))
[0,1,2,3,4,5]
>>>list(range(0,6,1))
[0,1,2,3,4,5]
>>>list(range(6))
[0,1,2,3,4,5]
>>>list(range(2,11,2))
[2,4,6,8,10]

For loop:
●​ Used to execute the same set of instructions repeatedly.
●​ initialisation and updation of looping variable is not required
●​ it is possible to get the values directly from the collection using for loop.
●​ this can be used only if we know the number of iterations.

syntax: for var in collection:


Statement block
Example :
for i in range(1,11):
print (i )

for i in 'python':
print (i )

for i in [10,20,30]:
print (i )

for i in (1,2,3):
print (i )

for i in {10,20,30}:
print (i )

for i in {'a':10, 'b':20}:


print (i )

Write a program to find sum of all the integers present in a given list
L=eval(input('Enter List of integer '))
s=0
for i in L:
if type (i)==int:
s=s+I
print (sum)

Write a program to extract all characters from string only if its ASCII value is 3 digit
number.
s=input('Enter a string:')
out=''
for i in s:
if 99<ord(i)<1000:
out+=i
print (out)

Write a program to find the length of collection without using length function.
x=eval(input(' values:')
len=0
for i in x:
len+=1
print(len)

Split function:
It is an inbuilt function used to convert the given string into list of words.
This works only on string collection.
Syntax: split()
●​ var.split()
Here the default split happens for every space.

●​ var.split(char)
Here it's splits at the specified character.

●​ var split (char, number of splits)


Here we can also control the number of splits.

Example:
>>>s='Python is very easy'
>>>s.split()
['Python', 'is', 'very', 'easy']
>>>s.split('y')
['P', 'thon', 'is', 'very', 'eas', ' ']
>>>s.split(' ',2)
['Python', 'is', 'very easy ']

●​ Split function: converts string to list of words.


●​ join function: converts list of words to string .

>>>a=['Python', 'is', 'very', 'easy']


>>>' '.join(a)
'Python is very easy'

>>>'_'.join(a)
'Python_is_very_easy'

Write a program to get the following output.


s='good day'
Output={'good':4, 'day':3}
s=input ('enter:')
out={}
for i in s.split():
out[i]=len(i)
print (out)

Write a program to generate following output


Input :'hi hello how are you'
output :'you are how hello hi'
a=input ('Enter a string:')
b=a.split()
c=b[::-1]
print (' '.join(c))

Nested for loop:


writing for loop inside another is called nested for loop

#Pr, Extract all lower case from a str


s=input('Enter') #WHILE LOOP
out=''
i=0
while i<len(s):
if 'a'<=s[i]<='z':
out=out+s[i]
i+=1
print(out)
#-------------------------------------------------------------------
s=input('Enter') #FOR LOOP
out=''
for i in s:
if 'a'<=i<='z':
out=out+i
print(out)

#Pr, extract all int from a list


d=eval(input('Enter a list'))
out=[]
for i in d:
if type(i)==int:
out=out+[i]
print(out)

#Pr, Print Palindrome no. between 1 to 100

#using while loop.


i=1
while i<=100:
if str(i)==str(i)[: : -1]:
print(i)
i=i+1
#============================

#using FOR loop.


for i in range(1, 101):
if str(i)==str(i)[: : -1]:
print(i)
#Pr, Print the following output:
#input: l= [12, 'hi', 3j, 45.8, 'Python']
#Output ={'hi':2, 'Python':6 }
l=eval(input('Enter a list:'))
out={}
i=0 #WHILE LOOP
while i<len(l):
if type(l[i])==str:
out[l[i]]=len(l[i])
i+=1
print(out)
#===================================================
l=eval(input('Enter a list:'))
out={}
for i in l: #FOR LOOP
if type(i)==str:
out[i]=len(i)
print(out)

#Pr, Print the following output:


#input: a= [12, 'hi', 3j, 45.8, 'Python']
#Output: {'hi':'ih', 'Python':'nohtyP' }
a=eval(input('Enter a list'))
out={}
i=0 #WHILE LOOP
while i<len(a):
if type(a[i])==str:
out[a[i]]=a[i][: : -1]
i+=1
print(out)
#=====================================
a=eval(input('Enter a list'))
out={} #FOR LOOP
for i in a:
if type(i)==str:
out[i]=i[: : -1]
print(out)

#Pr, Print the following output:


#input: a= (2, 'hi', 3j, 45.8, 'Python', 3, 4)
#Output: {2:4, 3:9, 4:16 }
a=eval(input('Enter a tuple'))
out={}
i=0
while i<len(a):
if type(a[i])==int:
out[a[i]]=a[i]**2
i+=1
print(out)
#================================
a=eval(input('Enter a tuple'))
out={}
for i in a:
if type(i)==int:
out[i]=i**2
print(out)
#Pr, Print the following output:
#input: s='Good Day'
#Output: {'Good':4, 'Day':3}

s=input('Enter a String')
out={}
a=s.split()
for i in a:
out[i]=len(i)
print(out)

#Pr, Print all natural nos. b/w 1 to n; if it is multiple of 7


num = int(input('Enter the input : '))
for i in range(1,num+1):
if i % 7 ==0:
print(i)

# pr. to extract special char from the string.

a = input('Enter the Value : ')


out = ''
for i in a:
if not('A'<=i<='Z' or 'a'<=i<='z' or '0'<=i<='9'):
out = out+i
print(out)

#Pr, Print the following ;


#input: s='Python programming lang data for loop'
#Output ['Python', 'lang', 'data', 'loop']

s=input('String input please:')


out=[]
x=s.split()
for i in x: #for i in s.split()
if len(i)%2==0:
out=out+[i]
print(out)

#Pr, Print the following ;


#input: s='Hi Hello How are you!'
#Output ['you!', 'are', 'How', 'Hello', 'Hi']
#Output 'you! are How Hello Hi'
s = input('Enter the Value : ')
a = s.split()
b=a[::-1]
print(b)
c=' '.join(b)
print(c)

#or
s = input('Enter the Value : ')
print(s.split()[::-1])
print(' '.join(s.split()[::-1]))
#or
print(input('Enter:').split()[::-1])
print(' '.join(input('Enter:').split()[::-1]))
#Pr, Find length of a collection without using len()

x=eval(input('Enter any data'))


len=0
for i in x:
len=len+1
print(len)

Intermediate Termination in Loops:


As we know, For and While loop will get executed for 'n' Number of times.
●​ If it is required for the user to stop the loop in between, then intermediate termination
can be used.
●​ This can be done by using the following keywords:
●​ Break
●​ Continue
●​ Pass

Break:
It is a keyword which is used to stop the loop in between.
As soon as a control findals a keyword break, it stops a loop immediately and it will not go
back to the same loop for further instruction execution.

Example:
for i in range(1, 11):
print( i)
break
output: 1

for i in range (1,11):


break
print( i)
output : no output.
for i in range(1,11):
if i==6:
break
print (i)
Output:
1
2
3
4
5

Write a program to accept username input from the user ;


run the program continuously until the user enters a proper username.
(Original username - oun; while true: this will execute the loop till the condition is true)
oun='Python'
while True:
un=input ('enter the username')
if un= oun
break
else:
print('Enter the correct username')

Write a program to check if the given list contains only integer in it.
l=eval( input ('enter list :'))
for i in l:
if type(I)!= int:
print(" other than integer")
break
else:
print ('only integer ')

Note: if we write if condition inside for loop, then else condition should be written outside
the for loop

#Pr, Guess the Number Game

num=678
while True:
n=int(input('Enter the Number:'))
if n==num:
print('Correct')
break
elif n<num:
print('Please enter greater number')
elif n>num:
print('Please enter lesser number')

#Pr, check if the str contains only lower case char in it.

s=input('Enter a string')
for i in s:
if not('a'<=i<='z'):
print('Other than lower case char is present')
break
else:
print('String has only lower case char')
Continue:
It is a keyword which is used to skip the current execution and will make the control to go for
next iteration execution.
continue can be used in both while and for loop.
for i in range(1, 11):
if i==5 or i==7:
continue
print(i)

for i in range(1, 11):


print(i)
continue

for i in range(1, 11):


continue
print(i)

#pr, print all even No. b/w 1 to 100

for i in range(1, 101):


if i%2!=0:
continue
print(i)

#Pr, Extract all lowercase from string


s=input('Enter a string:')
out=''
for i in s: #without "continue" keyword
if 'a'<=i<='z':
out=out+i
print(out)
#------------------------------------------------------------------------------------
s=input('Enter a string:')
out=''
for i in s: #with "continue" keyword
if not('a'<=i<='z'):
continue
out=out+i
print(out)

#Pr, Extract all VOWELS from string


s=input('Enter a string:')
out=''
for i in s: #with "continue" keyword
if i not in 'AEIOUaeiou':
continue
out+=i
print(out)

#Pr, Extract all int from list

l=eval(input('List please:'))
out=[]
for i in l:
if type(i)!=int: #if not(type(i)==int):
continue
out+=[i]
print(out)

Pass:
pass is a keyword which is used to keep an empty statement block .
it is used whenever it is required to keep an empty statement block, because if the statement
block is not present then the program will throw error , so to avoid that we use pass
statement.
a=10

b=20

if a<b:

pass

for i in range(1, 11):

pass

#Assignment:
#Simple if

#Pr, check if number is multiple of 3 and 5

#Pr, check if the data is of single value data type

#Pr, check if the int is odd

#if else:

#pr, check if the given char is Special Character or not

#Pr, check if the data is Mutable/Immutable

#Pr, check if the data is Single value/Multi value

#Pr, check if int is Positive/ Negative

#Pr, print 'True' if str has >5 char, else print 'False'

# elif:

#Pr, check if the number is 1digit/2digit/3digit/4digit/5digit/more than 5digits

#Pr, * print reversed string if str has 5 char

# * print all char present in even index, if str has even no. of char

# * print odd index char, if len of str is odd number

#Pr, consider int input, print 'fizz' if No. is divisible by 3

# print 'buzz' if No. is divisible by 5

# print 'fizzbuzz' if No. is divisible by both 3 and 5

#Pr, check if int is +ve / -ve / 0

#Nested if:

#Pr, check if given char is vowel/consonant

#while loop
#Pr, Print all natural nos, between 1 to n only if it is multiple of 3 and 5

#Pr, extract all alphabets from a string

#Pr, extract all special char from a string

#Pr, extract all complex from a tuple

#Pr, extract all str from a list only if the str has 3 char in it.

#pr, Convert uppercase to lower case and vice versa

#For Loop(using functions:)

#Pr, Check if the number is Prime number/not

#Pr, Extract all special char, only if its ASCII value is 2digit numbers

#Pr, extract all float values from list

You might also like