[go: up one dir, main page]

0% found this document useful (0 votes)
27 views18 pages

Unit 4 1

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)
27 views18 pages

Unit 4 1

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/ 18

Unit-4

Creating Python Programs: Input and Output Statements, Control statements


(Branching, Looping, Conditional Statement, Exit function, Difference between
break, continue and pass.), Defining Functions, default arguments.
Input and Output Statements
How to print/display a statement in Python
In python a statement is printed with the help of print() method.
The syntax to use print() is as follow :
>>>print(“message to be printed”) # To print a message
Or
>>>print(‘message to be printed’) # To print a message
Or
>>>print(variable_name) #To print the value of the variable
Or
>>>print(“message to be printed”, variable_name) #To print the value of the variable with some
message
Or
>>>print(‘message to be printed’, variable_name) #To print the value of the variable with some message
How to input a value for the user in Python
A value can be input from the user with the help of input() method.
Syntax:
variable_name = input(“Enter any number”)
Program to adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Python program to add Two Numbers with User Input
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Here we use the built-in function input () to take the input. Since, input() returns a string, we convert the
string into number using the float() function. Then, the numbers are added.
It can be changed to other data types by using type.
e.g. age = int(input(“Enter your age”))
percentage= float(input(“Enter you percentage”))
We can also write the above program as given bellow:
# Store input numbers
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
sum = num1 + num2 # Add two numbers
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # Display the sum
Alternative to this, we can perform this addition in a single statement without using any variables as
follows.

print('The sum is %.1f' %(int(input('Enter first number: ')) +int(input('Enter second number: '))))

Python Program to calculate the square root


# change this value for a different result
num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
In this program, we store the number in variable num and find the square root using the ** exponent
operator. The program works for all positive real numbers.
But for negative or complex numbers, it can be done as follows.
Find square root of real or complex numbers
# Importing the complex math module
import cmath
num = 1+2j
# To take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

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)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("Jan", "Feb", "Mar")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Hello"
for i in s:
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("%s %d" % (i, d[i]))

# Iterating over a set


print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
Using else statement with for loops:
We can also combine else statement with for loop like in while loop. But as there is no condition in for
loop based on which the execution will terminate so the else block will be executed immediately after for
block finishes execution.
# Python program to illustratecombining else with for
list = ["apple", "orange", "banana"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
while loop
A while loop is used to execute a block of statements repeatedly until a given condition is satisfied.
And when the condition becomes false, the line immediately after the loop in the program is executed.
Syntax:
while expression:
statement(s)

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 ")

Using else statement with while loops


As discussed above, while loop executes the block until a condition is satisfied. When the condition
becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or
if an exception is raised, it won’t be executed.
Syntax
while condition:
# execute these statements
else:
# execute these statements
Example
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
Nested Loops
Python programming language allows to use one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
We can also put any type of loop inside of any other type of loop. For example, a for-loop can be inside a
while loop or vice versa.
Example
# Python program to illustrate nested for loops in Python
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
OP:
1
22
333
4444
Control Statements
In Python, Loops are used to iterate repeatedly over a block of code. In order to change the way a loop is
executed from its usual behavior, control statements are used. Control statements are used to control the
flow of the execution of the loop based on a condition. There are many types of control statements are used
in Python to change the way a loop is executed from its usual behavior.
 Break statement
 Continue statement
 Pass statement
Break statement
In Python, the break statement is employed to end or remove the control from the loop that contains the
statement. It is used to end nested loops (a loop inside another loop), which are shared with both types of
Python loops. The inner loop is completed, and control is transferred to the following statement of the
outside loop.
Ex :
for char in 'Python':
if (char == 'h'):
break
print("Current character: ", char)
Ex:
Details = [[19, 'Itika', 'Jaipur'], [16, 'Aman', 'Bihar']]
for candidate in Details:
age = candidate[0]
if age <= 18:
break
print (f"{candidate[1]} of state {candidate[2]} is eligible to vote")
Continue statement
When a program encounters a continue statement in Python, it skips the execution of the current iteration
when the condition is met and lets the loop continue to move to the next iteration. It is used to continue
running the program even after the program encounters a break during execution.
Ex: for char in 'python':
if (char == 'y'):
continue
print("Current character: ", char)
Ex :
for letter in 'Flexi ple':
if letter == ' ':
continue
print ('Letters: ', letter)
Pass statement
The pass statement is a null operator and is used when the programmer wants to do nothing only when the
statement is required syntactically (or when the condition is satisfied). This control statement in Python does
not terminate or skip the execution; it simply passes to the next iteration.
A loop cannot be left empty otherwise the interpreter will throw an error and to avoid this, a programmer
can use the pass statement.
for char in 'Python':
if char == 't':
pass
print('Currect character: ', char)

Difference between continue and pass statement


Continue Pass
The continue statement is used to reject
the remaining statements in the current
1 iteration of the loop and moves the Pass Statement is used when a statement is required
control back to the start of the loop. syntactically.
2 It returns the control to the beginning of When we execute the pass statements then nothing
the loop. happens.
3 It can be used with while loop and for It is a null Operation.
loop.
4 Its syntax is -: Its syntax is -:
continue pass
5 It is mainly used inside a condition in a The pass statement is discarded during the byte-
loop compile phase
Python pass Vs break Vs continue Statement
In Python, break is used to exit a for loop or a while loop when certain condition is satisfied.
Whereas continue statement will just by pass the current iteration and continue with the next iteration.
However, pass statement is used as a place-holder statement that does nothing.
An appropriate control flow selection can be made for an application only if one is clear with the difference
between pass vs break vs continue. The following example clearly shows the comparison
of pass vs break vs continue.
The table below differentiates between pass Vs break Vs continue statement in Python.
Break Continue Pass
break statement is used to continue statement is used to skip the pass statement is used as a
bring the control out of remaining statements in the current place-holder that does nothing.
inner most loop. iteration of the loop and moves the
control back to the start of the loop.
Syntax : break Syntax : continue Syntax : pass
Brings control out of Brings control to the beginning of loop Considered as a null statement.
loop. So control continues its
execution in normal way.
Can be used with looping, to
Can be used with looping Can be used with the looping
declare empty function and
statements statements.
empty class.

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")

Parameters of exit() in Python

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.

print() - prints the string inside the quotation marks


sqrt() - returns the square root of a number
pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we must include the module
inside our program.
Example, sqrt() is defined inside the math module.
# pow() computes the power
x = pow(2, 3)
print("2 to the power 3 is",)
# sqrt computes the square root
import math
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
or
We can also write as given bellow:
from math import sqrt
# sqrt computes the square root
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)

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

To learn more python library function open the following links.


https://www.javatpoint.com/python-built-in-functions
or
https://www.programiz.com/python-programming/methods/built-in
User-defined 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.
Advantages of user-defined functions
 User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.

 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.

Syntax of Python Function

def function_name( parameters ):


# block of code / function body

return value

Here,

 The beginning of a function header is indicated by a keyword called def.


 The function header is terminated by a colon (:).
 function_name: Function name is the name of the function. We can give any name to function.
 parameter: Parameter is the value passed to the function. We can pass any number of parameters.
Function body uses the parameter’s value to perform an action. However, they are optional
 function_body: The function body is a block of code that performs some task. This block of code is
nothing but the action we wanted to carry out.
 return value: Return value is the output of the function.
We can use a documentation string called docstring in the short form to explain the purpose of the function.
Example of User-Defined Function
def square( num ): #function header
"""
This function computes the square of the number.
"""
return num**2
result = square(6) #call function
print( "The square of the given number is: ", result )
Output:
The square of the given number is: 36
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must be
passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in the program. To call
a function, use the function name followed by parenthesis.
Ex:
def my_function():
print("Hello from a function")
my_function()
The following is an example of how to use the a_function function.
Example Python Code for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)
# Calling the function we defined
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length of the string Functions is: 9
Length of the string Python is: 6
Function Arguments
The argument is a value or a variable, or an object that we pass to a function or method call. In Python, there
are four types of arguments allowed.
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
Default Arguments
Information can be passed into functions as arguments. Arguments are specified after the function name,
inside the parentheses. We can add as many arguments as we want, just separate them with a comma.
A default argument is a kind of parameter that takes default value as input if no value is supplied for the
argument when the function is called. We can assign a default value to an argument in function definition
using the = assignment operator.
Python code to demonstrate the use of default arguments
Example 1:# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output: Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
Example 2:# Function definition is here
def printinfo( name, age = 35 ):
''' This prints a passed info into this function'''
print ("Name: ", name)
print ("Age ", age)
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Output: Name: miki
Age 50
Name: miki
Age 35
Example 3:# function with default argument
def message(name="Guest"):
print("Hello", name)
# calling function with argument
message("John")
# calling function without argument
message()
Output: Hello John
Hello Guest
When we call a function with an argument, it will take that value.

For more examples can refer this link: https://pynative.com/python-functions/

You might also like