0% found this document useful (0 votes)
2 views13 pages

unit 2 python

The document provides an overview of Python control flow statements, including conditional, iterative, and transfer statements. It explains various types of conditional statements (if, if-else, if-elif-else, nested if-else), looping constructs (for and while loops), and transfer statements (break, continue, pass). Additionally, it covers the concept of functions in Python, including their definition, types, and the use of arguments, as well as lambda functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views13 pages

unit 2 python

The document provides an overview of Python control flow statements, including conditional, iterative, and transfer statements. It explains various types of conditional statements (if, if-else, if-elif-else, nested if-else), looping constructs (for and while loops), and transfer statements (break, continue, pass). Additionally, it covers the concept of functions in Python, including their definition, types, and the use of arguments, as well as lambda functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Unit 2 python

Python Control Flow Statements and Loops


In Python programming, flow control is the order in which statements or blocks of code are
executed at runtime based on a condition.
Control Flow Statements
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false. You
can execute different blocks of codes depending on the outcome of a condition. Condition
statements always evaluate to either True or False.
There are three types of conditional statements.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the
condition is True. We also call it a loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
1. for loop
2. while loop
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain
manner. For this purpose, we use three types of transfer statements.
1. break statement
2. continue statement
3. pass statements
1.If statement in Python
4. In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.
5. If the condition is True, then the True block of code will be executed, and if the condition
is False, then the block of code is skipped, and The controller moves to the next line
6. Syntax of the if statement
7. if condition:
8. statement 1
9. statement 2
10. statement n
If – else statement
The if-else statement checks the condition and executes the if block of code when the condition
is True, and if the condition is False, it will execute the else block of code.
Syntax of the if-else statement
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition is False, statement 2
will be executed. See the following flowchart for more detail.

Chain multiple if statement in Python


In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one
after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple
conditions one by one and if the condition fulfills, then executes that code.
Syntax of the if-elif-else statement:
if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement

Nested if-else statement


In Python, the nested if-else statement is an if statement inside another if-else statement. It is
allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful when
we want to make a series of decisions.
Syntax of the nested-if-else:
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
for loop in Python
Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.
Read the Complete guide on Python for loop.

Python for loop


Syntax of for loop:
for element in sequence:
body of for loop
Example to display first ten numbers using for loop
for i in range(1, 11):
print(i)
While loop in Python
In Python, The while loop statement repeatedly executes a code block while a particular
condition is true.
In a while-loop, every time the condition is checked at the beginning of the loop, and if it is
true, then the loop’s body gets executed. When the condition became False, the controller comes
out of the block.
Break Statement in Python
The break statement is used inside the loop to exit out of the loop. It is useful when we want
to terminate the loop as soon as the condition is fulfilled instead of doing the remaining
iterations. It reduces execution time. Whenever the controller encountered a break statement, it
comes out of that loop immediately
Let’s see how to break a for a loop when we found a number greater than 5.
Example of using a break statement
for num in range(10):
if num > 5:
print("stop processing.")
break
print(num)
Continue statement in python
The continue statement is used to skip the current iteration and continue with the next iteration.
Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body of
the loop for other numbers.
Example of a continue statement
for num in range(3, 8):
if num == 5:
continue
else:
print(num)

Pass statement in Python


The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation in
programming where we need to define a syntactically empty block. We can define that block
with the pass keyword.
A pass statement is a Python null statement. When the interpreter finds a pass statement in the
program, it returns no operation. Nothing happens when the pass statement is executed.
It is useful in a situation where we are implementing new methods or also in exception
handling. It plays a role like a placeholder.
Example
months = ['January', 'June', 'March', 'April']
for mon in months:
pass
print(months)
Python Functions

Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability

Types of Functions in Python


Below are the different types of functions in Python:
• Built-in library function: These are Standard functions in Python that are available to
use.
• User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to python")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the
example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to python")

# Driver code to call a function


fun()
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number passed
as an argument to the function is even or odd.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function call.
In Python, we have the following function argument types in Python:
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments to write
functions in Python.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller does
not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='ram', lastname='sham')
student(lastname=’sham’, firstname='ram')

Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong places,
as shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned
to the age.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'python')

Python lambda
In Python, an anonymous function means that a function is without a name. As we already
know that def keyword is used to define the normal functions and the lambda keyword is used
to create anonymous functions.
Python lambda Syntax:
lambda arguments : expression

Python lambda properties:


• This function can have any number of arguments but only one expression, which is
evaluated and returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
• It has various uses in particular fields of programming, besides other types of expressions
in functions.

Difference between lambda and normal function call


The main difference between lambda function and other functions defined using def keyword
is that, we cannot use multiple statements inside a lambda function and allowed statements are
also very limited inside lambda statements. Using lambda functions to do complex operations
may affect the readability of the code.
Assignment No 2: Question
1.explain conditional statements.
2.expalin looping statements
3.explain break , continue , and pass statement
4. explain function and function with arguments.
5. explain lambda function.

You might also like