Module 02 - Variables and Calculations
Module 02 - Variables and Calculations
Contents
2.1 Variables
2.2 Operators and operands
2.3 Problem Solving: First Do It By Hand
2.4 Strings
2.5 Input and Output
1/19/2025 2
1
1/19/2025
2.1 Variables
1/19/2025 3
Variables
• A variable is a named storage location in a computer program
• There are many different types of variables, each type used to store
different things
• You ‘create’ a variable by telling the compiler:
• What name you will use to refer to it
• The initial value of the variable
1/19/2025 4
2
1/19/2025
Variable Definition
• To create a variable, you must specify an initial value.
• The value on the right of the '=' sign is assigned to the variable on the
left
1/19/2025 5
1/19/2025 6
3
1/19/2025
1/19/2025 7
1/19/2025 8
4
1/19/2025
• Step 2: Store the result in the variable named on the left side of
the assignment operator
1/19/2025 9
Association
• The data type is associated with the value and not the variable:
• A variable can be assigned different values at different places in a program
taxRate = 5 # an int
Then later…
And then
1/19/2025 10
10
5
1/19/2025
1/19/2025 11
11
A Minor Change
• Change line 8 to read:
print(taxRate + “??”)
When you use the “+” operator with strings the second argument is
concatenated to the end of the first
1/19/2025 12
12
6
1/19/2025
1/19/2025 13
13
Naming variables
• Variable names should describe the purpose of the variable
• ‘canVolume’ is better than ‘cv’
• Use These Simple Rules
1. Variable names must start with a letter or the underscore ( _ )
character
• Continue with letters (upper or lower case), digits or the
underscore
2. You cannot use other symbols (? or %...) and spaces.
• They are not permitted
3. Separate words with ‘camelCase’ notation
• Use upper case letters to signify word boundaries
4. Don’t use ‘reserved’ Python words
1/19/2025 14
14
7
1/19/2025
Python Keywords
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
Continue global pass
1/19/2025 15
15
1/19/2025 16
16
8
1/19/2025
1/19/2025 17
17
Constants
• A constant is a variable whose value should not be changed after it’s
assigned an initial value.
• It is a good practice to use all caps when naming constants
BOTTLE_VOLUME = 2.0
• It is good style to use named constants to explain numerical values to
be used in calculations
• Which is clearer?
totalVolume = bottles * 2
totalVolume = bottles * BOTTLE_VOLUME
• A programmer reading the first statement may not understand the
significance of the “2”
1/19/2025 18
18
9
1/19/2025
1/19/2025 19
19
Python comments
• Use comments at the beginning of each program, and to clarify details
of the code
• Comments are a courtesy to others and a way to document your
thinking
• Comments to add explanations for humans who read your code.
1/19/2025 20
20
10
1/19/2025
1/19/2025 21
21
1/19/2025 22
22
11
1/19/2025
Undefined Variables
• You must define a variable before you use it: (i.e. it must be defined
somewhere above the line of code where you first use the variable)
canVolume = 12 * literPerOunce
literPerOunce = 0.0296
• The correct order for the statements is:
literPerOunce = 0.0296
canVolume = 12 * literPerOunce
1/19/2025 23
23
1/19/2025 24
24
12
1/19/2025
1/19/2025 25
25
Precedence
• Precedence is similar to Algebra:
• PEMDAS
• Parenthesis, Exponent, Multiply/Divide, Add/Subtract
• Examples
8 / 4 + 5 * (3 + 1) - 7 % 4
1/19/2025 26
26
13
1/19/2025
1/19/2025 27
27
Powers
• Double stars ** are used to calculate an exponent
• Analyzing the expression:
• Becomes:
• b * ((1 + r / 100) ** n)
1/19/2025 28
28
14
1/19/2025
Floor division
• When you divide two integers with the / operator, you get a floating-
point value. For example,
7/4 # Yields 1.75
• We can also perform floor division using the // operator.
• The “//” operator computes the quotient and discards the fractional part
7 // 4
• Evaluates to 1 because 7 divided by 4 is 1.75 with a fractional part of 0.75,
which is discarded.
1/19/2025 29
29
Calculating a remainder
• If you are interested in the remainder of dividing two integers, use the
“%” operator (called modulus):
remainder = 7 % 4
• The value of remainder will be 3
1/19/2025 30
30
15
1/19/2025
A Simple Example:
• Open a new file in your IDE:
• Type in the following:
# Convert pennies to dollars and cents
pennies = 1729
dollars = pennies // 100 # Calculates the number of dollars
cents = pennies % 100 # Calculates the number of pennies
print("I have", dollars, "and", cents, "cents")
1/19/2025 31
31
1/19/2025 32
32
16
1/19/2025
Calling functions
• Recall that a function is a collection of programming instructions that
carry out a particular task.
• The print() function can display information, but there are many other
functions available in Python.
• When calling a function you must provide the correct number of
arguments
• The program will generate an error message if you don’t
1/19/2025 33
33
1/19/2025 34
34
17
1/19/2025
1/19/2025 35
35
1/19/2025 36
36
18
1/19/2025
1/19/2025 37
37
Built-in Functions
• Built-in functions are a small set of functions that are defined as a part
of the Python language
• They can be used without importing any modules
1/19/2025 38
38
19
1/19/2025
1/19/2025 39
39
1/19/2025 40
40
20
1/19/2025
Arithmetic Expressions
1/19/2025 41
41
Roundoff Errors
• Floating point values are not exact
• This is a limitation of binary values; not all floating-point numbers have an
exact representation
1/19/2025 42
42
21
1/19/2025
Unbalanced Parentheses
• Consider the expression
((a + b) * t / 2 * (1 - t)
• What is wrong with the expression?
1/19/2025 43
43
1/19/2025 44
44
22
1/19/2025
1/19/2025 45
45
1/19/2025 46
46
23
1/19/2025
1/19/2025 47
47
1/19/2025 48
48
24
1/19/2025
The algorithm
• Calculate the number of pairs of tiles
• Number of pairs = integer part of (total width – tile width) / (2 * tile width)
1/19/2025 49
49
2.4 Strings
1/19/2025 50
50
25
1/19/2025
Strings
• Start with some simple definitions:
• Text consists of characters
• Characters are letters, numbers, punctuation marks, spaces, ….
• A string is a sequence of characters
1/19/2025 51
51
String Length
• The number of characters in a string is called the length of the string.
(For example, the length of "Harry" is 5).
• You can compute the length of a string using Python’s len() function:
length = len("World!") # length is 6
• A string of length 0 is called the empty string. It contains no characters
and is written as "" or ''.
1/19/2025 52
52
26
1/19/2025
1/19/2025 53
53
1/19/2025 54
54
27
1/19/2025
1/19/2025 55
55
1/19/2025 56
56
28
1/19/2025
c h a r s h e r e
1/19/2025 57
57
String Operations
1/19/2025 58
58
29
1/19/2025
Methods
• In computer programming, an object is a software entity that
represents a value with certain behavior.
• The value can be simple, such as a string, or complex, like a graphical
window or data file.
• The behavior of an object is given through its methods.
• A method is a collection of programming instructions to carry out a specific
task – similar to a function
• But unlike a function, which is a standalone operation, a method can
only be applied to an object of the type for which it was defined.
• Methods are specific to a type of object
• Functions are general and can accept arguments of different types
• You can apply the upper() method to any string, like this:
name = "John Smith"
# Sets uppercaseName to "JOHN SMITH"
uppercaseName = name.upper()
1/19/2025 59
59
1/19/2025 60
60
30
1/19/2025
print("“C:\\Temp\\Secret.txt“")
1/19/2025 61
61
1/19/2025 62
62
31
1/19/2025
• The above is equivalent to doing it two steps (getting the input and then
converting it to a number):
aString = input("Please enter age: ") # String input
age = int(aString) # Converted to int
1/19/2025 63
63
Formatted output
• Outputting floating point values can look strange:
Price per liter: 1.21997
1/19/2025 64
64
32
1/19/2025
1/19/2025 65
65
1/19/2025 66
66
33
1/19/2025
Volume2.py
1/19/2025 67
67
1/19/2025 68
68
34
1/19/2025
2.6 Summary
1/19/2025 69
69
Summary: variables
• A variable is a storage location with a name.
• When defining a variable, you must specify an initial value.
• By convention, variable names should start with a lower-case letter.
• An assignment statement stores a new value in a variable, replacing
the previously stored value.
1/19/2025 70
70
35
1/19/2025
Summary: operators
• The assignment operator = does not denote mathematical equality.
• Variables whose initial value should not change are typically
capitalized by convention.
• The / operator performs a division yielding a value that may have a
fractional value.
• The // operator performs a division, the remainder is discarded.
• The % operator computes the remainder of a floor division.
1/19/2025 71
71
Summary: Strings
• Strings are sequences of characters.
• The len() function yields the number of characters in a String.
• Use the + operator to concatenate Strings; that is, to put them
together to yield a longer String.
• In order to perform a concatenation, the + operator requires both
arguments to be strings. Numbers must be converted to strings using
the str() function.
• String index numbers are counted starting with 0.
• Use the [ ] operator to extract the elements of a String.
1/19/2025 72
72
36
1/19/2025
1/19/2025 73
73
Summary: Strings
• Strings are sequences of characters.
• The len() function yields the number of characters in a String.
• Use the + operator to concatenate Strings; that is, to put them
together to yield a longer String.
• In order to perform a concatenation, the + operator requires both
arguments to be strings. Numbers must be converted to strings using
the str() function.
• String index numbers are counted starting with 0.
• Use the [ ] operator to extract the elements of a String.
1/19/2025 74
74
37