Unit - 2 - Data Types, IO, Types of Errors and Control - Structures
Unit - 2 - Data Types, IO, Types of Errors and Control - Structures
Module – 1
2.1 Data types, I/O, Types of Errors
A data type is a data storage format that can contain a specific type or range of values. Variables can store data of different
types, and different types can do different things. Python has the following data types built-in by default, in these
categories.
Numeric Types: int, float, complex
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod empor incididunt ut labore et dolore
magna aliqua."""
print(a)
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Lists:
List is an ordered sequence of items. All the items in a list do not need to be of the same type and lists are mutable - they
can be changed. Elements can be reassigned or removed, and new elements can be inserted.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].
t = (5,'program', 1+3j)
range():
The range() type returns an immutable sequence of numbers between the given start integer to the stop integer.
print(list(range(10))
>>> d = {1:'value','key':2}
>>> type(d)
a = {5,2,3,1,4}
We can use the set for some mathematical operations like set union, intersection, difference etc. We can also use set to
remove duplicates from a collection.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(a,complex))
Output
We add two variables num_int and num_flo, storing the value in num_new.
We will look at the data type of all three objects respectively.
In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
Also, 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.
Now, let's try adding a string and an integer, and see how Python deals with it.
num_int = 123
num_str = "456"
print(num_int+num_str)
Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
num_int = 123
num_str = "456"
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
Module-2
2.4 Mutable and Immutable types
A first fundamental distinction that Python makes on data is about whether the value changes are not. If the value can
change, then is called mutable, while if the value cannot change, that is called immutable.
Mutable:
list,
dict
set
Immutable:
int,
float,
complex,
string,
tuple
2.5 Input and Output Operations and Formats
Python provides numerous built-in functions that are readily available at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations respectively.
2.5.1 Python Output Using print() function
We use the print() function to output data to the standard output device (screen).
Example 1:
Output
Example 2:
a=5
print('The value of a is', a)
Output
The value of a is 5
In the second print() statement, we can notice that space was added between the string and the value of variable a. This is
by default, but we can change it.
The actual syntax of the print() function is:
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers.
Output
We can also format strings like the old sprintf() style used in C programming language. We use the % operator to
accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this.
The syntax for input() is:
input([prompt])
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
2.6.1 Syntax errors: Syntax errors are produced by Python when it is translating the source code into byte code. They
usually indicate that there is something wrong with the syntax of the program.
Example: Omitting the colon at the end of an if statement yields the somewhat redundant message.
Here are some ways to avoid the most common syntax errors:
1. Make sure you are not using a Python keyword for a variable name.
2. Check that you have a colon at the end of the header of every compound statement, including for, while, if,
and def statements.
3. Check that indentation is consistent. You may indent with either spaces or tabs but it’s better not to mix them. Each
level should be nested the same amount.
4. Make sure that strings in the code have matching quotation marks.
5. If you have multiline strings with triple quotes (single or double), make sure you have terminated the string properly.
An un-terminated string may cause an invalid token error at the end of your program, or it may treat the following
part of the program as a string until it comes to the next string. In the second case, it might not produce an error
message at all!
6. An unclosed bracket – (, {, or [ – makes Python continue with the next line as part of the current statement.
Generally, an error occurs almost immediately in the next line.
7. Check for the classic = instead of == inside a conditional.
2.6.2 Run Time Error: Errors that occur after the code has been executed and the program is running. The error of this
type will cause your program to behave unexpectedly or even crash. An example of a runtime error is the division by zero.
Consider the following example:
The program above runs fine until the user enters 0 as the second number:
>>>
Enter a number: 9
Enter a number: 2
9.0 divided by 2.0 equals: 4.5
>>>
Enter a number: 11
Enter a number: 3
It is also called semantic errors, logical errors cause the program to behave incorrectly, but they do not usually crash the
program. Unlike a program with syntax errors, a program with logic errors can be run, but it does not operate as intended.
Consider the following example of logical error:
The example above should calculate the average of the two numbers the user enters. But, because of the order of
operations in arithmetic (the division is evaluated before addition) the program will not give the right answer:
>>>
Enter a number: 3
Enter a number: 4
The average of the two numbers you have entered is: 5.0
>>>
>>>
Enter a number: 3
Enter a number: 4
The average of the two numbers you have entered is: 3.5
>>>
Module-3:
10 | P a g e RGUKT-RK Valley
3.7 Conditional Constructs
There come situations in real life when we need to make some decisions and based on these decisions, we decide what we
should do next. Similar situations arise in programming also where we need to make some decisions and based on these
decisions we will execute the next block of code.
Decision making statements in programming languages decides the direction of flow of program execution. Decision making
statements available in python are:
if statement
if..else statements
nested if statements
if-elif ladder
Short Hand if statement
Short Hand if-else statement
3.7.1 if statement: if statement is the simplest decision-making statement. It is used to decide whether a certain statement
or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise
not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it
will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown in
the below example:
if condition:
statement1
statement2
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
Output:
I am Not in if
11 | P a g e RGUKT-RK Valley
As the condition present in the if statement is false. So, the block below the if statement is not executed.
3.7.2 if- else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement.
We can use the else statement with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow Chart:-
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is false after call the
statement which is not in block(without spaces).
12 | P a g e RGUKT-RK Valley
3.7.3 nested-if: A nested if is an if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.
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
Flow chart:
Output:
i is smaller than 15
i is smaller than 12 too
13 | P a g e RGUKT-RK Valley
3.7.4 if-elif-else ladder: Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flow Chart:-
Example:-
14 | P a g e RGUKT-RK Valley
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20
Short Hand if-else statement: This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example:
# Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)
Output:
True
15 | P a g e RGUKT-RK Valley
MCQ on Data Types and Conditional Constructs
1. Which statement is correct?
a. List is immutable && Tuple is mutable
b. List is mutable && Tuple is immutable
c. Both are Mutable.
d. Both are Immutable.
2. Which one of the following is mutable data type?
a. Set
b. Int
c. Str
d. tupl
3. Which one of the following is immutable data type?
a. List
b. Set
c. Int
d. dict
4. Which of these is not a core data type?
a. List
b. Tuple
c. Dictionary
d. Class
5. Which one of the following is False regarding data types in Python?
a. In python, explicit data type conversion is possible
b. Mutable data types are those that can be changed.
c. Immutable data types are those that cannot be changed.
d. None of the above
6. Which of the following function is used to know the data type of a variable in Python?
a. datatype()
b. typeof()
c. type()
d. vartype()
7. Which one of the following is a valid Python if statement :
a. if (a>=2):
b. if (a >= 2)
c. if (a => 22)
d. if a >= 22
8. What keyword would you use to add an alternative condition to an if statement?
a. else if
b. elseif
c. elif
d. None of the above
9. Can we write if/else into one line in python?
a. Yes
b. No
c. if/else not used in python
d. None of the above
10. Which statement will check if a is equal to b?
16 | P a g e RGUKT-RK Valley
a. if a = b:
b. if a == b:
c. if a === c:
d. if a == b
17 | P a g e RGUKT-RK Valley
Un-Solved Problem Set
1. Take values of length and breadth of a rectangle from user and check if it is square or not.
2. Take two int values from user and print greatest among them
3. A shop will give discount of 10%, if the cost of purchased quantity is more than 1000.
Ask user for quantity
Suppose, one unit will cost 100.
Ex: quantity=11
cost=11*100=1100>1000
so, he will get 10% discount, that is 110.
Final cost is 1100-110=990
4. A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years.
Ask user for their salary and year of service and print the net bonus amount.
5. A school has following rules for grading system:
a. Below 25 - F
b. 25 to 45 - E
c. 45 to 50 - D
d. 50 to 60 - C
e. 60 to 80 - B
f. Above 80 - A
Ask user to enter marks and print the corresponding grade.
6. Take input of age of 3 people by user and determine oldest and youngest among them.
7. Write a program to print absolute vlaue of a number entered by user. E.g.-
INPUT: 1 OUTPUT: 1
INPUT: -1 OUTPUT: 1
8. Modify the 4th question (in solved problem set) to allow student to sit if he/she has medical cause. Ask user if
he/she has medical cause or not ( 'Y' or 'N' ) and print accordingly.
9. Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of
service.
if employee is female, then she will work only in urban areas.
if employee is a male and age is in between 20 to 40 then he may work in anywhere
if employee is male and age is in between 40 t0 60 then he will work in urban areas only.
And any other input of age should print "ERROR".
Descriptive Questions
1. What is data type? What are the different types of data?
2. What are the numeric data types? Explain with examples.
3. What are the sequence types of data?
4. Explain about type conversions.
5. What is mutable and immutable? What are mutable and immutable data types?
6. Explain about python output formatting.
7. Describe types of errors.
8. Explain about types of conditional constructs.
9. Give examples for all conditional constructs.
10. Write shorthand if and shorthand if-else statement.
18 | P a g e RGUKT-RK Valley