UNIT-II-1
UNIT-II-1
1. Expression
2. Input & Output
3. Comments, line & Indentation
4. Quotations
5. Tuple Assignment
6. Operators
7. Precedence Of operator
8. Function: Definition & use
Types of function, Flow of execution, Parameters & arguments, modules
9. Conditional Statement
10. Iteration/Control Statement
11. Fruitful Function vs Void Function
12. Parameters/Arguments
13. Return values, variable scope, function composition
Expressions: -
An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend
TUPLE ASSIGNMENT
An assignment to all of the elements in a tuple using a single assignment statement.
Python has a very powerful tuple assignment feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple on the right of the
assignment.
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments. This
feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right
have to be the same
>>> (a, b, c, d) = (1, 2, 3) ValueError: need more than 3 values to unpack
Example: -It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable.
For example, to swap a and b:
a=2;
b=3
print(a,b)
temp = a
a=b
>>> b = temp
print(a,b)
Tuple assignment solves this problem neatly: (a, b) = (b, a)
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a specific programming language. Python provides a variety of operators, which are
described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two
operands. It includes + (addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**) operators. Assume a=10 and b=5
Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
Greater than or
equal to: True if the
left operand is greater a >= b is true
than or equal to the
>= right
Example
a=10
b=5 a>b=>
print("a>b=>",a>b) a>b=>
print("a>b=>",a<b) a==b=>
print("a==b=>",a==b) a!=b=>
print("a!=b=>",a!=b) a>=b=>
print("a>=b=>",a<=b) a>=b=>
print("a>=b=>",a>=b)
Logical Operator :
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
and If both the operands are true then condition (a and b) true
Logical AND becomes true..
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
Bitwise Operators :
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows –
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
Example
a = 60
b = 13
c=0
c = a & b;
print "Line 1 - Value of c is ", c
c = a | b; print "Line 2 - Value of c is ", c
c = a ^ b;
print "Line 3 - Value of c is ", c
c = ~a;
print "Line 4 - Value of c is ", c
c = a << 2;
print "Line 5 - Value of c is ", c
c = a >> 2;
print "Line 6 - Value of c is ", c
Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
Let, x=[5,3,6,4,1].
To check particular item in list or not, in and not in operators are used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of the memory.
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.
-For mathematical operators, Python follows mathematical convention. –
The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction) is a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2
* (3-1)is 4, and (1+1)**(5-2) is 8
You can also use parentheses to make an expression easier to read, as in (minute *
100) / 60, even if it doesn’t change the result.
Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2
is 18, not 36.
Multiplication and Division have higher precedence than Addition and Subtraction. So
2*3-1 is 5, not 4, and 6+4/2 is 8, not 5. Operators with the same precedence are
evaluated from left to right (except exponentiation).
Examples
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15
find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1
Function
A function is a block of code which only runs when it is called.You can pass data, known as
parameters, into a function.A function can return data as a result.
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer.
It cannot be modified.
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2… statement n
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
Flow of Execution:
The order in which statements are executed is called the flow of execution.
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
Arguments :
Arguments are the value(s) provided in function call/invoke statement.
List of arguments should be supplied in same way as parameters are listed.
Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
Example: my_add(x,y)
RETURN STATEMENT:
The return statement is used to exit a function and go back to the place from where it
was called.
If the return statement has no arguments, then it will not return any values. But exits
from function.
Syntax: return[expression]
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output: 9
Function Prototypes:
I. Function without arguments and without return type
II. Function with arguments and without return type
III. Function without arguments and with return type
IV. Function with arguments and with return type
Function without arguments and without return type
In this type no argument is passed through the function call and no output is return to
main function.
The sub function will read the input values perform the operation and print the result
in the same block.
Function with arguments and without return type
Arguments are passed through the function call but output is not return to the main
function.
Function without arguments and with return type
In this type no argument is passed through the function call but output is return to the
main function.
Function with arguments and with return type
In this type arguments are passed through the function call and output is return to the
main function.
Without Argument
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
With Argument
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
MODULES:
A module is a file containing Python definitions ,functions, statements and instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or variables
in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user defined
modules.
Every module contains many function.
To access one of the function , you have to specify the name of the module and the
name of the function separated by dot . This format is called dot notation.
Syntax:
import module_name
module_name.function_name(variable)
import math
x=math.sqrt(25)
print(x)
Conditional (if):
The if statement contains a logical expression using which data is compared and a decision is
made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code after
the end of the if statement(s) is executed.
if Statement Flowchart:
Example:
Python if Statement
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Alternative If(If-Else):
An else statement can be combined with an if statement. An else statement contains the block
of code (false block) that executes if the conditional expression in the if statement resolves to
0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else Statement
following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
Nested if Statement
if statement can also be checked inside other if statement. This conditional statement is called
a nested if statement. This means that inner if condition will be checked only if outer if
condition is true and by this, we can see multiple conditions to be satisfied.
if test expression:
Body of if stmts
if test expression:
Body of elif stmts
else:
Body of else stmts
else:
Body of else stmts
if num > 5:
print("Bigger than 5")
Iteration:
A loop statement allows us to execute a statement or group of statements multiple times as long
as the condition is true. Repeated execution of a set of statements with the help of loops is
called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is repeatedly
executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart:
Example
i=1
while i<=6:
print("Nishita Degree college")
i=i+1
i=1
while (i < 10):
print (“The Count is ”, i)
i = i+1
For loop:
Python for loop is used for repeated execution of a group of statements for the desired number
of times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable
objects
Syntax:
for var in sequence:
Statement(s)
FlowChart
Example
List=[1,2,3,4,5]
For I in list:
Print(i)
For I in range(1,6):
Print(i)
Break
The break statement terminates the loop containing it and control of the program flows to the
statement immediately after the body of the loop. If break statement is inside a nested loop
(loop inside another loop), break will terminate the innermost loop.
Flowchart
Syntax
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
Continue
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.
Flowchart
The following shows the working of continue statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
Continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Fruitful Function
We write functions that return values, which we will call fruitful functions. We have seen the
return statement before, but in a fruitful function the return statement includes a return value.
This statement means: "Return immediately from this function and use the following
expression as a return value."
(or)
Any function that returns a value is called Fruitful function. A Function that does not return a
value is called a void function
By applying fruitful functions, you can make some repetitive tasks easier, not write redundant
code, and make your Python programs more flexible. Whether you are going to calculate totals,
work with complicated algorithms, or even solve some user inputs, fruitful functions make
everything in the process smoother.
Example:
def calculate_area(length, width):
area = length * width
return area
rect_area = calculate_area(10, 5)
print("The area of the rectangle is:", rect_area)
In this function, calculate_area, we accept two parameters: length and width. The line area =
length * width computes the area of the rectangle. The return statement then sends this value
back to the caller.
Void Functions
Void functions are those that do not return any value after their calculation is complete. These
types of functions are used when the calculations of the functions are not needed in the actual
program. These types of functions perform tasks that are crucial to successfully run the program
but do not give a specific value to be used in the program.
Example
function add_v(a, b);
c = a + b;
print(c);
end
# Function Call
add_v(3, 4)
Functions returning some value are Functions that does not return any value are
called as fruitful functions. called as void functions.
Fruitful functions return some Void functions return legal empty value of
computed result in terms of a value. Python, which is None, to their caller
Variable Scope
In Python, variable scope is the area or context in which a variable is declared and accessible.
It lays down the guidelines for how a variable must be displayed and used in different Python
code sections. There are two types of variable scopes in Python:
1. Local
2. Global
1. Local Scope
The variables we define within a function or block of code come under local scope. They are
not used or visible outside the function or code block but can be accessed by that function or
block. As the block or function ends, the local variables are also deleted. Therefore, we can’t
access their values.
Example
def calculate_square(number):
return result
square_of_5 = calculate_square(5)
2. Global Scope
The variables that we can define outside of a function at the top of the script module are a
part of the global scope. The global variables of a script or module can be accessed from
anywhere, inside or outside functions. We use the global keyword to ensure that you refer to a
global variable rather than defining a new local variable using the same name to edit a global
variable within the function.
Example
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Function composition
Function composition is the way of combining two or more functions in such a way that the
output of one function becomes the input of the second function and so on. For example, let
there be two functions “F” and “G” and their composition can be represented as F(G(x))
where “x” is the argument and output of G(x) function will become the input of F() function.
def multiply_by_two(x):
return x * 2
def add_five(y):
return y + 5