Part-2 Notes
Part-2 Notes
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.
num_flo = 1.23
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
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
<required_datatype>(expression)
num_str = "456"
num_str = int(num_str)
OUTPUT:
Decision Constructs
Statement Description
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.
Indentation in Python
Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
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 !!");
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)
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
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)
Syntax:
range(start,stop,step size)
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.
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.
while expression:
statements
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
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
Example:
for i in range(9):
if i > 3:
break
print(i)
output:
0
1
2
3
Example -
# An empty loop
str1 = 'javatpoint'
i=0
Output: Value of i : 10
Module:2: Collections and Functions
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
Output:
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.
Output:
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
Example:
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.
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 ().
# Tuple slicing
print (tup[1:])
print (tup[0:1])
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
t[2] = "cmr";
The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
Output:
name is Jimmy
name is mike
dict_keys([1, 2, 3, 4])
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.
Output:
<class 'bool'>
<class 'bool'>
Python Function
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 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
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Output:
hello world
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.
Types of 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.
Example 1
def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))
Output:
Default Arguments
Example 1
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
Output:
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:
You can also send arguments with the key = value syntax.
Example
OUTPUT:
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
Output:
Output:
The sum is 60
Value of sum outside the function: 0
Python Function Recursion
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
Disadvantages of Recursion
Python 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
EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
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
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.
The statements that don't throw the exception should be placed inside
the else block.
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.
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
Syntax
raise Exception_class,<value>
Points to remember
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: