Unit 4 1
Unit 4 1
print('The sum is %.1f' %(int(input('Enter first number: ')) +int(input('Enter second number: '))))
In the above program, we use the sqrt() function in the cmath (complex math) module.
If we want to take complex number as input at runtime, we have to use the eval() function instead
of data type (int /float).
The eval() method can be used to convert complex numbers as input to the complex objects in Python.
Python Conditional Statements
Python provides decision-making statements that to make decisions within a program for an application based on
the user requirement.
Python provides various types of conditional statements:
Statement Description
if Statements It consists of a Boolean expression which results are either TRUE or FALSE,
followed by one or more statements.
if else It also contains a Boolean expression. The if statement is followed by an optional
Statements else statement & if the expression results in FALSE, then else statement gets
executed. It is also called alternative execution in which there are two possibilities
of the condition determined in which any one of them will get executed.
Nested We can implement if statement and or if-else statement inside another if or if - else
Statements statement. Here more than one if conditions are applied & there can be more than
one if within elif.
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 . The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
Flowchart
Syntax:
if condition/Expression:
# Statements to execute if condition is true
Example
a = 15
if a > 10:
print("a is greater”)
Example 2:
if 10 > 5:
print("10 greater than 5")
# Indentation (White space) is used to delimit the block of code.
print("Program ended")
[As the condition present in the if statement is false. So, the statement below the if statement is
executed.]
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.
Flow Chart:-
Syntax: if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example:
# if..else statement example
Example
a = 15
b = 20
if a > b:
print("a is greater")
else:
print("b is greater")
We can also chain if..else statement with more than one condition.
# if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
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.
Flow chart:-
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
# Nested if statement example
num = 10
if num > 5:
print("Bigger than 5")
if num <= 15:
print("Between 5 and 15")
if-elif 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. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if-statement.
Flow Chart:-
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example:-
# if-elif statement example
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
Loop statements
Looping simplifies complicated problems into smooth ones. It allows programmers to modify the flow of
the program so that rather than writing the same code, again and again, programmers are able to repeat
the code a finite number of times. A looping statement contains instructions that continually repeat until a
certain condition is reached.
In Python, there are three different types of loops:
for loop
while loop
Nested loop
For loop
Generally for loops are used for sequential traversal.
For example: traversing a list or string or array etc.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).
There is “for in” loop which is similar to for each loop in other languages.
Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over a range and iterations.
Example:
n=4
for i in range(0, n):
print(i)
Example with List, Tuple, string, and dictionary iteration using for Loops
# Python program to illustrate
# Iterating over a list
print("List Iteration")
l = ["Sunday", "Monday", "Tuesday"]
for i in l:
print(i)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code.[Python uses indentation as its method of grouping
statements.]
Example:
count = 0
while (count < 3):
count = count + 1
print("Hello ")
The built-in Python function exit(), quit(), sys.exit(), and os. exit() are most frequently used to end a
program.
exit() function in Python
The exit () is defined in site.py and it works only if the site module is imported so it should be used in the
interpreter only.
exit() Function
We can use the in-built exit() function to quit and come out of the execution loop of the program in Python.
Example:
number = 7
if number < 8:
# exits the program
print(exit)
exit()
else:
print("number is not less than 8")
It is like a synonym for quit() to make Python more user-friendly. It too gives a message when printed:
# Python program to demonstrate exit()
for i in range(10):
# If the value of i becomes 5 then the program is forced to exit
if i == 5:
# prints the exit message
print(exit)
exit()
print(i)
quit() Function
quit() function is another in-built function, which is used to exit a python program. When the interpreter
encounters the quit() function in the system, it terminates the execution of the program completely.
Syntax: quit()
Example:
number = 7
if number < 8:
# exits the program
print(quit)
quit()
else:
print("number is not less than 8")
The exit() and quit() functions don't take any parameter as input.
Function in Python
A function is a block of organized, reusable code that is used to perform a single, related action.
Types of Functions:
There are two types of functions in python
Standard library function: These are build-in functions in python that are available to use.
User-defined function: We can create our own functions based on our requirements.
Python Library Functions
The standard library functions are the built-in functions that can be used directly in our program.
Since sqrt() is defined inside the math module, we need to include it in our program.
abs():
The abs()Returns the absolute value of a number . If the number is a complex number, abs() returns its
magnitude.
Example
number = -20
print(abs(number))
Output: 20
any():
The any() function returns True if any element of an iterable is True if not, it returns False.
Example
boolean_list = ['True', 'False', 'True']
# check if any element is true
result = any(boolean_list)
print(result)
Output: True
all():
The all() function returns True if all elements in the given iterable are true, if not it returns False.
Example
boolean_list = ['True', 'True', 'True']
result = all(boolean_list) # check if all elements are true
print(result)
Output: True
float():
float() method returns a floating point number from a number or a string
num=25
newnum=float(num)
print(newnum)
Output: 25.0
eval():
The eval() parses the expression passed to this method and runs the python expression within the
program.
len()
The python len() function is used to return the length (the number of items) of an object.
strA = 'Python'
print(len(strA))
Output: 6
round():
The round() function rounds off the digits of a number and returns the floating point number.
Example
print(round(10))
print(round(10.8))
print(round(6.6))
print(round(6.5))
Output:
10
11
7
6
If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
By including functions, we can prevent repeating the same code block repeatedly in a program.
Python functions, once defined, can be called many times and from anywhere in a program.
Programmers’ working on large project can divide the workload by making different functions.
Steps to define function in Python.
Use the def keyword with the function name to define a function.
Next, pass the number of parameters as per requirement. (Optional).
Next, define the function body with a block of code. This block of code is nothing but the action you
wanted to perform.
In Python, no need to specify curly braces for the function body. The only indentation is essential to
separate code blocks. Otherwise, it will throw an error.
return value
Here,