0% found this document useful (0 votes)
79 views72 pages

Unit - 2 Python Programs

The document discusses various control flow statements in Python like if, else, elif statements and how they are used to make decisions in code. It also covers loop statements like while, for and nested loops and how they are used to repeat tasks. Range function, break and continue statements are also explained which can control loop execution.
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)
79 views72 pages

Unit - 2 Python Programs

The document discusses various control flow statements in Python like if, else, elif statements and how they are used to make decisions in code. It also covers loop statements like while, for and nested loops and how they are used to repeat tasks. Range function, break and continue statements are also explained which can control loop execution.
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/ 72

UNIT-2

CREATING
PYTHON
PROGRAMS
CONTROL-FLOW STATEMENTS
 Decision making is the most important aspect of almost all
the programming languages.
 Decision making allows us to run a particular block of code
for a particular decision.

Condition checking is the backbone of decision making


Statement Description

If Statement The if statement is used to test a specific


condition. If the condition is true, a block
of code (if-block) will be executed.
If - else Statement The if-else statement is similar to if
statement except the fact that, it also
provides the block of code for the false
case of the condition to be checked. If
the condition provided in the if statement
is false, then the else statement will be
executed.
Nested if Statement Nested if statements enable us to use if-
else statement inside an outer if
statement.
INDENTATION
 In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are
the part of the same block.
 If two statements are at the different indentation level, then
they are not part of the same block.
 All the statements of one block are intended at the same
level indentation.
if-statement
 This statement is used to test a particular condition.
 if the condition is true, it executes a block of code known as
if-block.
 The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.

Syntax: if expression:
statement
# Simple Python program to understand the if statement

num = int(input("enter the number:"))


if num%2 == 0:
print("The Given number is an even number")

Output:
enter the number: 10
The Given number is an even number
if-else statement:
 The if-else statement provides an else block combined with
the if statement which is executed in the false case of the
condition.
 If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.

Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
# Simple Python Program to check whether a number is
even or odd.
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
else:
print("The Given Number is an odd number")

Output: enter the number: 10


The Given number is even number
enter a number 29
The Given number is not an odd number
elif statement
 The elif statement enables us to check multiple conditions
and execute the specific block of statements depending
upon the true condition among them. We can have any
number of elif statements in our program depending upon
our need.
 The elif statement works like an if-else-if ladder statement
in C. It must be succeeded by an if statement.
Syntax:
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
# Simple Python program to understand elif statement

number = int(input("Enter the number?"))

if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50");
elif number==100:
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Output:
Enter the number 25
The given number is not equal to 10, 50 or 100

Enter the number 50


The given number is equal to 50
Loops: Run a single statement or a set of statements
repeatedly. OR
Repetition of certain set of statements until the condition
holds true.
The following loops are available in the Python
programming language.
Sl.No. Name of the Loop Type & Description
loop
1 While loop Repeats a statement or group of statements while a
given condition is TRUE. It tests the condition
before executing the loop body.

2 For loop This type of loop executes a code block multiple


times and abbreviates the code that manages the
loop variable.
3 Nested loops We can iterate a loop inside another loop.
While Loop
While loops are used in Python to iterate until a specified
condition is true. However, the statement in the program that
follows the while loop is executed once the condition changes
to false.
Syntax:
while <condition>:
{ code block }
Python program to show how to use a while loop
counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

Output:
Python Loops
Python Loops
Python Loops
Python Loops
For Loop:
Python's for loop is designed to repeatedly execute a code
block while iterating through a list, tuple, dictionary or other
iterable objects of Python.
The process of traversing a sequence is known as iteration.
Syntax:
for value in sequence:
{ code block }

Loop repeats until the final item of the sequence are reached.
# Python program to show the working of for loop

# Creating a sequence which is a tuple of numbers


numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

# variable to store the square of the number


square = 0

# Creating an empty list


squares = []

# Creating a for loop


for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81,
4]
Range() Function
 With the help of the range() function, we may produce a series of
numbers.
For ex: range(10) will produce values between 0 and 9. (10
numbers)
 We can give specific start, stop, and step size values in the
manner range(start, stop, step size). If the step size is not
specified, it defaults to 1.

Ex:
print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))


Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
Nested Loops
One loop present inside another loop.
Ex: Program to demonstrate nested for-loop
import random
numbers = [ ]
for val in range(0, 11):
numbers.append(random.randint( 0, 11 ) )
for num in range( 0, 11 ):
for i in numbers:
if num == i:
print( num, end = " " )

Output:0 2 4 5 6 7 8 8 9 10
Loop Control Statements:
Continue Statement:
 Python continue keyword is used to skip the remaining
statements of the current loop and go to the next iteration.
 In Python, loops repeat processes on their own in an
efficient way. However, there might be situation when we
wish to leave the current loop entirely, skip iteration, or
dismiss the condition controlling the loop.
 The continue keyword is a loop control statement that
allows us to change the loop's control.
Syntax:
continue
Python Continue Statements in for Loop
# looping from 10 to 20
for iterator in range(10, 21):

# If iterator is equals to 15, loop will continue to the next itera


tion
if iterator == 15:
continue
# otherwise printing the value of iterator
print( iterator )
Output:
10
11
12
13
14
16
17
18
19
20
Break Statement
 The break is a keyword in python which is used to bring the
program control out of the loop.
 The break statement breaks the loops one by one, i.e., in the
case of nested loops, it breaks the inner loop first and then
proceeds to outer loops. In other words, we can say that
break is used to abort the current execution of the program
and the control goes to the next line after the loop.
 The break is commonly used in the cases where we need to
break the loop for a given condition.

Syntax:
#loop statements
break;
Break statement with for loop

my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print("Item matched")
count += 1
break
print("Found at location", count)

Output: Item matched


Found at location 2
break statement with while loop
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");

Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
Headings continue pass
Definition The continue statement is utilized The pass keyword is used when a
to skip the current loop's phrase is necessary syntactically to be
remaining statements, go to the placed but not to be executed.
following iteration, and return
control to the beginning.
Action It takes the control back to the Nothing happens if the Python
start of the loop. interpreter encounters the pass
statement.
Application It works with both the Python It performs nothing; hence it is a null
while and Python for loops. operation.
Syntax It has the following syntax: -: Its syntax is as follows:- pass
continue

Interpretation It's mostly utilized within a loop's During the byte-compile stage, the
condition. pass keyword is removed.
Pass Statement:
 The pass statement is also known as the null statement.
 We can use the pass statement as a placeholder when
unsure of the code to provide. Therefore, the pass only
needs to be placed on that line.
 We can simply insert a pass in cases where empty code is
prohibited, such as in loops, functions, class definitions,
and if-else statements.

Syntax:
Keyword:
pass
# Python program to show how to use a pass statement in
a for loop
sequence = {"Python", "Pass", "Statement", "Placeholder"}
for value in sequence:
if value == "Pass":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)
Output:
Not reached pass keyword: Python
Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
Functions
 A collection of related assertions that carry out a
mathematical, analytical or evaluative operation is known
as a function.
 Python functions are necessary for intermediate-level
programming and are easy to define.
 The objective is to define a function and group-specific
frequently performed actions. Instead of repeatedly creating
the same code block for various input variables, we can call
the function and reuse the code it contains with different
variables.
Advantages of Python Functions
We can stop a program from repeatedly using the same code
block by including functions.
 Once defined, Python functions can be called multiple
times and from any location in a program.
 Our Python program can be broken up into numerous, easy-
to-follow functions if it is significant.
 The ability to return as many outputs as we want using a
variety of arguments is one of Python's most significant
benefit.
Defining a Function
 Function blocks begin with the keyword def followed by the
function name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within
these parentheses.
You can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement;
the documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and
is indented.
 The statement return [expression] exits a function, optionally
passing back an expression to the caller.
A return statement with no arguments is the same as return
None.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

Example:
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return greetings()
Calling a Function
 Calling a Function To define a function, use the def
keyword to give it a name, specify the arguments it must
receive and organize the code block.
 When the fundamental framework for a function is finished,
we can call it from anywhere in the program.

Output:
Length of the string Functions is: 9
Length of the string Python is: 6
Example for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Pass by Reference vs. Pass by Value
 There are two main function calling mechanisms: Call by
Value and Call by Reference.
 In the Python programming language, all parameters are
passed by reference.
 It shows that if we modify the worth of contention within a
capability, the calling capability will similarly mirror the
change.
# defining the function
def square( item_list ):
”This function will find the square of items in the list”
squares = [ ]
for p in item_list:
squares.append( p**2 )
return squares

# calling the defined function


my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )

Output: Squares of the list are: [289, 2704, 64]


Function Arguments
The following are the types of arguments that we can use to
call a function:
 Default arguments
A default contention is a boundary that takes as
information a default esteem, assuming that no worth is
provided for the contention when the capability is called.

 Required arguments
Required arguments are those supplied to a function
during its call in a predetermined positional sequence. The
number of arguments required in the method call must be
the same as those provided in the function's definition.
 Variable-length arguments
We can use unique characters in Python capabilities to
pass many contentions. However, we need a capability.
This can be accomplished with one of two types of
characters:
"args" and "kwargs" refer to arguments not based on
keywords.

 Keyword arguments
Keyword arguments are linked to the arguments of a
called function. While summoning a capability with
watchword contentions, the user might tell whose
boundary esteem it is by looking at the boundary name.
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling the function and passing only one argument


print( "Passing only one argument" )
function(30)

# Now giving two arguments to the function


print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
Return Statement
 When a defined function is called, a return statement is
written to exit the function and return the calculated value.
 The return statement can be an argument, a statement, or a
value, and it is provided as output when a particular job or
function is finished. A declared function will return an
empty string if no return statement is written.

Syntax:
return < expression to be returned as output >
# Python code to demonstrate the use of return statements
# Defining a function with return statement
def square( num ):
return num**2

# Calling function and passing arguments.


print( "With return statement" )
print( square( 52 ) )

# Defining a function without return statement


def square( num ):
num**2

# Calling function and passing arguments.


print( "Without return statement" )
print( square( 52 ) )
Output:
With return statement 2704
Without return statement None
Scope and Lifetime of Variables
 A variable's scope refers to the program's domain wherever
it is declared. A capability's contentions and factors are not
external to the characterized capability. They only have a
local domain as a result.
 The length of time a variable remains in RAM is its
lifespan.
 The lifespan of a function is the same as the lifespan of its
internal variables. When we exit the function, they are
taken away from us. As a result, the value of a variable in a
function does not persist from previous executions.
# Python code to demonstrate scope and lifetime of variab
les

#defining a function to print a number.


def number( ):
num = 50
print( "Value of num inside the function: ", num)

num = 10
number()
print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 50
Value of num outside the function: 10
Built-in Functions:
The Python built-in functions are defined as the functions
whose functionality is pre-defined in Python. OR
The python interpreter has several functions that are always
present for use. These functions are known as Built-in
Functions.

1. abs() Function
The python abs() function is used to return the absolute value
of a number.
It takes only one argument, a number whose absolute value is
to be returned. The argument can be an integer and floating-
point number.
If the argument is a complex number, then, abs() returns its
magnitude.
# integer number
integer = -20
print('Absolute value of -0 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -20.83 is:', abs(floating))

Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
2. all() Function
The python all() function accepts an iterable object (such as
list, dictionary, etc.).
It returns true if all items in passed iterable are true.
Otherwise, it returns False. If the iterable object is empty, the
all() function returns True.

Output:
True
False
False
False
True
# all values true
k = [1, 3, 4, 6]
print(all(k))

# all values false


k = [0, False]
print(all(k))

# one false value


k = [1, 3, 7, 0]
print(all(k))

# one true value


k = [0, False, 5]
print(all(k))

# empty iterable
k = []
print(all(k))
3. Python bool()
The python bool() converts a value to boolean(True or False) using
the standard truth testing procedure.

Example:
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True
4.compile() Function
The python compile() function takes source code as input and
returns a code object which can later be executed by exec()
function.
Ex: # compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)

Output:
<class 'code'>
sum = 15
5.sum() Function
This function is used to get the sum of numbers of an iterable,
i.e., list.
Example:

s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)

Output:
7
17
6. any() Function
The python any() function returns true if any item in an iterable is
true. Otherwise, it returns False.
Example:
l = [4, 3, 2, 0]
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))
Output:
True
False
True
False
7. eval() Function
The python eval() function parses the expression passed to it
and runs python expression(code) within the program.

Example:
x=8
print(eval('x + 1'))

Output:
9
8. float() function
The python float() function returns a floating-point number
from a number or string.

Output:
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'
Example:
# for integers
print(float(9))

# for floats
print(float(8.19))

# for string floats


print(float("-24.27"))

# for string floats with whitespaces


print(float(" -17.19\n"))

# string float error


print(float("xyz"))
9.Python bytearray()
The python bytearray() returns a bytearray object and can
convert objects into bytearray objects or create an empty
bytearray object of the specified size.

Example:
string = "Python is a programming language."
# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

Output:
bytearray(b 'Python is a programming language.')
10. format() Function
The python format() function returns a formatted
representation of the given value.

Output:
123
123.456790
1100
Modules
A document with definitions of functions and various
statements written in Python is called a Python module. OR
A module is a file containing Python code, definitions of
functions, statements, or classes.
example_module.py file is a module we will create and
whose name is example_module.
In Python, we can define a module in any one of three ways:
 Python itself allows for the creation of modules.
 Similar to the re (regular expression) module, a module can
be primarily written in C programming language and then
dynamically inserted at run-time.
 A built-in module, such as the itertools module, is
inherently included in the interpreter.
Command line arguments
 The Python supports the programs that can be run on the
command line, complete with command line arguments.

 It
is the input parameter that needs to be passed to the script
when executing them.
Module Use Python version

sys All arguments in All


sys.argv (basic)
argparse Build a command >= 2.3
line interface
docopt Created command >= 2.5
line interfaces
fire Automatically All
generate command
line interfaces (CLIs)
optparse Deprecated < 2.7
1. Python sys module
import sys
# Check the type of sys.argv
print(type(sys.argv)) # <class ' list '>
# Print the command line arguments
print(' The command line arguments are: ')
# Iterate over sys.argv and print each argument
for i in sys.argv:
print(i)

Output:
<class ' list '>
The command line arguments are:
script.py
arg1 arg2
ASSIGNMENT1:
1.DEFINE PYTHON. EXPLAIN ANY THREE FEATURES OF PYTHON.

2. EXPLAIN INDENTATION WITH SUITABLE EXAMPLE PROGRAM.

3.DEFINE IDENTIFIERS, KEYWORDS AND VARIABLES.

4.BRIEFLY EXPLAIN OPERATORS IN PYTHON.

5.EXPLAIN DIFFERENT CONTROL-FLOW STATEMENTS IN PYTHON


PROGRAMMING.
Assignment2:
1.bin() Function 2. bytes()
3. callable() 4. exec()
5.ascii() 6. frozenset()
7. getattr() 8.globals()
9. hasattr() 10. iter()
11. len() 12. list()
13. pow() 14. print()
15. int() 16. input()

You might also like