Python Unit 3
Python Unit 3
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.")
Output:
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:
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:
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
# 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
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.
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.
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
Output:
0.25
We cannot divide by zero
Output:
Attempting to divide by zero
This is code of finally clause