Variables and Data Types
Variables and Data Types
1
6
‣ In the following algorithm there are two variable names
‣ number
‣ square
‣ Algorithm
1. Start
2. number = 3
3. square = number * number
4. Write square
5. Stop
7 Variables and Data Types
‣ As discussed, Variables are reserved memory locations to store
data (values).
‣ When a variable is created, space is reserved in memory.
‣
‣ But, how much memory is reserved?
‣ This would depend on the type of data (or data type) that would
be stored in the variable
‣ The type of data could be numbers, words, or a combination
‣
‣ Therefore, the program needs to tell the computer the data type of
a variable, so that
‣ the computer can allocate sufficient memory and
‣ monitor the type of data that is stored in the reserved memory
location.
‣
‣ Python variables do not need explicit declaration to reserve
memory space.
‣ The declaration happens automatically when you assign a value
to a variable.
‣ The equal sign (=) is used to assign values to variables.
8 Basic Data Types
‣ The data stored in memory can be of many types.
‣ For example,
‣ a person's age is stored as a numeric value
‣ the address is stored as alphanumeric characters (i.e.
numbers and alphabets) .
‣
‣ Python has the following basic data types
‣ Numbers :int, float ,complex
‣ String: set of characters
9
‣ Numbers :int, float ,complex
‣ String: set of characters
‣ Boolean: true and false
‣ List
‣ Tuple
‣ Dictionary
9 Numbers
‣ Python supports three numerical types
‣ int (integers)( whole numbers)
‣ float (floating point real numbers) ( decimal numbers)
‣ complex (complex numbers). ( with variable )
‣ Examples
10 Class Work
1 ‣ Write a program that asks the user for length expressed in Feet.
Your program must convert and display the length in Meters.
2 ‣ Algorithm
‣ Start
‣ Write “Enter length in Feet: “
‣ Read lenFeet
‣ lenMeter = lenFeet * 0.3048
‣ Write “The length in Meter is: “ + lenMeter
‣ Stop
Python:
Feet = int(input("enter the length:"))
lm= feet*0.348
print(" the length in meter is" ,lm)
11 Class Work
# Reading user input
# Length Conversion
main()
int(nameOFvariable)
Float(nameOf varibale)
Str(name of variable)
12 Class Work
‣ Write a program that asks the user for an amount of money in
Dirhams. Your program must convert and display the amount in
US Dollars.
‣ Python:
‣ money =float(input("enter the amount in dirhms" ))
dollars= money/0.3
print("The amount in dirham is:", dollars)
‣ Output:
‣ enter the amount in dirhms456
‣ The amount in dirham is: 1520.0
‣
13 Class Work
‣ The formula for converting temperature in Degree Celsius (C) to
Fahrenheit (F) is as follows:
F = 9/5 x C + 32
‣ Write a Python program to ask the user for the temperature in
Degree Celsius and convert it to Fahrenheit.
‣ Display the result with proper remarks
‣ Ensure that comments are included in the program
‣ Verify the results
Python:
temp=float (input("enter the tempreture"))
F = 9/5 * temp+ 32
print("the temp in F is", F)
Output:
enter the tempreture 90
the temp in F is 194.0
14
1
2
enter the tempreture 90
the temp in F is 194.0
14 Strings
1 ‣ Strings are identified as a contiguous set of characters
represented in a pair of quotation marks.
‣ Python allows for either pairs of single or double quotes.
2 # Data Type - Strings
def main():
string1 = "Hello World!"
print (string1) # Prints the complete string
main()
15 Strings
1 ‣ In Python, subsets of strings can be taken using the slice operator
‣ [ ] and [:]
‣ Indexes start at 0
2 # Data Type - Strings
def main():
string1 = "Hello World!" space between letters is counted as an
index
firstChar = string1[0]
print (firstChar) # Prints first character of the string
secondChar = string1[1:2]
print(secondChar) # Prints second character of the string
print (string1[2:5]) # Prints characters starting from 3rd to 5th
print (string1[2:]) # Prints starting from 3rd character to the end
print (string1[-1]) # Prints the last character of the string
16
17
print (string1[-1]) # Prints the last character of the string
main()
16 Class Work
‣ Write a Python program to ask the user to enter a string and then
print the last character of the string that the user entered.
17 Strings
1 ‣ The plus (+) sign is a string concatenation operator.
2 # Data Type - Strings
def main():
string1 = "College of"
string2 = "Technological"
string3 = "Innovation"
main()
18 Strings
1 ‣ The comma (,) is another string concatenation operator.
2 # Data Type - Strings
def main():
string1 = "College of"
string2 = "Technological"
string3 = "Innovation"
main()
19 Strings
1 The asterisk (*) sign is the string repetition operator.
2 # Data Type - Strings
def main():
string1 = "Hello World!"
print (string1 * 2)
print (string1 * 2)
main()
20 Boolean
1 ‣ The boolean data type, is used to represent truth values i.e. True
and False.
‣ The two truth states can be assigned to variables and can also be
used to evaluate expressions.
‣ For example:
‣ Is 45 > 35? The answer would be: True
‣ Is 89 < 79? The answer would be: False
2 # Data Type – Boolean
def main():
# Boolean values
zero = False
one = True
print (zero)
print (one)
main()
21 Operators
Basic Operators in Python
22 Arithmetic Operators
1 ‣ Basic arithmetic operations:
+, -, *, /, and ** (exponentiation)
‣
‣ The operators can be used with parentheses to force the order of
operations away from normal operator precedence.
2 # Arithmetic Operators
def main():
# basic arithmetic operators
2
print (5+5)
print (90-45)
print (7*2)
print (7/2)
print(2+3*4)
print((2+3)*4)
# power operations
print(2**10)
print(2**100)
main()
23 Operator Precedence
‣ To evaluate expressions with multiple operators, the precedence
of operators are used
‣
‣
‣
‣
‣ Operators in 1 have a higher precedence than operators in 2
‣ When operators have the same level of precedence, operations
are performed from left to right
‣ Evaluate result in the following expressions (on paper) then verify
using Python:
‣ result = 3 + 4 * 5
‣ result = 3 * (7 – 6) + 2 * 5 / 4 + 6
‣ result =7.0 + 3 * 8 + 2 / 10
24 Arithmetic Operators
# Arithmetic Operators
def main():
# division operations
print(6/3)
print(7/3)
print(7//3) # integer division
print(7/3)
print(7//3) # integer division
print(3/6)
print(3//6) # integer division
main()
25 Class Work
‣ A box of cookies can hold 24 cookies and a container can hold 75
boxes of cookies. Write a program that prompts the user to enter
the total number of cookies. The program then outputs the number
of boxes and the number of containers to ship the cookies. Note
that each box must contain the specified number of cookies and
each container must contain the specified number of boxes. If the
last box of cookies contains less than the number of specified
cookies, you can discard it, and output the number of leftover
cookies. Similarly, if the last container contains less than the
number of specified boxes, you can discard it, and output the
number of leftover boxes.
26 Relational Operators
1 ‣ Relational operators are used to compare values
‣ The result of a comparison is always a truth value (True or False)
2 # Relational Operators
def main():
result = (56 > 55)
print("Greater Than:", result)
result = (56<55)
print ("Less Than:", result)
result = (56 == 55)
print("Equal To:", result)
result = (56!=55)
print ("Not Equal To:", result)
main()
27 Logical Operators
1 ‣ The Logical operators are:
2
27 Logical Operators
1 ‣ The Logical operators are:
‣ and
‣ or
‣ not
‣ Relational and logical operators can be combined to result in truth
values, True or False.
2 # Logical Operators
def main():
x = True
y = False
# Output: x or y is True
print('x or y is', x or y)
main()
28 Example
# Logical operators and operations
def main():
print(False and True) # result is False
print((55>56) and (55==55)) # result is False
# not operation
zero = False
one = True
print(not zero) # result is True
29
30
one = True
print(not zero) # result is True
31 main()
29 Assignment Operators
30 Class work
‣ Suppose x, y, and z are variables and x=2, y=5, and z=6. What is
the output of each of the following statements?
32 a. print("x = " + str(x) + ", y = " + str(y) + ", z = " + str(z))
b. print("x + y = " + str(x + y))
c. print("Sum of "+ str(x) + " and "+ str(z) + " is "+ str(x+z))
d. print("z / x = " + str(z / x))
e. print("2 times " + str(x) + " = " + str(2 * x))
33
31 Class work
‣ Write a program that prompts the user to enter the capacity, in
litres, of an automobile’s fuel tank and the kilometres per litres the
automobile can be driven. The program then outputs the number
of kilometres the automobile can be driven without refuelling.
32 Class work
‣ Write a Python program that prompts the user to input the elapsed
time for an event in seconds. The program then outputs the
elapsed time in hours, minutes, and seconds. (For example, if the
elapsed time the
d. Outputs is 9630
profitseconds, then the
for producing milkoutput is 2:40:30.)
33
34 More on Strings
String Manipulations
35 String Manipulation
1 ‣ Python uses some built-in methods to manipulate strings
‣ It is very beneficial to know and use these while programming
2 # String Manipulation
def main():
word = "Hello World"
# determine the length of the string
print(len(word))
34
main()
35
36
1
2
main()
36 String Manipulation
# String Manipulation
def main():
word = "Hello World"
print(word.count('l')) # count how many times l is in the string
print(word.count(' ')) # count the spaces is in the string
print(word.find("W")) # location of the character W in the string
print(word.index("World")) # find the location of the letters World
in the string
main()
37 String Manipulation
# String Manipulation
def main():
word = "Hello World"
main()
38 In Summary
‣ Keywords
‣ Identifiers
‣ Variables
‣ Reserving memory space and good variable names
‣ Data Types
‣ Numbers, Strings, Boolean
‣ Operators
‣ Arithmetic Operators
‣ Relational Operators
‣ Logical Operators
‣ String Manipulations