Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Python Unit 3

The document discusses input, output, and control flow statements in Python. It explains functions like print(), input(), if/else statements, loops like for and while, and break, continue, and pass statements. It also covers defining user-defined functions in Python.

Uploaded by

samreen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Python Unit 3

The document discusses input, output, and control flow statements in Python. It explains functions like print(), input(), if/else statements, loops like for and while, and break, continue, and pass statements. It also covers defining user-defined functions in Python.

Uploaded by

samreen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 3

Input and output statements


input (): This function first takes the input from the user and converts it
into a string. The type of the returned object always will be <class ‘str’>.
It does not evaluate the expression it just returns the complete
statement as String. For example, Python provides a built-in function
called input which takes the input from the user. When the input
function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what
the user typed.
Example:
name = input('What is your name?\n') # \n-> newline-> It causes a
line break
print(name)

Print(): Python print() function prints the message to the screen or any
other standard output device.
we can pass variables, strings, numbers, or other data types as one or
more parameters when using the print() function.
Code:
name = "Alice"
age = 25
print("Hello, my name is", name, "and I am", age, "years old.")

Example for input and output


name = input("What is your name")
age = int(input("Please enter your age"))
print("Hello, my name is", name, "and I am", age, "years old.")

Output:

Control Flow Statements


A program’s control flow is the order in which the program’s code
executes. The control flow of a Python program is regulated by
conditional statements, loops, and function calls.
In a program, statements may be executed sequentially, selectively or
iteratively. Every programming language provides constructs to support
sequence, selection or iteration

Conditional Statement: A conditional statement as the name suggests


itself, is used to handle conditions in the program. These statements
guide the program while making decisions based on the conditions
encountered by the program.

If statement: An if statement tests a particular condition; if the


condition evaluates to true, a course-of-action is followed i.e, a
statement or set-of-statements is executed. If the condition is false, it
does nothing.
The syntax (general form) of the if statement is as shown below:
if expression:
statement1
statement2
For example, consider the following code fragments
if grade == 'A':
print("Congratulations! You did well")

if else statement: The if statement executes a block of statements only


if the condition is true, but if it's false, nothing is executed. To address
this, we use the if-else statement in
Python, which executes the else
statement when the condition is false.
Proper indentation is necessary for
the if-else statement.
Syntax: The syntax for the if-else
statement is as below:
if expression1:
statement1
# When the expression1 is TRUE the statement1 gets executed.
else :
statement2
# When the expression1 is FALSE the statement2 gets printed.
Nested If: In Python, we can use nested
if statements to account for multiple
possibilities when coding. Nested if
statements involve placing an if
statement within another if statement.
Proper attention to indentation is crucial
when implementing nested if
statements, especially when dealing
with multiple blocks of nested if statements.
Syntax: The syntax for the if statement is as below:
if expression1:
if (expression2):
statement2
# When the expression1 is TRUE, then the if statement starts to
evaluate the expression2.
If-elif-else Ladder: The if-elif-else statement checks all if statements in
order, and if none of them are true, it moves to check the elif
statements. When a condition is true, the block of statements under
that if statement is executed, and the rest of the ladder is bypassed. If
none of the conditions are true, the else statement is executed.
Syntax: The syntax for the If-elif statement is as below:
if expression1:
print(statement_if)
elif (expression2):
print(statement_elif)
else:
print(statement_else)

Iteration/Looping statement
The iteration statements or repetition statements allow a set of
instructions to be performed repeatedly until a certain condition is
fulfilled. The iteration statements are also called loops or looping
statements.
Python provides two kinds of
loops:
1. for loop
2. while loop
1.for loop: The for loop is designed to process the items of any
sequence ,such as a list or a string one by one. The syntax of for loop is
as:
for val in sequence:
loop body
Example code:

range() function: The range() function returns a sequence of numbers,


starting from 0 by default, and increments by 1 (by default), and stops
before a specified number.
Syntax:
range(start, stop, step)
Parameter Description

start Optional. An integer number specifying at which position to


start. Default is 0

stop Required. An integer number specifying at which position to


stop (not included).

step Optional. An integer number specifying the incrementation.


Default is 1

Program to print table of given number


num=int(input("Enter any number to print the table"))
print('Table of',num )
for i in range(1,11):
print(num,'x',i,'=',num*i)

Output:
While loop: A while loop is a conditional loop that will repeat the
instructions within itself as long as a conditional remains true (Boolean
True or truth value true).
The general form of Python while loop is:
while <logical Expression> :
loop-body
Program that multiplies two integer numbers without using the
operator, using repeated addition.
n1 = int(input("Enter first number: "))
n2=int(input("Enter second number: "))
product = 0
count = n1
while count > 0:
count = count-1
product = product + n2
print("The product of", n1, "and", n2, "is", product)

Output:

Break Statement: Break can be used to unconditionally jump out of the


loop. It terminates the execution of the loop. Break can be used in
while loop and for loop. Break is mostly required, when because of
some external condition, we need to exit from a loop.
Example
for letter in „Python‟:
if letter = = „h‟:
break
print letter
will result into
P
y
t

Continue Statement: This statement is used to tell Python to skip the


rest of the statements of the current loop block and to move to next
iteration, of the loop. Continue will return back the control to the loop.
This can also be used with both while and for statement.
Example
for letter in „Python‟:
if letter == „h‟:
continue
print letter
will result into
P
Y
T
O
N
The pass keyword: Essentially the pass keyword is not used to alter the
execution flow, but rather it is used merely as a placeholder. It is a null
statement. The only difference between a comment and a pass
statement in Python is that the interpreter will entirely ignore the
comment whereas a pass statement is not ignored. However, nothing
happens when pass is executed. In Python, loops cannot have an empty
body. Suppose we have a loop that is not implemented yet, but we
want to implement it in the future, we can use the pass statement to
construct a body that does nothing.
# Input
stocks = ['AAPL', 'HP', 'MSFT', 'GOOG']
for stock in stocks:
pass
else:
print('For loop is over!')

Loop else statements: Python loops have an optional else clause.


Complete syntax of Python loops along with else clause is as given
below:
for <variable> in <sequence>: while <test condition>:

statement1 statement1
statement2
statement2

else: else:

statement(s) statement(s)
The else clause of a Python loop executes when the loop terminates
normally, i.e., when test-condition results into false for a while loop or
for loop has executed for the last value in the sequence; not when the
break statement terminates the loop.
Function
A function is a block of code(that performs a specific task) which runs
only when it is called.
From the definition, it can be inferred that writing such block of codes,
i.e. functions, provides benefits such as
 Reusability: Code written within a function can be called as and
when needed. Hence, the same code can be reused thereby
reducing the overall number of lines of code.
 Modular Approach: Writing a function implicitly follows a
modular approach. We can break down the entire problem that
we are trying to solve into smaller chunks, and each chunk, in
turn, is implemented via a function.
Functions can be thought of as building blocks while writing a program,
and as our program keeps growing larger and more intricate, functions
help make it organized and more manageable. They allow us to give a
name to a block of code, allowing us to run that block using the given
name anywhere in a program any number of times. This is referred to
as calling a function.
There are three types of functions in Python:
1. Built-in functions such as print to print on the standard output
device, type to check data type of an object, etc. These are the
functions that Python provides to accomplish common tasks.
2. User-Defined functions: As the name suggests these are custom
functions to help/resolve/achieve a particular task.
3. Anonymous functions, also known as lambda functions are
custommade without having any name identifier.
1. built-in functions: Built-in functions are the ones provided by
Python. The very first built-in function we had learned was the print
function to print a string given to it as an argument on the standard
output device. They can be directly used within our code without
importing any module and are always available to use.
In addition to print function, We have some built-in functions listed
below:
 type(object) is used to check the data type of an object
 float([value]) returns a floating point number constructed from a
number or string value
 int([value]) returns an integer object constructed from a float or
string value, or return 0 if no arguments are given
 str([object]) returns a string version of object. If the object is not
provided, returns the empty string.
 bool([value]) return a Boolean value, i.e. one of True or False.
value is converted using the standard truth testing procedure1 . If
the value is false or omitted, this returns False; otherwise, it
returns True.
 len(object) returns the length (the number of items) of an object.
The argument may be a sequence (such as a string, bytes, tuple,
list, or range) or a collection (such as a dictionary, set, or frozen
set).
2. User defined functions: As Python programmers, we might need to
break down the programming challenge into smaller chunks and
implement them in the form of custom or user defined functions. The
concept of writing functions is probably an essential feature of any
programming language.
Functions are defined using the def keyword, followed by an identifier
name along with the parenthesis, and by the final colon that ends the
line. The block of statements which forms the body of the function
follows the function definition.
Syntax:

def function_name(arguments):
# function body

return

Here,
 def - keyword used to declare a function
 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function
Example Code:
def add_numbers():
x=5
y=6
sum = x + y
print("The sum is", sum)
add_numbers() #Calling Function

Output:
The sum is 11

Python Function Arguments


A function can also have arguments. An argument is a value that is
accepted by a function.
Note the terminology used here:
 Parameters: They are specified within parenthesis in the function
definition, separated by commas.
 Arguments: When we call a function, values that parameters take
are to be given as arguments in a comma separated format.
For example,

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

# Output: Sum: 9
Functions with multiple arguments and a return statement: There is
one more functionality that functions are capable of performing is to
return a value to the calling statement using the keyword return.
Example Code:
# Program to illustrate
# the use of user-defined functions

def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Functions with default arguments: Let us say, we are writing a function


that takes multiple parameters. Often, there are common values for
some of these parameters. In such cases, we would like to be able to
call the function without explicitly specifying every parameter. In other
words, we would like some parameters to have default values that will
be used when they are not specified in the function call.
To define a function with a default argument value, we need to assign a
value to the parameter of interest while defining a function.
def power(number, pow=2):
"""Returns the value of number to the power of pow."""
return number**pow

Notice that the above function computes the first argument to the
power of the second argument. The default value of the latter is 2. So
now when we call the function power only with a single argument, it
will be assigned to the number parameter and the return value will be
obtained by squaring number.

# Calling the power function only with


required argument
print(power(2))
# Output
4
Exception handling

Errors are the problems in a program due to which the program will
stop the execution. On the
other hand, exceptions are
raised when some internal
events occur which
changes the normal flow
of the program.
Two types of Error occurs
in python.

1. Compile time error


2. Run time error
(Exceptions)
1.Compile time error: A compile-time error generally refers to
the errors that correspond to the semantics or syntax.
 SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
2.Run time error: A runtime error refers to the error that we encounter
during the code execution during runtime. We can easily fix a compile-
time error during the development of code. A compiler cannot identify
a runtime error.
Different types of exceptions in python:
 TypeError: This exception is raised when an operation or function
is applied to an object of the wrong type, such as adding a string
to an integer.
 NameError: This exception is raised when a variable or function
name is not found in the current scope.
 IndexError: This exception is raised when an index is out of range
for a list, tuple, or other sequence types.
 KeyError: This exception is raised when a key is not found in a
dictionary.
 ValueError: This exception is raised when a function or method is
called with an invalid argument or input, such as trying to convert
a string to an integer when the string does not represent a valid
integer.
 AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-
existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as
reading or writing a file, fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is
made to divide a number by zero.
 ImportError: This exception is raised when an import statement
fails to find or load a module.
Catching Exceptions
Try and Except Statement
In Python, we catch exceptions and handle them using try and except
code blocks. The try clause contains the code that can raise an
exception, while the except clause contains the code lines that handle
the exception.
Code:
# Python code to catch an exception and handle it using try and except c
ode blocks

a = ["Python", "Exceptions", "try and except"]


try:
#looping through the elements of the array a, choosing a range that g
oes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed b
y the Python interpreter
except:
print ("Index out of range")

Output:
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

Try with Else Clause


Python also supports the else clause, which should come after every
except clause, in the try, and except blocks. Only when the try clause
fails to throw an exception the Python interpreter goes on to the else
block.
Code:
1. # Python program to show how to use else clause with try and except
clauses
2.
3. # Defining a function which returns reciprocal of a number
4. def reciprocal( num1 ):
5. try:
6. reci = 1 / num1
7. except ZeroDivisionError:
8. print( "We cannot divide by zero" )
9. else:
print ( reci )
# Calling the function and passing values
10. reciprocal( 4 )
11. reciprocal( 0 )

Output:
0.25
We cannot divide by zero

Finally Keyword in Python


The finally keyword is available in Python, and it is always used after
the try-except block. The finally code block is always executed after the
try block has terminated normally or after the try block has terminated
for some other reason.
Code:
1. # Python code to show the use of finally clause
2.
3. # Raising an exception in try block
4. try:
5. div = 4 // 0
6. print( div )
7. # this block will handle the exception raised
8. except ZeroDivisionError:
9. print( "Attempting to divide by zero" )
# this will always be executed no matter exception is raised or not
10. finally:
11. print( 'This is code of finally clause' )

Output:
Attempting to divide by zero
This is code of finally clause

You might also like