0% found this document useful (0 votes)
3 views29 pages

Control Statements in Python

Control statement in python

Uploaded by

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

Control Statements in Python

Control statement in python

Uploaded by

saru49497
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Literals in Python:

A literal is a constant value that is stored into a variable in a program.

a=15 here ‘a’ is a variable into which the constant value ‘15’ is stored,
hence, the value 15 is called literal. Python supports different types of
literals, such as numeric literals, string literals, Boolean literals, and
special values like none.

For example:

10, 3.14, and 5 + 2j are numeric literals.


'Hello' and "Python" are string literals.
True and false are Boolean literals.
Numeric Literals
Numeric literals represent numbers and are classified into three types:
Integer Literals – Whole numbers (positive, negative, or zero) without
a decimal point. Example: 10, -25, 0
Floating-point (Decimal) Literals – Numbers with a decimal point,
representing real numbers. Example: 3.14, -0.01, 2.0
Complex Number Literals – Numbers in the form a + bj, where a is the
real part and b is the imaginary part Example: 5 + 2j, 7 - 3j
# Integer literals
a = 100
b = -50
# Floating-point literals
c = 3.14
d = -0.005
# Complex number literals
e = 4 + 7j
f = -3j
print(a, b, c, d, e, f)
Output
100 -50 3.14 -0.005 (4+7j) (-0-3j)

String Literals

String literals are sequences of characters enclosed in quotes. They are


used to represent text in Python.

Types of String Literals:


Single-quoted strings – Enclosed in single quotes (' '). Example: 'Hello,
World!'
Double-quoted strings – Enclosed in double quotes (" "). Example:
"Python is fun!"
Triple-quoted strings – Enclosed in triple single (''' ''') or triple double
(""" """) quotes, generally used for multi-line strings or docstrings.
Example:
# Different string literals
a = 'Hello' # Single-quoted
b = "Python" # Double-quoted
c = '''This is
a multi-line string''' # Triple-quoted
d = r"C:\Users\Python” # Raw string
print(a)
print (b)
print(c)
print(d)
Output
Hello
Python
This is
a multi-line string
C:\Users\Python
Boolean Literals
Boolean literals represent truth values in Python. They help in decision-
making and logical operations. Boolean literals are useful for controlling
program flow in conditional statements like if, while, and for loops.
Types of Boolean Literals:
True – Represents a positive condition (equivalent to 1).
False – Represents a negative condition (equivalent to 0).
# Boolean literals
a = True
b = False
print(a, b) # Output: True False
print (1 == True) # Output: True
print(0 == False) # Output: True
print(True + 5) # Output: 6 (1 + 5)
print(False + 7) # Output: 7 (0 + 7)
Collection Literals
Python provides four different types of literal collections:
List literals: [1, 2, 3]
Tuple literals: (1, 2, 3)
Dictionary literals: {"key": "value"}
Set literals: {1, 2, 3}
Rank = ["First", "Second", "Third"] # List
colors = ("Red", "Blue", "Green") # Tuple
Class = { "Jai": 10, "Anaya": 12 } # Dictionary
unique_num = {1, 2, 3} # Set
print(Rank, colors, Class, unique_num)

Output
['First', 'Second', 'Third'] ('Red', 'Blue', 'Green') {'Jai': 10, 'Anaya': 12}
{1, 2, 3}
Expressions & precedence rules:
In Python, an expression is a combination of values, variables, operators,
and function calls that the interpreter evaluates to produce a new
value. Operator precedence and associativity determine the specific
order in which these operations are performed in a complex expression.
Expressions in Python
Expressions are the fundamental building blocks of computation in
Python. They can be simple, such as a single value or variable, or
complex, combining multiple operations.
Examples of Expressions:
5 (a constant expression)
x + 10 (an arithmetic expression)
a < b <= c (a relational/comparison expression)
name == "Alex" or age >= 2 (a logical expression)
my_list[index] (an expression involving
Python Operator Precedence Rules
Python follows specific rules, similar to the mathematical
PEMDAS/BODMAS rule, to determine the order of operations.
Operators with higher precedence are evaluated before those with lower
precedence. The following table summarizes the order from highest
precedence to lowest:
Rank Operators Description Associativity
Highest () [] {} Parentheses, subscription, slicing, Left-to-right
dict/list/set displays
** Exponentiation Right-to-left
+x, -x, ~x Unary plus, minus, bitwise NOT Right-to-left
*, @, /, //, % Multiplication, matrix multiplication, Left-to-right
division, floor division, modulus
+, - Addition and subtraction Left-to-right
<<, >> Bitwise shifts Left-to-right
& Bitwise AND Left-to-right

^ Bitwise XOR Left-to-right


` ` Bitwise OR
in, not in, is, is Comparisons, identity, membership tests Non-
not, <, <=, >, >=, !=, == associative*
not Boolean NOT Right-to-left
and Boolean AND Left-to-right

Control Statements in Python


Control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
By default, the instructions in a computer program are executed in a
sequential manner, from top to bottom, or from start to end.
We would like the program to have a decision-making ability, so that it
performs different steps depending on different conditions.
Python supports the following control statements.
Decision Making Statements
Decision making allows us to run a particular block of code for a
particular decision.
Here, the decisions are made on the validity of the particular conditions.
Condition checking is the backbone of decision making.
In python, decision making is performed by the following statements.
 If Statement
 If - else Statement
 Nested if Statement
 Else-if ladder statement
Indentation in Python
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.
Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the
same level indentation.

simple if statement
The if statement is used to test a particular condition and if the condition
is true, it executes a block of code known as if-block.
Syntax:
If (condition):
Statement1
Statement 2
Next statement
Flow Chart:
Ex1: #To Implement code simple if statement
#Check given number positive or not
n=int(input(“Enter a Number:”))
if (n>0):
print(“Given number is Positive”)

Ex 2: #Check Given number divisible by 2


n=int(input(“Enter a number:”))
if(n%2==0):
print(“Given number divisible by 2”)
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)
Next statements

Flow Chart:
Ex 1: #To Implement code check given number even or odd
n=int(input(“Enter a number:”))
if(n%2==0):
print(“Given number is Even”)
else:
print(“Given number is Odd”)
Ex 2: #To Implement code check eligibility for vote
age=int(input(“Enter person age:”))
if (age>=18):
print(“Person eligible for vote”)
else:
print(“Person not eligible for vote”)

if elif else 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.
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements

else:
# block of statements

Flow Chart:
Ex 1: #To Implement code check given number positive, negative or
zero
number =int(input(“Enter a numbr:”))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Ex 2: #To Implement code display student grades
marks =int(input(“Enter student Percentage:”))

if marks >= 90:


print("A")
elif marks >= 80:
print("B")
elif marks >= 70:
print("C")
elif marks >= 60:
print("D")
else:
print("F")
Iterative Styatements
Python loops allow us to execute a statement or group of statements
multiple times.
In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. There may
be a situation when you need to execute a block of code several number
of times.
Programming languages provide various control structures that allow for
more complicated execution paths.

Flowchart of a Loop
The following diagram illustrates a loop statement –

Types of Loops in Python


Python programming language provides following types of loops to
handle looping requirements –
A. while loop
B. for loop
C. nested loops

while Loop:
Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.
A while loop in Python programming language repeatedly executes a
target statement as long as the specified boolean expression is true.
This loop starts with while keyword followed by a boolean expression
and colon symbol (:). Then, an indented block of statements starts.
Syntax:
while expression:
statement(s)

Flowchart of While loop

Ex 1: #Write a Program to display sum of 1 to n numbers.


num=int(input(“Enter a Range:”))
total = 0
i= 1
while i <= num:
total =total+ i
i =i+1
print("Sum:", total)
Python Infinite while Loop
A loop becomes infinite loop if a condition never becomes
FALSE. You must be cautious when using while loops because of the
possibility that this condition never resolves to a FALSE value. This
results in a loop that never ends. Such a loop is called an infinite loop.
Python - For Loops
The for loop in Python provides the ability to loop over the items of any
sequence, such as a list, tuple or a string.
It performs the same action on each item of the sequence.
This loop starts with the for keyword, followed by a variable that
represents the current item in the sequence.
The in keyword links the variable to the sequence you want to iterate
over.
A colon (:) is used at the end of the loop header, and the indented block
of code beneath it is executed once for each item in the sequence.

Syntax of Python for Loop


for iterating_var in sequence:
statement(s)
NOTE:- Here, the iterating_var is a variable to which the value of each
sequence item will be assigned during each iteration. Statements
represents the block of code that you want to execute repeatedly.

Flowchart of Python for Loop


Ex 1: #Write a Program Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
Python range() Function:
The Python range() function generates a sequence of numbers.
By default, the sequence starts at 0, increments by 1, and stops before
the specified number.
range() Syntax:
range(start, stop, step_size)
The start and step arguments are optional.
Start:By default 0 (Implicity)
Step_size: default 1
Stop:it is a explicity

Ex 1: #Write a Program To print numbers from 1 to n


n=int(input(“Enter a Number:”))
for i in range(1, n):
print(i)
Nested Loops:
In Python, when you write one or more loops within a loop statement
that is known as a nested loop.
The main loop is considered as outer loop and loop(s) inside the outer
loop are known as inner loops.
Ex: #Write a program implement nested Loops
months = ["jan", "feb", "mar"]
days = ["sun", "mon", "tue"]
for x in months:
for y in days:
print(x, y)
print("Good bye!")
loop control statements
Python break Statement:
Python break statement is used to terminate the current loop and resumes
execution at the next statement, just like the traditional break statement
in C.
The most common use for Python break statement is when some
external condition is triggered requiring a sudden exit from a loop. The
break statement can be used in both Python while and for loops.
Syntax of break Statement
looping statement:
condition check:
break
Flow Diagram of break Statement

Ex 1: #Write a program to implement break statement


n=int(input(“Enetr a number:”))
i=1
while(i<=n):
if(i==5):
break
Ex 2: #Write a program to implement break statement
Fruits=[“apple”,”mango”,”Banana”,”cherry”]
for item in Fruits:
if(item==”Banana”):
break
Python continue Statement
Python continue statement is used to skip the execution of the program
block and returns the control to the beginning of the current loop to start
the next iteration.
When encountered, the loop starts next iteration without executing the
remaining statements in the current iteration.
The continue statement is just the opposite to that of break. It skips the
remaining statements in the current loop and starts the next iteration.
Syntax of continue Statement
looping statement:
condition check:
continue
Flow Diagram of continue Statement

Ex 1: #Print Even Numbers from 1 to n using continue statement


n = int(input("Enter n: "))
for i in range(1, n + 1):
if i % 2 != 0: # skip odd numbers
continue
print(i)
Ex 2: #Print Odd Numbers from 1 to n using continue statement
n = int(input("Enter n: "))
for i in range(1, n + 1):
if i % 2 == 0: # skip even numbers
continue
print(i)
Python pass Statement
Python pass statement is used when a statement is required syntactically
but you do not want any command or code to execute.
It is a null which means nothing happens when it executes.
This is also useful in places where piece of code will be added later, but
a place holder is required to ensure the program runs without errors.
Example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
else with loops

In Python, loops (for and while) can have an else block.

The else block executes only if the loop finishes normally


Syntax

for loop

for variable in iterable:

# statements

else:

# executes if no break

Example
for i in range(3):
print(i)
else:
print("Loop completed")
x = 1
while loop

while condition:
# statements
else:
# executes if no break

Example
while x <= 3:
print(x)
x += 1
else:
print("Loop finished")

Functions in Python:
Definition: A Python function is a block of organized, reusable code
that is used to perform a single, related action.
Functions provide better modularity for your application and a high
degree of code reusing.
A function is a similar to a program that consists of a group of
statements that are intended to perform a specific task.

Types of Python Functions


 Built-in Functions or pre defind functions or system defind functions
 User-defined functions

Built-in Functions
Python's standard library includes number of built-in functions.
Some of Python's built-in functions are print(), int(), len(), sum(), etc.
These functions are always available, as they are loaded into computer's
memory as soon as you start Python interpreter.
User-defined functions
In addition to the built-in functions and functions in the built-in
modules, you can also create your own functions. These functions are
called user-defined functions.
Defining a Python 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 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 to Define a Python Function


def function_name( parameters ):
statement 1
statement 2
return [expression]
Example to Define a Python Function
def greetings():
#"This is docstring of greetings function"
print ("Hello World")
Calling Function
 Defining a function only gives it a name, specifies the parameters that
are to be included in the function and structures the blocks of code.

 Once the basic structure of a function is finalized, you can call it by


using the function name itself.
 If the function requires any parameters, they should be passed within
parentheses. If the function doesn't require any parameters, the
parentheses should be left empty.

Example:
greetings() #calling function
Example: To Implement different types functions and find the areas
def square():
side=float(input("Enter a square Length:"))
print("Area of square:",side*side)
def rectangle():
l=float(input("Enter rectangle Length:"))
b=float(input("Enter rectangle Breadth:"))
print("Area of Rectangle:",l*b)
def circle():
r=float(input("Enter circle radius:"))
print("Area of circle:",3.14*r**2)
#calling functions
square()
rectangle()
circle()
output:
Enter a square Length:1.5
Area of square: 2.25
Enter rectangle Length:1.5
Enter rectangle Breadth:2.5
Area of Rectangle: 3.75
Enter circle radius:1.5
Area of circle: 7.065
Return statement:
 The Python return statement marks the end of a function and specifies
the value or values to pass back from the function call.

 Return statements can return data of any type, including integers,


floats, strings, lists, dictionaries, and even other functions.

Example:
def adding(x, y):
i=x+y
return i
result = adding(16, 25)
print(f'Output of adding(16, 25) function is {result}')
Returning Multiple Values
In the Python programming language, a user can return multiple values from a
function. The following are the various methods for this.
Example: To Implement code function return multiple values
def arith(a,b):
add=a+b
sub=a-b
mul=a*b
return add,sub,mul
#calling function
x,y,z=arith(10,20)
print("Addition:",x)
print("Subtraction:",y)
print("Multiplication:",z)
Input/Output Cases in Python Functions
1. No Input – No Output
def greet():
print("Hello")
greet() # Output: Hello
- No parameters, no return. Only prints output.

2. Input – No Return Value

def add(a, b):


print("Sum =", a + b)
add(2, 3) # Output: Sum = 5
- Takes input, prints output. No return value.

3. No Input – With Return Value


def get_num():
return 10
num = get_num()
print(num) # Output: 10
- No parameters, returns a value.
4. Input – With Return Value (Best Practice)
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result) # Output: 20
- Takes input, returns output. Recommended for reusable code.
5. User Input Inside Function
def add():
a = int(input("Num1: "))
b = int(input("Num2: "))
print("Sum =", a + b)
add()
- Inputs taken inside function, prints output.
Scope of variables
scope of a variable in Python is defined as the specific area or region
where the variable is accessible to the user.
The scope of a variable depends on where and how it is defined. In
Python, a variable can have either a global or a local scope.
Types of Scope for Variables in Python
On the basis of scope, the Python variables are classified in three
categories –
1. Local Variables
2. Global Variables
1. Local Variables
 A local variable is defined within a specific function or block of code.

 It can only be accessed by the function or block where it was defined,


and it has a limited scope.
 In other words, the scope of local variables is limited to the function
they are defined in and attempting to access them outside of this
function will result in an error.
 Always remember, multiple local variables can exist with the same
name.
The following example shows the scope of local variables.
def myfunction():
a = 10
b = 20 //Local Variables
print("variable a:", a)
print("variable b:", b)
return a+b
print (myfunction()) #calling Function
2. Global Variables
 A global variable can be accessed from any part of the program, and it
is defined outside any function or block of code. It is not specific to any
block or function.
 The following example shows the scope of global variable. We can
access them inside as well as outside of the function scope.

#global variables
name = 'TutorialsPoint'
marks = 50
def myfunction():
# accessing inside the function
print("name:", name)
print("marks:", marks)
# function call
myfunction()

Nested functions
Nested (or inner) functions are functions defined within other functions that
allow us to directly access the variables and names defined in the enclosing
function.
Syntax
def outer_function():
print("Outer function")
def inner_function():
print("Inner function")
inner_function() # call inner function inside outer

Example 1: Basic Nested Function


def greet(name):
def message():
return f"Hello, {name}!"
print(message())

greet("Alice")
ouput
Hello, Alice!

Example 2: Returning Inner Function


def outer(x):
def inner(y):
return x + y
return inner

add_five = outer(5) # returns inner function


print(add_five(10)) # 15
Function Arguments

Information can be passed into functions as [Link]


are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a
comma.
Required arguments
Required arguments are the arguments that must be passed to a function
in the correct positional order.
def add(a, b):
return a + b
print(add(2, 3)) # Output: 5
print(add(2)) # Error: missing b
Positional arguments
Positional arguments are passed based on their position in the function
call.
def greet(name, age):
print(f"Hi {name}, age {age}")
greet("John", 25) # Output: Hi John, age 25
Default arguments
Default arguments have default values and are optional to pass.
def greet(name="User"):
print(f"Hi {name}")
greet() # Output: Hi User
greet("Bob") # Output: Hi Bob
Variable Length Arguments in Python
Variable length arguments allow a function to accept a variable number
of arguments. There are two types of variable length arguments in
Python:
*args (Non-Keyword Arguments)-
Captures extra positional arguments as a tuple.
- Allows a function to accept a variable number of positional arguments.
Example:
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
**kwargs (Keyword Arguments)-
Captures extra keyword arguments as a dictionary.
- Allows a function to accept a variable number of keyword arguments.
Example:
def info(**kwargs):
print(kwargs)
info(name="John", age=25) # Output: {'name': 'John', 'age': 25}
info(name="Jane", age=30, city="New York") # Output: {'name': 'Jane',
'age': 30, 'city': 'New York'}
Using *args and **kwargs Together
You can use *args and **kwargs together in a single function definition.
Example:
def func(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
func(1, 2, 3, name="John", age=25)
# Output:
# Args: (1, 2, 3)
# Kwargs: {'name': 'John', 'age': 25}
Python Main Function
Main function is like the entry point of a program. However, Python
interpreter runs the code right from the first line. The execution of the
code starts from the starting line and goes line by line. It does not matter
where the main function is present or it is present or not. Since there is
no main()
function in Python, when the command to run a Python program is
given to the interpreter, the code that is at level 0 indentation is to be
executed. However, before doing that, it will define a few special
variables.
__name__
is one such special variable. If the source file is executed as the main
program, the interpreter sets the
__name__
variable to have a value
__main__
. If this file is being imported from another module,
__name__
will be set to the module’s name.
__name__
is a built-in variable which evaluates to the name of the current module.
Example:
# Python program to demonstrate
# main() function
print("Hello")

# Defining main function


def main():
print("hey there")
# Using the special variable
# __name__
if __name__=="__main__":
main()
Output:
Hello
hey there

When above program is executed, the interpreter declares the initial


value of name as "main". When the interpreter reaches the if statement
it checks for the value of name and when the value of if is true it runs
the main function else the main function is not executed.
Python documentation
It involves two main aspects: accessing existing documentation for
Python itself and its libraries, and writing documentation for your own
code.
Accessing Python Documentation
Online Documentation: The main source is the official Python
documentation website.
Built-in Help: You can access documentation for any Python object
(module, class, function, etc.) directly in the interactive interpreter or in
a Jupyter notebook.
Use the help() function: help(len).
In an IPython environment (like Jupyter), use the ? character after an
object: len?.
Offline Access: The pydoc module can serve the documentation as a
local website or display text in the console if you have the
documentation installed locally.
Documenting Your Python Code
Effective documentation for your own code includes internal comments
and user-facing documentation strings (docstrings).
Real Python
Docstrings (Documentation Strings)
Docstrings are string literals that appear as the first statement in a
module, function, class, or method definition. They can be accessed at
runtime using the __doc__ attribute or the help() function.
Format: They are typically enclosed in triple double quotes """...""".
Conventions: PEP 257 outlines the standard conventions, including a
one-line summary followed by a blank line and a more detailed
description if needed.
Styles: Different styles are used, including Google
docstrings and NumPy-style docstrings, which provide structured ways
to list parameters, return values, and exceptions.

You might also like