Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
Lab Assignment-03
Values and Data Types, operators, if, if-else and if- elif-else
In computer programming, data types specify the type of data that can be stored inside a variable, known as
Data Type of that variable.
This asignment will introduce some of the fundamental types in Python. We will learn about:
bool: the binary type
int: the integer
float: the floating-point (decimal) number
str: the string (array) of characters
list: the mutable array of objects
tuple: the immutable array of objects
(i) Boolean
Booleans are binary data structures, representing True and False (or yes/no, on/off, 0/1, depending
on the case). In Python, their type is called bool and they can have only one of two values,
either True or False.
We can use the type() function to check the type of an object in Python.
type(True)
a = False
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
type(a)
You may recognize the bool type, because we already saw it when we used the == equality operator in the
previous chapter.
2 == 3
type(2 == 3)
Bool vs bool
What do you think happens if we check the equality of two bools? Try it!
True == True
True == False
False == False
Booleans as integers
In Python bool types have a special property: True and False can also be treated as the integers 1 and 0,
respectively. You can include booleans in expressions and when they are converted to numbers automatically, it
is called casting.
45 * False
True + True + True + True + True
What do you think happens when you test equality between a bool and 0 or 1?
True == 1
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
False == 0
False == 1
This can be useful to know because as the simplest data type, booleans also use the least memory. If you need a
large array of exclusively 0s and 1s, it will use less memory (and be the exact same), if you store those values
as bool rather than numbers!
(ii)Boolean operators
There are two special operators in Python for comparing bool. They are and and or.
The and operator is True only when both of the compared bools are True.
True and True
True
True and False
False
False and False
False
The or operator is True when one of the compared bools are True.
True or True
True or False
False or False
Recall that Pyhton evaluates expressions when it comes time to compare them. Try to figure out if each of the
following expressions evaluate to True or False and then run them to check!
(2 == 2) and (2 == 3)
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
(1 == 4) or (4 == 4)
(0 == 1) or False
(iii) Integer (int)
The int type represents integers: positive and negative whole numbers and 0.
type(42)
Unlike other languages, Python 3 integers have no fixed size. When they grow too big, they are automatically
given more memory by Python, meaning integers have essentially no size limit (Note: this is not true in most
other languages! Languages like C can only store Integers in the range (-2147483647, 2147483647) before
needing a new data type to handle them).
a=2
a
b = a ** 64
b
c = a ** 128
c
print(type(a), type(b), type(c))
(iv) Floating-point numbers (float)
Decimal (or floating-point) numbers in Python belong to the float data type.
type(3.2)
a = -0.11
type(a)
What do you think happens when you combine an int and a float in a mathematical expression?
2 * 3.2
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
4.81 / 2
8.99 * 0
Python returns a float whenever performing operations on a mix of int and float types.
Integer division
What happens if we divide two ints that cannot be expressed as a whole number?
4/3
Uh oh! Usually when we have an expression with two int types, the result is also an int, but in the case of
division, two int can make a float! If we want to force division to return an int, we can use the integer
division operator (//).
4 // 3
Integer division returns the floor (nearest lower integer) of the quotient. You might imagine that now we
dropped the remainder, but may want to know what it is. For this we can use the modulo % operator.
4%3
Now we know that 4 // 3 = 1 with remainder 1 and all of the values are still type int!
(v)Comparison Operators
We already saw a host of mathematical operators we can apply to numbers to add, multiply, divide them, etc.
We can also compare numerical types with handy comparison operators. We learned about the == comparison
operator already. These are the most common comparison operators:
==: Equal to
!=: Not equal to
<: Less than
>: Greater than
<=: Less than or equal to
>=: Greater than or equal to
Reminer
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
The single equal sign = is the assignment operator for defining variables (a = 5).
The double equal sign is a comparison operator for checking equality (4 == 5 would return False).
3<6
4.55 > 7.89
9 != 12.2
What do you think happens if you compare a float and int with the same value?
4.0 == 4
Chaining comparisons
What if we want to know if a given value is between two other values?
x = 5.5
x>4
x<6
We can chain comparisons in Python to write this much more simply as the following range:
4<x<6
0<x<5
(vi)String (str)
In Python, the string is used to store text. Strings can be created with either single quotes '' or double quotes "".
The PEP8 style guideline does not specify one over the other, just recommends consistency: “Pick a rule and
stick to it”.
The standard way to get Python to show output as it is running is to use a print() statement. The print() function
attempts to convert the argument in parentheses into a string and then shows the result in the shell.
first_str = 'Hello, I am a str type'
print(first_str)
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
Hello, I am a str type
type(first_str)
str
# Nearly anything in Python can be printed using print()
print(4.2653)
# Remember expressions are evaluated before being passed to functions
print(8*10)
# To print the expression, use quotes ("") to make it a str!
print('8*10')
4.2653
80
8*10
(vii) Str indexing
A particular character in a string can be accessed by its index. Python uses the square brackets [] to denote
indices.
Note: Some languages start indexing at 0, and some start at 1. In Python, indexing starts at 0.
Python also allows you to use negative indices to access characters from the end of the string. The forward and
backwards indices are summarized in image below:
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
For example:
mystring = 'Hello World'
#Get the 2nd character in the string
print(mystring[1])
#Get the last character
print(mystring[-1])
(viii) Str slicing
You can also extract a range of characters from a string by taking a slice. Slicing in Python is again done with
square brackets, but this time we need to provide a start index, a stop index, and a colon string[start:stop].
Note: The stop index in Python is one higher than the last character you want to slice. E.g. if you sliced from 0
to 3, you would get the 0th, 1st, and 2nd characters ('Hello[0:3] == 'Hel'). The character at index 3 is not included!
If you do not provide a start index, Python assumes you want all characters from the beginning of the string to
the stop index ('Hello'[:3] == 'Hel').
Likewise, if you do not provide a stop index, Python assumes you want all characters from the start index to the
end of the string ('Hello[2:] == 'llo').
What do you think the slice 'Hello'[:] produces? Try it and see if you were right.
Also try indexing the string to get various letter combinations.
'Hello'[:]
Indexing and slicing are core concepts in Python that work the exact same way for other data types like
the tuple and list.
(ix) List
A list is a common way to store data of arbitrary type in Python (the list could contain bool, str, or even
other list objects). Lists are defined with square brackets ([]).
# An empty list can be assigned to a variable and added to later with append
empty_list = []
# Or a list can be initialized with a few elements
fruits_list = ['apple', 'banana', 'orange', 'watermelon']
type(fruits_list)
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
list
Lists elements can be data of any type. You can even mix and match!
medley = [True, 42, 'Hello world!', 3.14159]
print(medley)
type(medley)
[True, 42, 'Hello world!', 3.14159]
list
Lists are ordered, meaning they can be indexed to access their elements with square brackets, much like
accessing characters in a str. Remember Python indexes starting at 0!
fruits_list[0]
'apple'
They can also be sliced by providing a range. Remember the end index of the range is excluded in Python slices.
fruits_list[1:3]
['banana', 'orange']
Lists are also mutable, meaning they can change length and their elements can be modified.
# Let's replace apple with pear (modifying an element)
fruits_list[0] = 'pear'
fruits_list
We can also add an element to the end of a list with the .append() method.
fruits_list.append('peach')
fruits_list
Or we can remove and return the last element from a list with pop().
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
fruits_list.pop()
# Notice that 'peach' is no longer in the fruits list
fruits_list
To understand mutability, let’s compare the list with an immutable array-like data type, the Tuple.
(x) Tuples
Tuples in Python are defined with () parentheses.
# Tuples are defined similarly to lists, but with () instead of []
empty_tuple = ()
fruits_tuple = ('apple', 'banana', 'orange', 'watermelon')
type(fruits_tuple)
tuple
Like the str and list, the tuple can be indexed and sliced to access its elements.
fruits_tuple[0]
fruits_tuple[1:3]
By contrast with the list (which is mutable), we get an error if we try to change the elements of the tuple.
fruits_tuple[0] = 'pear'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-3dbfe5bf3508> in <module>
----> 1 fruits_tuple[0] = 'pear'
TypeError: 'tuple' object does not support item assignment
Likewise, we cannot change the length of a tuple once it has been defined, so the .append() and .pop() methods do
not exist.
fruits_tuple.append('peach')
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
(xi) Set
It is an unordered collection of unique and immutable (which cannot be modified) items.
Set in Python are defined with {} parentheses.
e.g. set1={11,22,33,22}
print(set1)
Output: {33, 11, 22}
(xii) Dictionary
It is an unordered collection of items and each item consist of a key and a value.
Dictionary in Python are defined with {key:vaue} parentheses.
e.g. dict = {'Subject': 'comp sc', 'class': '11'}
print(dict)
print ("Subject : ", dict['Subject'])
print ("class : ", dict.get('class'))
Output: {'Subject': 'comp sc', 'class': '11'}
Subject : comp sc
class : 11
Note**: Develop your own logic. Do not use the Python library's ready-made functions. Use break, continue
and pass statements wherever required.
1. Write a program to demonstrate the use of built-in functions: type (), print (), input(), range().
2. Write a program to demonstrate the use of various data types (numeric, sequence, boolean,
set, dictionary). Provide input from user and print the data type of input value.
3. Write a program to Exchange value of two variables.
(a) using third variable (b) without using third variable.
Note for next questions: Take input from user using input() function. If input data is not
in desired format, then provide the error message.
1. Write a program to demonstrate the use of operators like, addition, subtraction,
multiplication, division, modular, exponentiation.
2. Write a program to find area of rectangle, square and circle.
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab
3. Given the principal amount, rate of interest and time. Take suitable data type value as
input from the user. Find the simple interest and compound interest.
4. Write a program to find the odd/ even.
5. Write a program to find the grade of students. Take input marks from user and provide
the output based on NITJ grading system.
6. Write a program to find the maximum between two numbers.
7. Write a program to find the maximum between three numbers.
8. Write a program to check number is positive, negative or zero.
9. Write Python algebraic expressions corresponding to the following statements:
i. The average age of Sara (age 23), Mark (age 19), and Fatima (age 31)
ii. The number of times 73 goes into 403
iii. The remainder when 403 is divided by 73
iv. 2 to the 10th power
v. The lowest price among the following prices: 34.99,34.99,29.95, and $31.50
10. Translate the following statements into Python Boolean expressions and evaluate them:
i. The sum of 2 and 2 is less than 4.
ii. The value of 7 // 3 is equal to 1 + 1.
iii. The sum of 3 squared and 4 squared is equal to 25.
iv. The lowest price among 34.99,34.99,29.95, and 31.50 is less than 31.50 is less than 30.00.
v. The sum of 2, 4, and 6 is greater than 12.
11. Write Python statements that correspond to the actions below and execute them:
a) Assign integer value 3 to variable a.
(b) Assign 4 to variable b.
(c) Assign to variable c the value of expression a a + b b.
12. Start by executing the assignment statements: s1 = 'ant' s2 = 'bat' s3 = 'cod'
Write Python expressions using s1, s2, and s3 and operators + and * that evaluate to:
(a) 'ant bat cod'
(b) 'ant ant ant ant ant ant ant ant ant ant '
(c) 'ant bat bat cod cod cod'
(d) 'ant bat ant bat ant bat ant bat ant bat ant bat ant bat '
(e) 'batbatcod batbatcod batbatcod batbatcod batbatcod '
13. First execute the assignment words = ['bat', 'ball', 'barn', 'basket', 'badminton'] Now write
two Python expressions that evaluate to the first and last, respectively, word in words, in
dictionary order.
Mk- Ckh vkj vECksndj jk"Vªh; izkS|ksfxdh laLFkku] tkya/kj
Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY,
JALANDHAR
Tkh Vh jksM+ ckbZ ikl] tkya/kj&ƒ††Œƒƒ iatkc ¼Hkkjr½
G T Road ByPass, Jalandhar-144011, Punjab (India)
(Under Ministry of Human resource Development (MHRD), Government of India, New Delhi)
DEPARTMENT OF INFORMATION TECHNOLOGY
ITFC0131 Problem Solving using Python Lab