python course 2
Control Statements:
A control statement is a statement that determines the control flow of a set of instructions. It decides the
sequence in which the instructions in a program are to be executed. A control statement can either comprise of
one or more instructions.
The three fundamental methods of control flow in a programming language are
i) Sequential Control Statements
ii) Selection Control Statements
iii) Iterative Control Statements
i) Sequential Control Statements: The code of Python program is executed sequentially from the first
line of the program to its last line. That is, the second statement is executed after the first, the third statement
is executed after the second, so on and so forth. This method is known as sequential Control flow and these
statements called as sequential control statements.
ii) Selection Control Statements: Some cases, execute only a set of statements called as selection
control statements. This method is known as selection control flow.
iii) Iterative Control Statements: execute a set of statements repeatedly called as Iterative control
statements. This method is known as Iterative control flow.
The decision control statements usually jumps from one part of the code to another depending on whether a
particular condition is satisfied or not. That is, they allow you to execute statements selectively on certain
decisions. Such type of decision control statements are known as selection control statements or conditional
branching statements. Python supports different types of conditional branching statements which are as
follows:
● If statement
● If –else statement
● Nested if statement
Example 1: Program to increment a number if it is positive.
x=10
if (x>0):
x=x+1
print (x)
Output:
x=11
Example 2: Write a program to determine whether a person is eligible to vote.
age=int(input(“Enter the age: “))
if (age>18):
print (“You are eligible to vote”)
Output:
Enter the age: 35
You are eligible to vote
if –else Statement: An if-else construct, first the test expression (Boolean expression) is evaluated. If the
expression is True, statement block 1 is executed and statement block 2 is skipped. Otherwise, if the expression
is False, statement block 2 is executed and statement block 1 is ignored.
Syntax of if statement
if test_expression:
Statement block 1
else:
Statement block 2
Statement x
Example 3: Write a program to determine whether a person is eligible to vote or not. If he is not eligible,
display how many years are left to be eligible.
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 another”+ str(yrs)+ “years to
cast your vote”)
Output:
Enter the age: 10
You have to wait for another 8 years to cast your vote.
Example 4: Write a program to find whether the given number is even or odd.
num=int(input(“Enter any number :”))
if (num%2==0):
print (num, “is even”)
else:
print (num, “is odd”)
Output:
Enter any number: 125
125 is odd
Nested if statements: To perform more complex check, if statement 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 condition is satisfied.
Example 5: Write a python program to find the given number is positive or negative number, if positive number
then compare with 100, if number is greater than 100, output display as “high” otherwise display as “low”.
num = float(input("Enter a number: "))
if num >0:
if num >100:
print("High")
else:
print("Low")
else:
print("Negative number")
Output:
Enter a number: 5
low
if-elif-else Statement: The elif statement allows to check multiple expressions and executes block of
statements wherever the condition returns as True. From there, it exit from the entire if-elif-else block. If any of
the expression not returns as true, then it executes the else block code
Example 6: Program to test whether a number entered by the user is negative, positive or equal to Zero?
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
ITERATIVE CONTROL STATEMENTS/LOOPING STATEMENTS
Iterative statements are decision control statements that are used to repeat the execution of a list/set/group of
statements. Python language supports two types of iterative statements While loop and for loop.
While loop:
The while loop provides a mechanism to repeat one or more statements while a particular condition is True.
While loop, the condition is tested before any of the statements
in the statement block is executed. If the condition is True, only
then the statements will be executed otherwise if the condition
is False, it is jump to next statement which is outside of the
while loop.
Note: If the condition of a while loop is never updated and
condition never become False, then the computer will run
into an infinite loop.
Syntax of While Loop:
statement x
while (condition):
Statement block
Statement y
Example 7: Write a python program to print first 10 numbers using a while loop. i=0
while (i<=10):
print (i)
i=i+1
Output:
1
2
3
4
5
6
7
8
9
10
The for loop provides a mechanism to repeat a task(set of statements) until a particular condition is true.
The For loop is known as a determine loop because the programmer
knows exactly how many times the loop will repeat. The number of times
the loop has to be executed can be determined mathematically checking
the logic of the loop.
The for …… in statement is a looping statement used in python to
iterate over a sequece(list, tuple, string) of objects i.e., go through each
item in a sequence. Sequence means an ordered collecion of itmes.
Syntax of for Loop
for val in sequence:
Body of for (Statement Block)
Note: The for loop is widely used to execute a single or a group of
statements.
The range function():
The range() is a built-in function in Python that is used to iterate over a sequence of numbers. The syntax of
range() is
range(beginning, ending, [step size])
The range() produces a sequence of numbers starting with beginning (inclusive) and ending with one less
than the numeber end. The step argument is optional. By default, every number in range is incremented by 1
but we can specify a different increment using step.
Note: Step size can be either positive or negative but it cannot be equal to zero.
Example 10:
Program:
for i in range (1,5):
print (i, end=“ ”)
Output: 1 2 3 4
Example 11:
Program:
for i in range(1, 10, 2):
print (i, end= “ ” )
Output: 1 3 5 7 9
Example 12:
Program:
for i in range(10):
print (i, end= “ ” )
Output: 0 1 2 3 4 5 6 7 8 9
Example 13:
Program:
for i in range(1, 15):
print (i, end= “ ” )
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Example 14:
Program:
for i in range(1, 20,3): print
(i, end= “ ” )
Output: 1 4 7 10 13 16 19
break STATEMENT:
Break can be used to unconditionally jump out of the loop. It terminates the execution of the loop. Break can
be used in while loop and for loop. Break is mostly required, when because of some external condition, we
need to exit from a loop.
Example 15: Program to using the break statement i=1
while (i<=10):
print (i, end=“ ”)
if (i==5):
break
i=i+1
print ()
print (“completed”)
Output:
1 2 3 4 5
completed
Continue Statement:
This statement is used to tell Python to skip the rest of the statements of the current loop block and to move to
next iteration, of the loop. Continue will return back the control to the beginning of the loop. This can also be
used with both while and for statement.
Example 16: Program to using the continue statement
for i in range(1,11):
if (i==5):
continue
print (i, end=“ ”)
print (“\n completed”)
Output:
1 2 3 4 6 7 8 9 10
Exercise:
1. Write a program to classify a given number as prime or composite.
2. Write a program to read the numbers until -1 is encountered. Count the number of prime numbers
and composite numbers entered by the user.
3. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
4. Write a Python program to Print first 100 prime numbers.
Pass Statement:
The pass statement is used when a statement is required syntactically but no command or code has to be
executed. It specifies a null operation or No Operation (NOP) statement. Nothing happens when the pass
statement is executed.
Example17: Program to demonstrate pass statement
for letter in “Hello”:
pass #The statement is doing nothing
print (“PASS:”, letter)
print (“Done”)
Output:
PASS: H
PASS: E
PASS: L
PASS: L
PASS: O
Done
The pass statement is used as a placeholder. For example, if we have a loop that is not implement yet, but we
may wish to write some piece of code in it in the future. In such cases, pass statement can be written because
we cannot have an empty body of the loop. Though the pass statement will not do anything but it will make
the program syntactically correct.
Note: The difference between comment and pass statements is, pass is null statement that is executed by
python interpreter, comment is non-executable statement that is ignored(not executed) by python interpreter.
The else STATEMENT used with Loops:
Unlike C and C++, in python have the else statement associated with a loop statements.
1) In for-else statement, the else statement is executed when the loop has completed iterating. Break
statement can be used to stop a for loop. In such case, the else statement is ignored. Remaining cases, for
loop’s else part is executed if no break occurs.
Example 18:
for i in range(1,11):
print (i, end="")
else:
print ("\n Done")
Output:
1 2 3 4 5 6 7 8 9 10
Done
Example 19:
for i in range(1,20):
if (i==5):
break
print (i, end="")
else:
print ("\n Done")
Output:
1 2 3 4
2) else statement with the while loop, the else statement is executed when the conditions becomes
False. The while loop can be terminated with a break statement. In such case, the else part is ignored. Hence, a
while loop's else part runs if no break occurs and the condition is false.
Example 20:
i=1
while (i<0):
print (i)
i=i-1
else:
print (i, "is not negative so loop did not execute")
Output:
1 is not negative so loop did not execute
Example 21:
i=1
while (i<10):
if (i==6):
break
print (i, end=“ ”)
i=i+1
else:
print ("Completed")
Output:
1 2 3 4 5
Functions
Function is a group of related statements that perform a specific task. Functions help break our program into
smaller and modular chunks. As our program grows larger and larger, functions make it more organized and
manageable. It avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters): #Keyword def marks the start of function header.
statement(s)
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
Built-in Functions
Functions that come built into the Python language itself are called built-in functions and are
readily available to us.
Functions like print(), input(), len() etc. that we have been using, are some examples of the
built-in function. There are 68 built-in functions defined in Python 3.7.4
User-defined functions
Functions that we define ourselves to do certain specific task are referred as user-defined functions.
Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our
user-defined function could be a library function to someone else.
Advantages of user-defined functions
1. User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
3. Programmers working on large project can divide the workload by making different functions.
Example 22:
Write a python script to print a message using user-defined function.
def message( ):
print("Iam working on it,")
print("shall let you know once I finish it off") #
Call the message function.
message( )
Docstring
The first string after the function header is called the docstring and is short for documentation string. It is used
to explain in brief, what a function does.
Although optional, documentation is a good programming practice.
Example 23:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
print(greet.__doc )
Output:
This function greets to
the person passed into the
name parameter
Function Call (Calling a Function)
Once we have defined a function, we can call it from another function, program or even the Python prompt. To
call a function we simply type the function name with appropriate parameters.
Example 24:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
greet('Paul') #call a function
Example 25:
# This program has two functions. First we define the main function. def
main( ):
print('I have a message for you.')
message( )
print('Goodbye!')
# Next we define the message function.
def message( ):
print("Iam working on it,")
print("shall let you know once I finish it off") #
Call the main function.
main( )
Example 26:
#Providing Function Definition
def sum(x,y):
"""Going to add x and y"""
s=x+y
print("Sum of two numbers is")
print(s)
#Calling the sum Function
sum(10,20)
sum(20,30)
The return statement
The return statement is used returns a value from the function and goes back to the place from where it was
called with the expression. A return statement may contain a constant, variable, expression. If return is used
without anything, it will return None.
Example 27:
# Function definition is here
def changeme( x ):
return x #return statement with a argument
# Now you can call changeme function x
= 5
print changeme( x )
Example 28:
# Function definition is here
def changeme( x ):
return #return statement without argument
# Now you can call changeme function x
= 5
print changeme( x )
Void Functions:
Function performs a task, and does not contain a return statement such functions are called void functions. Void
functions do not return anything. 'None' is a special type in Python which is returned after a void function ends.
Example 29:
def check (num):
if (num%2==0):
print “True”
else:
print “False”
result = check (29)
print (result)
Output:
Comments
Post a Comment