PYTHON Concepts
PYTHON Concepts
1. Python While Loop A while loop in Python iterates till its condition becomes False. In other words, it executes the
block of statements until the condition it takes is true.
Syntax
while <Logical Expression>:
loop body
When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code
under it is executed. After that, the condition is checked again. This continues until the condition becomes false. Then
the first statement, if any after the loop is executed. Remember to indent all statements under the loop equally.
e.g.
>>> a=3
>>> while(a>0):
print(a)
a-=1
Output
3
2
1
(a) An Infinite Loop Be careful while using a while loop. Because if you forget to increment or decrement the counter
variable in Python, or write flawed logic, the condition may never become false. In such a case, the loop will run
infinitely, and the conditions after the loop will starve. To stop execution, press Ctrl+C. However, an infinite loop may
sometimes be useful.
(b) The else statement for while loop A while loop may have an else statement after it. When the condition becomes
false, the block under the else statement is executed. However, it doesn’t execute if you break out of the loop or if an
exception is raised.
e.g.
>>> a=3
>>> while(a>0):
print(a)
a-=1
else:
print("Reached 0")
Output
3
2
1
Reached ()
In the following code, we put a break statement in the body of the while loop for a==1. So, when that happens, the
statement in the else block is not executed.
e.g.
>>> a=3
>>> while(a>0):
print(a) a-=1
if(a==1):
break
else:
print("Reached 0")
Output
32
(c) Single Statement while Like an if statement, if we have only one statement in while loop’s body, we can write it all in
one line.
e.g.
>>> a=3
>>> while a>0:
print(a);
a-=1;
Output
3
2
1
You can see that there were two statements in while loop’s body, but we used semicolons to separate them. Without
the second statement, it would form an infinite loop.
2. Python for Loop Python for loop can iterate over a sequence of items. The structure of a for loop in Python is
different than that in C++ or Java.
Library Functions: These functions are already built in the python library.
Functions defined in modules: These functions defined in particular modules. When you want to use these
functions in program, you have to import the corresponding module of that function.
User Defined Functions: The functions those are defined by the user are called user defined functions.
Library Functions in Python:
These functions are already built in the library of python. For example: type( ), len( ), input( ) etc.
Functions defined in modules:
Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49) 7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3) 82
3 floor( ) Returns the lower integer >>>math.floor(81.3) 81
4 pow( ) Calculate the power of a number >>>math.pow(2,3) 8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6) 5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3) 20.085536923187668
Function in random module:
randint( )- function generates the random integer values including start and end values.
Syntax: randint(start, end)- It has two parameters. Both parameters must have integer values.
Example:
import random n=random.randint(3,7) *The value of n will be 3 to 7.
User defined functions:
Syntax to create user defined function
def function_name([comma separated list of parameters]):
statements….
statements….
Key points to remember:
Keyword def marks the start of function header
Function name must be unique and follows naming rules same as for identifiers
Function can take arguments. It is optional
A colon(:) to mark the end of function header
Function can contains one or more statement to perform specific task
An optional return statement to return a value from the function.
Function must be called/invoked to execute its code
One or more valid python statements that make up the function body.
Statements must have same indentation level
Example:
def display(name):
print("Hello " + name + " How are you?")
User defined function can be:
Function with no arguments and no return
Function with arguments but no return value
Function with arguments and return value
Function with no argument but return value
Function Parameters: functions has two types of parameters:
Formal Parameter: Formal parameters are written in the function prototype and function header of the
definition. Formal parameters are local variables which are assigned values from the arguments when the function
is called.
Actual Parameter: When a function is called, the values that are passed in the call are called actual parameters.
At the time of the call each actual parameter is assigned to the corresponding formal parameter in the function
definition.
Types of Arguments:
There are 4 types of Actual Arguments allowed in Python:
1. Positional arguments: are arguments passed to a function in correct positional order
2. Default arguments: we can provide default values for our positional arguments. In this case if we are
not passing any value then default values will be considered.
3. Keyword arguments: allows to call function with arguments in any order using name of the
arguments.
4. Variable length arguments: allow to call function with any number of arguments.
Calling the function:
Once we have defined a function, we can call it from another function, program or even the Python prompt. To
call a function we simply type the function name with appropriate parameters.
Syntax:
Function_name(parameter)
Example:
ADD(10,20)
The return statement:
The return statement is used to exit a function and go back to the place from where it was called. There are two
types of functions according to return statement:
a. Function returning some value
b. Function not returning any value
a. Function returning some value :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2 Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple print(S)
Output: (7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately print(s1, s2, s3)
Output:
7 7 11
b. Function not returning any value : The function that performs some operations but does not return any
value, called void function.
def message():
print("Hello")
m=message()
print(m)
Output: Hello
None
Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables
defined inside a function is not visible from outside. Hence, they have a local scope.
There are two types of scope for variables:
i) Local Scope
ii) Global Scope
Local Scope: Variable used inside the function. It cannot be accessed outside the function. In this scope, the
lifetime of variables inside a function is as long as the function executes. They are destroyed once we return
from the function. Hence, a function does not remember the value of a variable from its previous calls.
Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the period
throughout which the variable exits in the memory.
Example 1
Example 2:
def func2():
A=2
print("Value inside function:",A)
A=5
func2()
print("Value outside function:",A)
OUTPUT:
Value inside function: 2
Value outside function: 5
Here, we can see that the value of A is 5 initially. Even though the function func2() changed the value of A to 2,
it did not affect the value outside the function.
This is because the variable A inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value
of variables outside the function, they must be declared as global variables using the keyword global.