Unit - 2 Python Programs
Unit - 2 Python Programs
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.
Syntax: if expression:
statement
# Simple Python program to understand the if statement
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")
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
# Simple Python program to understand elif statement
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
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
Ex:
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
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):
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:
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)
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)
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
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))
# 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))
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
Output:
<class ' list '>
The command line arguments are:
script.py
arg1 arg2
ASSIGNMENT1:
1.DEFINE PYTHON. EXPLAIN ANY THREE FEATURES OF PYTHON.