[go: up one dir, main page]

0% found this document useful (0 votes)
30 views12 pages

Unit III

Right

Uploaded by

anmo14251425
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)
30 views12 pages

Unit III

Right

Uploaded by

anmo14251425
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/ 12

iamriteshkandari 9259069231 riteshkandarics@gmail.

com

Python if...else Statement


Decision making is required when we want to execute a code only if a certain
condition is satisfied.
The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax


if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only
if the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body
starts with an indentation and the first unindented line marks the end.

Example: Python if Statement


# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number This is always printed This is also always printed.

Python if...else Statement


Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the body of if only
when the test condition is True.
iamriteshkandari 9259069231 riteshkandarics@gmail.com
If the condition is False, the body of else is executed. Indentation is used to separate
the blocks.
# Program checks if the number is positive or negative and displays an appropriate
message
num = 3
# Try these two variations as well. # num = -5 # num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero

Python if...elif...else Statement


Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the
condition for if is False, it checks the condition of the next elif block and so on. If all
the conditions are False, the body of else is executed. Only one block among the
several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
In this program, we check if the number is positive or negative or zero and display
an appropriate message
num = 3.4
# Try these two variations as well: # num = 0 # num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
When variable num is positive, Positive number is printed.
iamriteshkandari 9259069231 riteshkandarics@gmail.com
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This
is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is
the only way to figure out the level of nesting. They can get confusing, so they must
be avoided unless necessary.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number

Python for Loop


The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
iamriteshkandari 9259069231 riteshkandarics@gmail.com
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
When you run the program, the output will be:
The sum is 48

The range() function


It is used to create a list containing a sequence of numbers starting with the start
and ending with one less than the stop. We can generate a sequence of numbers
using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size).
step_size defaults to 1 if not provided.

Statement Value Generated


range(10) 0,1,2,3,4,5,6,7,8,9
range(5,10) 5,6,7,8,9
range(9,3,-1) 9,8,7,6,5,4
range(10,1,-2) 10,8,6,4,2

Python while Loop


The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate
beforehand.

Syntax of while Loop in Python


while test_expression:
Body of while
In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
# Program to add natural numbers up to sum =1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
iamriteshkandari 9259069231 riteshkandarics@gmail.com
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
When you run the program, the output will be:
Enter n: 10 The sum is 55

Python break and continue


In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes
we wish to terminate the current iteration or even the whole loop without checking
test expression. The break and continue statements are used in these cases.
The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop),
the break statement will terminate the innermost loop.
Syntax of break
Break
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
Output
s t r The end
In this program, we iterate through the "string" sequence. We check if the letter is
i, upon which we break from the loop. Hence, we see in our output that all the letters
up till i gets printed. After that, the loop terminates.

The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.
iamriteshkandari 9259069231 riteshkandarics@gmail.com
Syntax of Continue
continue
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been
replaced with continue.
We continue with the loop, if the string is i, not executing the rest of the block.
Hence, we see in our output that all the letters except i gets printed.

Python pass statement


In Python programming, the pass statement is a null statement. The difference
between a comment and a pass statement in Python is that while the interpreter
ignores a comment entirely, pass is not ignored.
However, nothing happens when the pass is executed. It results in no operation
(NOP).
Syntax of pass
pass
We generally use it as a placeholder.
suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
give an error. So, we use the pass statement to construct a body that does nothing.

Example: pass Statement


'''pass is just a placeholder for functionality to be added later.'''
sequence = {'p', 'a', 's', 's'}
for val in sequence:
iamriteshkandari 9259069231 riteshkandarics@gmail.com
pass
We can do the same thing in an empty function or class as well.
def function(args):
pass
class Example:
pass

Functions
A function is a group of statements that exists within a program for the purpose of
performing a specific task. Instead of writing a large program as one long sequence
of instructions, it can be written as several small functions, each performing a
specific part of the task. They constitute line of codes that are executed sequentially
from top to bottom by python interpreter.
Functions can be categorized into the following three types:
i. Built-in
ii. Modules
iii. User-defined
Built in functions are the predefined functions that are already available in Python.
Functions provide efficiency and structure to a programming language. Python has
many useful built in functions to make programming easier, faster and more
powerful.

Some built-in Functions:


A. Type conversion functions: Python provides built in functions that convert
values from one type to another, which are termed as type conversion
functions.
i. int()
ii. str()
iii. float()
B. input function: It enables us to accept an input string from the user without
evaluating its value. It provides the most common way to gather input from
the keyboard. The function input() continues to read input text from the user
until it encounters a new line.
for example:
name= input(“Enter a name:”)
print(“Welcome”,name+”Pleasure to meet you”)
C. eval function: This function is used to evaluate the value of a string.
iamriteshkandari 9259069231 riteshkandarics@gmail.com
for example: x=eval(‘45+10’)
print(x)
D. min and max functions: These are used to find the maximum and minimum
value respectively out of several values. The max() function takes two or more
arguments and returns the largest one.
For example: >>>max(9,12,,6,15)
15
The min() function takes two or more arguments and returns the smallest
item.
For example: >>>min(23,-109,5,2)
-109
E. abs function: The abs() function returns the absolute value of a single number
and always returns a positive value.
F. type function: If you wish to determine the type of a variable i.e. what type
of value does it hold/print to, then type() function can be used.
for example: >>>type(10)
<class ‘int’>
G. len function: It returns the length of an object. The argument may be a
sequence (string,tuple,list) or a dictionary.
for example: >>>x=[1,2,3,4,5]
>>>len(x)
5
H. range function: The range() function is used to define a series of numbers and
is particularly useful in for loops.

Modules
A module is a file containing functions and variables defined in separate files. A
module is simply a file that contains python code or a series of instructions. When
we break a program into modules, each module should contain functions that
perform related tasks. There are some commonly used modules in python that are
used for certain predefined tasks and they are called libraries.
Modules also make it easier to reuse the same code in more than one program. If
we have written a set of functions that is needed in several different programs, we
can place those functions in a module. Then, we can import the module in each
program that needs to call one of the functions.
iamriteshkandari 9259069231 riteshkandarics@gmail.com
Python language provides two important methods to import modules in a program
which are as follows:
i. import statement: To import entire module
ii. from: To import all functions
iii. import: To use modules in a program, we import them using the import
statement.
For example: import math

Math module:
i. ceil(x): returns the smallest integer that is greater than or equal to x.
ii. floor(x): returns the largest integer that is less than or equal to x.
iii. pow(x,y): returns the value of Xy
iv. fabs(): returns the absolute value(positive value)
v. sqrt(x): returns the square root of x
vi. log10(x): returns the base-10 logarithm of x.
vii. cos(x): returns the cosine of x in radians
viii. sin(x): returns the sin of x in radians
ix. tan(x): returns the tangent of x in radians

String module:
i. isalpha(): returns true if the string contains only letters
ii. Isdigit(): returns true if the string contains only digits.
iii. lower(): Convert all the uppercase letters in the string to lowercase
iv. islower(): returns true if all the letters in the string are in lowercase
v. upper(): Convert lowercase letters in the string to uppercase
vi. isupper(): returns true if the string is in uppercase
vii. ord(): returns the ASCII code of the character
viii. chr(): returns character represented by the inputted ASCII number

User Defined Functions


A function is a set of statements that performs a specific task, a common structuring
element that allow you to use a piece of code repeatedly in different parts of a
program.
A user defined python function is created or defined by the def statement followed
by the function name and parentheses as shown in the given syntax:
iamriteshkandari 9259069231 riteshkandarics@gmail.com

A function definition consists of the following components.


1. Keyword def marks the start of function header.
2. A function name to uniquely identify it.
3. Parameters through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. One or more valid Python statements that make up the function body.
6. An optional return statement to return a value from the function.

Parameters and Arguments in Functions


Parameters are the values provided in the parentheses when we write function
header. These are the values required by function to work.
If there is more than one value required by the function to work upon, then all of
them will be listed in parameter list separated by comma.
def s_i(p,r,t): #Parameters receive by the function
return (p*R*t/100)

An argument is a value that is passed to function when it is called. In other words,


arguments are the values provided in function call/invoke statement.
>>>s_i(40000,30,5)
60000.0
They are:
1. Positional arguments
2. Default arguments
iamriteshkandari 9259069231 riteshkandarics@gmail.com
3. Keyword arguments
4. Variable length arguments
❖ Positional arguments: Positional arguments are arguments passed to a
function in correct positional order.
❖ Default arguments: A Default argument is an argument that assumes a
default value if a value is not provided in the function call for that argument.
If we are not passing any name, then only default values will be considered.
❖ Keyword arguments: If there is a function with many parameters and we
want to specify only some of them in function call, then value for such
parameters can be provided by using their name instead of the
position(order). These are called Keyword arguments or named arguments.
❖ Variable length arguments: In certain situation, we can pass variable number
of arguments to a function. Such type of arguments are called Variable length
arguments. Variable length arguments are declared *(asterisk) symbol in
Python.
>>>def f1(*n):

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
Scope of variables refers to the part of the program where it is visible, i.e area where
you can refer(use) it. Two types of scope of variables-global scope and local scope
➢ Global
• Names assigned at the top level of a module, or directly in the
interpreter
• Names declared global in a function
➢ Local
• Names assigned inside a function definition or loop

For Example:
>>>a=2 #a is assigned in the interpreter, so its Global
>>>def f(x): # x is assigned in the interpreter, so its Local
y=x+a #y is assigned in the interpreter, so its Local
return y
>>>p=f(5)
>>>print(p)
7
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Recursion:
Recursion is one of the most powerful tools in a programming language. It is a
function calling itself again and again. Recursion is defined as defining anything in
terms of itself. In other words, it is a method in which a function calls itself one or
more times in its body.
Example:
def fact(x,n):
if n==0:
return 1
else:
return x*power(x,n-1)
a=5
Print(fact(a,4))

You might also like