0% found this document useful (0 votes)
18 views

Part-2 Notes

The document discusses two types of type conversion in Python: implicit and explicit. Implicit conversion occurs automatically between compatible types while explicit conversion involves casting using functions like int() and float(). Decision making in Python uses if, elif and else statements to check conditions and execute code blocks. Loops like for and while iterate over sequences and check conditions to repeatedly execute code.

Uploaded by

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

Part-2 Notes

The document discusses two types of type conversion in Python: implicit and explicit. Implicit conversion occurs automatically between compatible types while explicit conversion involves casting using functions like int() and float(). Decision making in Python uses if, elif and else statements to check conditions and execute code blocks. Loops like for and while iterate over sequences and check conditions to repeatedly execute code.

Uploaded by

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

Type conversion (Typecasting):

The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.

 Implicit Type Conversion


 Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data


type to another data type. This process doesn't need any user
involvement.

Let's see an example where Python promotes the conversion of the


lower data type (integer) to the higher data type (float) to avoid data
loss.

Example : Converting integer to float


num_int = 123

num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))

print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)

print("datatype of num_new:",type(num_new))

OUTPUT

datatype of num_int: <class 'int'>

datatype of num_flo: <class 'float'>

Value of num_new: 124.23

datatype of num_new: <class 'float'>

Note :we can see the num_new has a float data type because Python always
converts smaller data types to larger data types to avoid the loss of data.
Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to


required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion. This
type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
Syntax :

<required_datatype>(expression)

Example : Addition of string and integer using explicit


conversion
num_int = 123

num_str = "456"

print("Data type of num_int:",type(num_int))

print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)

print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)

print("Data type of the sum:",type(num_sum))

OUTPUT:

Data type of num_int: <class 'int'>

Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579

Data type of the sum: <class 'int'>

Decision Constructs

Decision making is the most important aspect of almost all the


programming languages. As the name implies, decision making allows us
to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition


is true, a block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that,
Statement it also provides the block of the code for the false case of the
condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside an


Statement outer if statement.

Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't


allow the use of parentheses for the block level code. In Python,
indentation is used to declare a block. If two statements are at the
same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.

he syntax of the if-statement is given below.

if expression:
statement

Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

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

Syntax:

if condition:
#block of statements
else:
#another block of statements (else-block)
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

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

Syntax:

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Iteration Control structures (for, while)

A loop statement allows us to execute a statement or group of


statements multiple times. The following diagram illustrates a loop
statement −

There are the following loop statements in Python.

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some
part of the code until the given condition is satisfied. The for loop is
also called as a per-tested loop. It is better to use for loop if the
number of iteration is known in advance.

while loop The while loop is to be used in the scenario where we don't know
the number of iterations in advance. The block of statements is
executed in the while loop until the condition specified in the while
loop is satisfied. It is also called a pre-tested loop.

do-while loop The do-while loop continues until a given condition satisfies. It is
also called post tested loop. It is used when it is necessary to
execute the loop at least once (mostly menu driven programs).
Python doesn't have do-while loop, but we can create a
program using while loop only.
for loop

The for loop in Python is used to iterate the statements or a part of


the program several times. It is frequently used to traverse the data
structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)

Example-1: Iterating string using for loop

str = "Python"
for i in str:
print(i)
Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

The range() function

The range() function is used to generate the sequence of the


numbers. If we pass the range(10), it will generate the numbers from
0 to 9. The syntax of the range() function is given below.

Syntax:

range(start,stop,step size)

Example-1: Program to print numbers in sequence.

n = int(input("Enter the number "))


for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)

We can also use the range() function with sequence of numbers.


The len() function is combined with range() function which iterate
through a sequence using indexing. Consider the following example.

list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])
Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The
inner loop is executed n number of times for every iteration of the
outer loop. The syntax is given below.

Example- 1: Nested for loop


# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

While loop

The Python while loop allows a part of the code to be executed until
the given condition returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the


number of iterations then the while loop is most effective to use.

The syntax is given below.

while expression:
statements
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

Loop Control Statements

We can change the normal sequence of while loop's execution using


the loop control statement. When the while loop's execution is
completed, all automatic objects defined in that scope are demolished.
Python offers the following control statement to use within the while
loop.

Continue Statement - When the continue statement is encountered,


the control transfer to the beginning of the loop.

Example

Skip the iteration if the variable i is 3, but continue with the next
iteration:
for i in range(9):
if i == 3:
continue
print(i)

output

0
1
2
4
5
6
7
8

Break Statement - When the break statement is encountered, it


brings control out of the loop.

Example:

End the loop if i is larger than 3:

for i in range(9):
if i > 3:
break
print(i)

output:

0
1
2
3

Pass Statement - The pass statement is used to declare the empty


loop. It is also used to define empty class, function, and control
statement. Let's understand the following example.

Example -

# An empty loop
str1 = 'javatpoint'
i=0

while i < len(str1):


i += 1
pass
print('Value of i :', i)

Output: Value of i : 10
Module:2: Collections and Functions

Python Data Types

A variable can hold different types of values. For example, a person's


name must be stored as a string whereas its id must be stored as an
integer.

Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given
below.

 Numbers
 Sequence Type
 Boolean
 Set
 Dictionary

String

The string can be defined as the sequence of characters represented in


the quotation marks. In Python, we can use single, double, or triple
quotes to define a string.

String handling in Python is a straightforward task since Python


provides built-in functions and operators to perform operations in the
string.

In the case of string handling, the operator + is used to concatenate


two strings as the operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation
"Python" *2 returns 'Python Python'.

The following example illustrates the string in Python.

str = "string using double quotes"


print(str)
s = '''''A multiline
string'''
print(s)

Output:

string using double quotes


A multiline
string

Strings indexing and splitting

Like other languages, the indexing of the Python strings starts from 0.
For example, The string "HELLO" is indexed as given in the below
figure.

Consider the following example:


str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

Output:

IndexError: string index out of range

As shown in Python, the slice operator [] is used to access the


individual characters of the string. However, we can use the :
(colon) operator in Python to access the substring from the given
string. Consider the following example.

Here, we must notice that the upper range given in the slice operator
is always exclusive i.e., if str = 'HELLO' is given, then str[1:3] will
always include str[1] = 'E', str[2] = 'L' and nothing else.
Consider the following example:

# Given String
str = "BANGALORE"
# Start 0th index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])

Output:

BANGALORE

ANGA

NG

BAN

ALO

Negative indexes

Indexes are used in arrays in all the programming languages. We can


access the elements of an array by going through their indexes. But no
programming language allows us to use a negative index value such as
-4. Python programming language supports negative indexing of
arrays, something which is not available in arrays in most other
programming languages. This means that the index value of -1 gives
the last element, and -2 gives the second last element of an array. The
negative indexing starts from where the array ends. This means that
the last element of the array is the first element in the negative
indexing which is -1.

Example:

arr = [10, 20, 30, 40, 50]

print (arr[-1])

print (arr[-2])
Output:

50

40

List

Python Lists can contain data of different types. The items stored in
the list are separated with a comma (,) and enclosed within square
brackets [].The lists are mutable types.

We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the
list in the same way as they were working with the strings.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)

Output:

<class 'list'>
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain
the collection of the items of different data types. The items of the
tuple are separated with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure (Immutable) as we can't


modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repetition using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "cmr"
Output:

<class 'tuple'>

('hi', 'Python', 2)

('Python', 2)

('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):

File "main.py", line 14, in <module>

t[2] = "cmr";

TypeError: 'tuple' object does not support item assignment


Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an


associative array or a hash table where each key stores a specific
value. Key can hold any primitive data type, whereas value is an
arbitrary Python object.

The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


# Printing dictionary
print (d)
# Accesing value using keys
print(" name is "+d[1])
print(" name is "+ d[4])
print (d.keys())
print (d.values())

Output:

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

name is Jimmy

name is mike

dict_keys([1, 2, 3, 4])

dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It
denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'. Consider
the following example.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:

<class 'bool'>

<class 'bool'>

NameError: name 'false' is not defined


Set

Python Set is the unordered collection of the data type. It is iterable,


mutable(can modify after creation), and has unique elements. In set,
the order of the elements is undefined; it may return the changed
sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly braces
and separated by the comma. It can contain various types of values.
Consider the following example.

# Creating Empty set


set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Python Function

Functions are the most important aspect of an application. A function


can be defined as the organized block of reusable code, which can be
called whenever required.

Python allows us to divide a large program into the basic building


blocks known as a function. The function contains the set of
programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the Python
program.

The Function helps to programmer to break the program into the


smaller part. It organizes the code very effectively and avoids the
repetition of the code. As the program grows, function makes the
program more organized.

Python provide us various inbuilt functions like range() or print().


Although, the user can create its functions, which can be called user-
defined functions.

There are mainly two types of functions.

User-define functions - The user-defined functions are those define


by the user to perform the specific task.
Built-in functions - The built-in functions are those functions that
are pre-defined in Python.

In this tutorial, we will discuss the user define functions.

Advantage of Functions in Python


 Using functions, we can avoid rewriting the same logic/code
again and again in a program.
 We can call Python functions multiple times in a program and
anywhere in a program.
 We can track a large Python program easily when it is divided
into multiple functions.
 Reusability is the main achievement of Python functions.

However, Function calling is always overhead in a Python program.

Creating a Function

Python provides the def keyword to define the function. The syntax of
the define function is given below.

Syntax:

def my_function(parameters):
function_block
return expression

The def keyword, along with the function name is used to define the
function.

The identifier rule must follow the function name.

A function accepts the parameter (argument), and they can be


optional.

The function block is started with the colon (:), and block statements
must be at the same indentation.

The return statement is used to return the value. A function can have
only one return

Function Calling

In Python, after the function is created, we can call it from another


function. A function must be defined before the function call;
otherwise, the Python interpreter gives an error. To call the function,
use the function name followed by the parentheses.
Consider the following example of a simple example that prints the
message "Hello World".

#function definition
def hello_world():
print("hello world")
# function calling
hello_world()

Output:

hello world

The return statement

The return statement is used at the end of the function and returns the
result of the function. It terminates the function execution and
transfers the result where the function is called. The return statement
cannot be used outside of the function.

Syntax

return [expression_list]

Arguments in function

The arguments are types of information which can be passed into the
function. The arguments are specified in the parentheses. We can pass
any number of arguments, but they must be separate them with a
comma.

#Python function to calculate the sum of two variables


#defining the function
def sum (a,b):
return a+b;

#taking values from the user


a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))

Types of arguments

There may be several types of arguments which can be passed at the


time of function call.
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required Arguments

we can provide the arguments at the time of the function call. As far as
the required arguments are concerned, these are the arguments which
are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If
either of the arguments is not provided in the function call, or the
position of the arguments is changed, the Python interpreter will show
the error.

Consider the following example.

Example 1

def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))

Output:

Enter the name: John


Hi John

Default Arguments

Python allows us to initialize the arguments at the function definition.


If the value of any of the arguments is not provided at the time of
function call, then that argument can be initialized with the value given
in the definition even if the argument is not specified at the function
call.

Example 1

def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")

Output:

My name is John and age is 22

Variable-length Arguments (*args)

In large projects, sometimes we may not know the number of


arguments to be passed in advance. In such cases, Python provides us
the flexibility to offer the comma-separated values which are internally
treated as tuples at the function call. By using the variable-length
arguments, we can pass any number of arguments.

However, at the function definition, we define the variable-length


argument using the *args (star) as *<variable - name >.

Consider the following example.

Example

def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick
Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

OUTPUT:

The youngest child is Linus

Scope of variables

The scopes of the variables depend upon the location where the
variable is being declared. The variable declared in one part of the
program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.

 Global variables
 Local variables

The variable defined outside any function is known to have a global


scope, whereas the variable defined inside a function is known to have
a local scope.

Consider the following example.

Example 1 Local Variable


def print_message():
message = "hello !! I am going to print a message." # the variable
message is local to the
# function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot
be accessible here.

Output:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined

Example 2 Global Variable


def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed

Output:

The sum is 60
Value of sum outside the function: 0
Python Function Recursion

Python also accepts function recursion, which means a defined function


can call itself.
Recursion is a common mathematical and programming concept. It
means that a function calls itself. This has the benefit of meaning that
you can loop through data to reach a result.

Example of a recursive function


def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output
The factorial of 3 is 6

Advantages of Recursion

 Recursive functions make the code look clean and elegant.


 A complex task can be broken down into simpler sub-problems
using recursion.
 Sequence generation is easier with recursion than using some
nested iteration.

Disadvantages of Recursion

 Sometimes the logic behind recursion is hard to follow through.


 Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
 Recursive functions are hard to debug.

Python Exception

An exception can be defined as an unusual condition in a program


resulting in the interruption in the flow of the program.

Whenever an exception occurs, the program stops the execution, and


thus the further code is not executed. Therefore, an exception is the
run-time errors that are unable to handle to Python script. An
exception is a Python object that represents an error
Python provides a way to handle the exception so that the code can be
executed without any interruption. If we do not handle the exception,
the interpreter doesn't execute all the code that exists after the
exception.

Python has many built-in exceptions that enable our program to run
without interruption and give the output. These exceptions are given
below:

Common Exceptions

Python provides the number of built-in exceptions, but here we are


describing the common standard exceptions. A list of common
exceptions that can be thrown from a standard Python program is
given below.

ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local or


global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.

Exception handling in python: try-expect statement

If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block. The try block
must be followed with the except statement, which contains a block of
code that will be executed if there is some exception in the try block.

Syntax

try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code
Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:10
Enter b:0
Can't divide with zero

The except statement using with exception variable

We can use the exception variable with the except statement. It is


used by using the as keyword. this object will return the cause of the
exception. Consider the following example:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
division by zero

Points to remember
Python facilitates us to not specify the exception with the except
statement.

We can declare multiple exceptions in the except statement since the


try block may contain the statements which throw the different type of
exceptions.
We can also specify an else block along with the try-except statement,
which will be executed if no exception is raised in the try block.

The statements that don't throw the exception should be placed inside
the else block.

The try...finally block

Python provides the optional finally statement, which is used with


the try statement. It is executed no matter what exception occurs and
used to release the external resource. The finally block provides a
guarantee of the execution.

We can use the finally block with the try block in which we can pace
the necessary code, which must be executed before the try statement
throws an exception.

The syntax to use the finally block is given below.

Syntax

try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

example

try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")

Output:

file closed

Error
Raising exceptions

An exception can be raised forcefully by using the raise clause in


Python. It is useful in in that scenario where we need to raise an
exception to stop the execution of the program.

For example, there is a program that requires 2GB memory for


execution, and if the program tries to occupy 2GB of memory, then we
can raise an exception to stop the execution of the program.

The syntax to use the raise statement is given below.

Syntax

raise Exception_class,<value>

Points to remember

To raise an exception, the raise statement is used. The exception class


name follows it.

An exception can be provided with a value that can be given in the


parenthesis.

To access the value "as" keyword is used. "e" is used as a reference


variable which stores the value of the exception.

We can pass the value to an exception to specify the exception type.

Example

try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

Output:

Enter the age:17


The age is not valid

You might also like