Module 2:
Data Types and Control Flows
Samira Nigrel
1
Topics
• Literals, reserved words and input functions
• Data Types: int, float, bool, str
• Decision Control Flows: If / Nested If / If-else / If-elif-else
• Control Flow Loops: While loop, For loop, While-else, For-
else
• Operators: Arithmetic, Relational or Comparison, Logical
2
Variables
• What are Variables?
x=1
y = 2.0
name = "Paul"
3
Variables …
Rules for Python variables:
● A variable name must start with a letter or the
underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _)
● Variable names are case-sensitive (age, Age and AGE
are three different variables)
4
Print in python
print("Hello World")
x=10
print(x)
print(*objects, sep=' ', end='\n', file=[Link],
flush=False)
5
Escape Sequences
6
Literals
Literals are the raw data that are assigned to variables or
constants while programming.
• String literals
• Numeric literals
• Boolean literals
7
Reserved Words
8
Input Functions
>>> name=input()
Samira
>>> print("Hey!" My name is " + name)
Hey! My name is Samira
9
Comments
Comments starts with a #, and Python will ignore them
print("Hello, World!") #This is a comment
What if I want to add multiline comment?
10
Data Types: Boolean
Boolean is nothing but True (1) and False (0) statements.
Their sole purpose is to evaluate conditions.
For example:
Is 2 < 3?
Yes, so it will return a value True.
11
Data Types:Numbers
Numeric Types: It is used to store numeric values.
For example:
x=5,
y = 10,
balance = 15,000 etc.
Python supports three different types of numbers, listed as follows:
● Int (integers)
● Float (decimal numbers)
● Complex (complex numbers)
12
Data Types
Determining the Type of Object with type()
If you are confused about what class an object belongs to simply use the type() function.
For example:
print(type(x))
13
Data Types
Checking Instance Type with isinstance()
The isinstance() function checks if the object (first argument) is an
instance or a subclass of classinfo (second argument).
syntax is: isinstance(object, classinfo)
For example:
isinstance(x, int)
returns True while
isinstance(y, int)
returns False
14
Data Types
Type Conversion
During data manipulation, there might arise a need for converting an
integer to float, float to an integer, float to a string, or splitting on a
decimal point in a float. Let's look at how you can do this.
Let's say you have number x. The following are some common
operations:
● int(x) converts it to an integer.
● float(x) converts it to a float.
● complex(x) converts it to a complex number with real part x and
imaginary part 0.
15
Data Types
Calculate the Compound Interest
In this problem, you will calculate the compound interest (C.I.).
Remember that the formula for compound interest for amount
after n years is A = P(1 + r/100)^n
Here, A is the Amount after n years, r is the rate of interest,
and P is the principal.
Your task is to calculate the amount after two years on a
principal amount of USD 1000 at the rate of 10 % p.a.
16
Data Types:Strings
A string is a collection of alphabets, words, or characters represented with
the help of quotation marks. Python has a built-in class for str to handle
string-related operations.
Wrap an object within quotes to denote it as a string.
● Single quotes: Example: name = 'Paul'
● Double quotes: Example: name = "Paul"
● Triple quotes: They are used so that we can work with multi-line strings,
and all associated whitespace will be included in the string.
Example: """This is a function. Do not change it or else it will not work"""
17
Common Operations on string
A=“Hello”
B=“World”
Operator Description Example
Concatenates two or more
+ a+b gives "HelloWorld"
strings
Repetition: Creates new
* strings, concatenating multiple a*2 gives "HelloHello"
copies of the same string
Range Slice: Gives the
[:] characters from the given a[1:4]will give "ell"
range
Membership: Returns true if a
in character exists in the given H in a will give 1
string
Membership: Returns true if a
not in character does not exist in the M not in a will give 1
given string
18
Common Built-in String Methods
Method Description
len() Length of the string
Determines if a string or a substring of string (if
starting index beg and ending index end are
startswith(str, beg=0,end=len(string))
given) starts with substring str; returns true if
so, and false otherwise
Determines if a string or a substring of a string
(if starting index beg and ending index end are
endswith(suffix, beg = 0, end = len(a))
given) ends with suffix; returns true if so,
and false otherwise
Converts all uppercase letters in a string to
lower()
lowercase
Converts all lowercase letters in a string to
upper()
uppercase
Splits a string according to delimiter str (space
split(str="", num=[Link](str)) if not provided) and returns a list of substrings,
split into at most num substrings if given
19
String Formatting
20
Perform String Operations
Follow the instructions below to carry out string operations like concatenation, indexing,
slicing, etc.:
● Two variables name and title with values of your choice.
● Concatenate (+) name and title and save it to variable called full_name. (Note: Add a
whitespace between name and title while concatenating)
● Use slicing to pick up the first name from full_name and save it to a first_name variable.
● Calculate the length of the full name using the len() function. Subtract 1 from it (so that
you get rid of the whitespace) and save it to a len_name variable.
● Check whether the alphabet "f" is in the full name and save it to a is_f variable.
● Now, split the full name back into first name and title using the .split() method on
the full_name variable. Save it to a split variable. The output will come as a list which is
another important data structure. You will learn more about it in the next chapter.
● Print the full_name, first_name, len_name, is_f and split variable to check your results
21
What are Operators
Operators are special symbols
Python supports the following types of operators:
● Arithmetic Operators
● Comparison (Relational) Operators
● Logical Operators
● Membership Operators
● Assignment Operators
● Bitwise Operators
● Identity Operators
● Ternary Operators
22
Arithmetic Operators
Operator Description Example
+(Addition) Adds values on either side of the operator 2+4
Subtracts the right hand operand from left
- (Subtraction) 4-2
hand operand
Multiplies values on either side of the
* (Multiplication) 2*4
operator
Divides the left hand operand by the right
/ (Division) 4 / 2 = 2.0
hand operand
Divides the left hand operand by the right
% (Modulus) 4%2=0
hand operand and returns remainder
Exponential (power) calculation on
** (Exponent) 4^2
operators
Division of operands where the result is
the quotient and the digits after the
9//2 = 4, 9.0//2.0 = 4.0, -
decimal point are removed. But if one of
// (Floor Division) 11//3 = -4, -11.0//3 = -
the operands is negative, the result is
4.0
floored, i.e., rounded away from zero
(towards negative infinity):
23
Do Some Mathematics
You are given two numbers x = 15 and y = 4.
Instructions
● Perform addition. Save it to an addition variable and print it out.
● Perform subtraction. Save it to a subtraction variable and print out the
result.
● Perform multiplication. Save it to a multiplication variable and print out
the result.
● Perform division. Save it to a division variable and print out the result.
● Perform integer division. Save it to an integer_division variable and
print out the result
● Perform exponentiation (x^y), Save it to anexponent variable and print
out the result.
24
Comparison Operators
Operator Description Example
If the values of the two operands are equal, then the
== (4 == 4) is true
condition becomes true
If values of the two operands are not equal, then the
!= (2!= 4) is true
condition becomes true
If the value of the left operand is less than the value of
> (2 > 4) is false
the right operand, then the condition becomes false
If the value of the left operand is less than the value of
< (2 < 4) is true
the right operand, then the condition becomes true
If the value of the left operand is less than or equal to
>= the value of the right operand, then the condition (2 >= 4) is false
becomes false
If the value of the left operand is less than or equal to
<= the value of the right operand, then the condition (2 <= 4) is true
becomes true
25
Compare Two Numbers
In this task, you will perform comparison operations using two numbers, x
= 10 and y = 12. These variables are already declared for you.
● Calculate if the output of condition x is greater than y and save it
as is_greater.
● Calculate if the output of condition x is less than y and save it
as is_less.
● Calculate if the output of condition x is equal to y and save it
as is_equal.
● Calculate if the output of condition x is greater than or equal to y and
save it as is_greater_equal.
● Calculate if the output of condition x is less than or equal to y and save
it as is_less_equal.
● Print out all the variables created.
26
Logical Operators
Operator Description Example
and (Logical If both the operands are true, (True and False) is
AND) then condition becomes true False
If any of the two operands are
or (Logical OR) non-zero then condition (True or False) is True
becomes true
not (Logical Used to reverse the logical
not(False) is True
NOT) state of its operand
27
Do Logical Comparison
In this task, you will use logical operators to perform some simple
operations using two variables, x = True and y = False.
● Calculate the output of the AND operation between x and y and save it
as x_and_y.
● Calculate the output of the OR operation between x and y and save it
as x_or_y.
● Print out x_and_y and x_or_y
28
Membership Operators
Operator Description Example
Evaluates to true if it finds a x in y, here in results in a 1
in variable in the specified sequence if x is a member of
and false otherwise sequence y
Evaluates to true if it does not finds x not in y, here not in results
not in a variable in the specified in a 1 if x is not a member of
sequence and false otherwise sequence y
29
Check the Membership
In this task, you will check if some element is in an iterable list with the
help of membership operators.
Instructions
● You are given a variable name = "John".
● Check whether the variable is in the list ["John", "Rick"] and save the
result in a variable called john.
● Check whether the variable is in the list ["Hall", "Rick"] and save the
result in a variable called hall.
● Print out both john and hall.
30
Assignment Operators
Operator Description Syntax
Assign value of right side of
= x=y+z
expression to left side operand
Add and Assign: Add right side
+= operand with left side operand a += b
and then assign to left operand
Subtract AND: Subtract right
operand from left operand and
-= a -= b
then assign to left operand:
True if both operands are equal
Multiply AND: Multiply right
*= operand with left operand and a *= b
then assign to left operand
Divide AND: Divide left operand
/= with right operand and then a /= b
assign to left operand
Modulus AND: Takes modulus
using left and right operands
%= a %= b
and assign result
31 to left
operand
Assignment Operators
Operator Description Syntax
Divide(floor) AND: Divide left operand
//= with right operand and then assign the a //= b
value(floor) to left operand
Exponent AND: Calculate
exponent(raise power) value using
**= a **= b
operands and assign value to left
operand
Performs Bitwise AND on operands and
&= a &= b
assign value to left operand
Performs Bitwise OR on operands and
|= a |= b
assign value to left operand
Performs Bitwise xOR on operands and
^= a ^= b
assign value to left operand
Performs Bitwise right shift on operands
>>= a >>= b
and assign value to left operand
Performs Bitwise left shift on operands
<<= a <<= b
and assign value to left operand
32
Bitwise Operators
OPERATOR NAME DESCRIPTION SYNTAX
Result bit 1,if both operand
& Bitwise AND bits are 1;otherwise results x&y
bit 0.
Result bit 1,if any of the
| Bitwise OR operand bit is 1; otherwise x|y
results bit 0.
~ Bitwise NOT inverts individual bits ~x
Results bit 1,if any of the
operand bit is 1 but not
^ Bitwise XOR x^y
both, otherwise
results bit 0.
The left operand’s value is
moved toward right by the
>> Bitwise right shift number of bits x>>
specified by the right
operand.
The left operand’s value is
moved toward left by the
<< Bitwise left shift number of bits x<<
33specified by the right
operand.
Identity Operators
Operator Description Example
is Returns true if both x is y
variables are the same
object
is not Returns true if both x is not y
variables are not the same
object
34
Ternary Operators
Determines if a condition is true or false and then returns the
appropriate value in accordance with the result.
Syntax: [on_true] if [expression] else [on_false]
35
Decision control flows: If
if condition:
#statement to be executed if true
E.g. check if user input is even
36
Using Indentation to create blocks
• You may have noticed that the second line of the if
statement is indented.
• By indenting the line, it becomes the block,
• A block is one or more consecutive lines indented by the
same amount.
• Indenting the sets lines off not only visually, but also it is
logical and together it form a single unit.
37
Tab Vs Space
• There is a passionate debate within the python community
about whether to use tabs or space for indentation.
• This is really a question of personal style.
• But there are two guidelines worth following:-
• First is be consistent.
• If you use space then use the space always.
• Second, do not mix the space and tab.
• Even though you can line up blocks using the combination
of both, this can lead to big headache later.
Commonly used style is one tab or four spaces.
38
Decision control flows: If-else
if condition:
#statement to be executed if true
else:
#execute this if condition is false
39
Decision control flows: nested If
if condition1:
#statement to be executed if condition 1 is true
if condition 2:
#statement to be executed if condition 2 is
true
40
Decision control flows: If-elif
if condition:
#statement to be executed if condition is true
elif condition:
#statement to be executed if condition is true
.
.
.
else:
#statement to be executed if condition is false
41
Is the number positive or negative?
In this task you are going to make use of the if-elif-else statement to find
out if a number is positive, negative or zero.
● A variable num = 5 is given along with another variable
condition=None (captures the state of num)
● Put the conditions for checking whether the number is positive (+) ,
negative (-) or zero (0) using if-elif-else construct.
● If num is greater than 0 set condition=positive. Print out the variable
condition.
● Else num is less than 0, set condition=negative. Print out the variable
condition.
● Else num is equal to 0 set condition=zero. Print out the variable
condition.
42
Control Flow Loops: while
With the while loop we can execute a set of statements
as long as a condition is true.
E.g.
i=1
while i < 6:
print(i)
i += 1
43
The break Statement
With the break statement we can stop the loop even if
the while condition is true:
E.g.
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
44
The continue Statement
With the continue statement we can stop the current
iteration, and continue with the next:
E.g.
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i) 45
The while-else Statement
With the else statement we can run a block of code
once when the condition no longer is true:
E.g.
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
46
Find multiples of 10
In this task you will be using a while loop to iterate over natural numbers from 1
to 100 and store only the multiples of 10 in a list and print that list
● Initialize an empty list factors and a variable num equal to 1
● Set the condtion in the while loop until the variable num is less than or equal
to 100
● Check using an if statement whether the variable is divisible by 10 and if is,
append that number(i.e. num) to factors
● Increment the variable num by 1 post checking the above condition. (note
that this increment will be outside the if statement, take care of the
indentation in order to avoid a scenario of infinite loop)
● Print out the factors list
47
For Loops
A for loop is used for iterating over a sequence (that is
either a list, a tuple, a dictionary, a set, or a string).
E.g.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
48
The range() Function
To loop through a set of code a specified number of
times, we can use the range() function
E.g.
for x in range(6):
print(x)
49
Else in For Loop
The else keyword in for loop specifies a block of code to be
executed when the loop is finished:
E.g.
for x in range(6):
print(x)
else:
print("Finally finished!")
50
Nested Loops
A nested loop is a loop inside a loop.
E.g.
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
51
Find numbers divisible by 2 or 3
In this task you will learn how to use a for loop and conditionals by making
a list of natural numbers less than or equal to 50 which are divisible by 2 or
3.
● Iterate over a range using the range() function from 1to 51 using the for
loop
● Initialize an empty list named divisible to store your results
● Use the if statement to check if the iterable is divisible by 2 or 3, and if
yes, then append it to the list created in the above step
● Print divisible
52
Recap
• Literals, reserved words and input functions
• Data Types: int, float, bool, str
• Decision Control Flows: If / Nested If / If-else / If-elif-else
• Control Flow Loops: While loop, For loop, While-else, For-
else
• Operators: Arithmetic, Relational or Comparison, Logical
53