0% found this document useful (0 votes)
0 views37 pages

Module 02 - Variables and Calculations

This document is a training module for ITM200 - Fundamentals of Programming, focusing on variables and strings. It covers topics such as variable creation, types of data, arithmetic operations, and the importance of naming conventions. Additionally, it discusses constants, comments, and the use of Python libraries and functions.

Uploaded by

Zohaib Afridi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views37 pages

Module 02 - Variables and Calculations

This document is a training module for ITM200 - Fundamentals of Programming, focusing on variables and strings. It covers topics such as variable creation, types of data, arithmetic operations, and the importance of naming conventions. Additionally, it discusses constants, comments, and the use of Python libraries and functions.

Uploaded by

Zohaib Afridi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

1/19/2025

Module 2: Variables and Strings


ITM200 – FUNDAMENTALS OF PROGRAMMING
WINTER 2025

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

• You use an assignment statement to place a value into a variable


cansPerPack = 6 # define & initializes
the variable cansPerPack
• The “=“ sign is NOT used for comparison:
• It copies the value on the right side into the variable on the left side

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

An example: soda deal


• Soft drinks are sold in cans and bottles. A store offers a six-pack of 12-
ounce cans for the same price as a two-liter bottle. Which should you
buy? (12 fluid ounces equal approximately 0.355 liters.)

Variables Type of Number


Number of cans per pack Whole number
Ounces per can Whole number
Ounces per bottle Number with fraction

1/19/2025 6

3
1/19/2025

Why different types?


• Three different primitive types of data that we will use
in this module:
1. A whole number (no fractional part) 7 (integer or int)
2. A number with a fraction part 8.88 (float)
3. A sequence of characters "Bob” (string)

• The data type is associated with the value, not the


variable:
cansPerPack = 6 # int
canVolume = 12.0 # float

1/19/2025 7

Updating a Variable (assigning a value)


• If an existing variable is assigned a new value, that value replaces the
previous contents of the variable.
• For example:
cansPerPack = 6
cansPerPack = 8

1/19/2025 8

4
1/19/2025

Updating a Variable (computed)


• Executing the Assignment:
cansPerPack = cansPerPack + 2
• Step by Step:
• Step 1: Calculate the right hand side of the assignment. Find the value of
cansPerPack, and add 2 to it.

• 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…

taxRate = 5.5 # a float

And then

taxRate = “Non- taxable” # a string

1/19/2025 10

10

5
1/19/2025

Our First Program of the Day…


• Open your IDE and create a new file
• type in the following
• save the file as typetet.ipynb or typetest.py
• Run the program

1. # Testing different types in the same


variable
2. taxRate = 5 # int
3. print(taxRate)
4. taxrate = 5.5 # float
5. print(taxRate)
6. taxRate = "Non-taxable" # string
7. print(taxRate)
8. print(taxRate + 5)
• So…
• Once you have initialized a variable with a value of a particular type you
should take great care to keep storing values of the same type in the
variable

1/19/2025 11

11

A Minor Change
• Change line 8 to read:
print(taxRate + “??”)

• Save your changes


• Run the program

• What is the result?

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

Number Literals in Python

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

Variable Names in Python

1/19/2025 16

16

8
1/19/2025

Programming Tip: Use Descriptive Variable Names


• Choose descriptive variable names
• Which variable name is more self descriptive?
canVolume = 0.35
cv = 0.355
• This is particularly important when programs are written by more than
one person.

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”

• Python will let you change the value of a constant


• Just because you can do it, doesn’t mean you should do it

1/19/2025 18

18

9
1/19/2025

Constants: Naming & Style


• It is customary to use all UPPER_CASE letters for constants to
distinguish them from variables.
• It is a nice visual way cue
BOTTLE_VOLUME = 2 # Constant
MAX_SIZE = 100 # Constant
taxRate = 5 # Variable
• In Python, constants are usually declared and assigned in a module
• a new file containing variables, functions, etc which is imported to the main
file.

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.

• The compiler ignores comments.

1/19/2025 20

20

10
1/19/2025

Commenting Code: 1st Style


##
# This program computes the volume (in liters) of a six-pack of soda
# cans and the total volume of a six-pack and a two-liter bottle
#

# Liters in a 12-ounce can


CAN_VOLUME = 0.355

# Liters in a two-liter bottle.


BOTTLE_VOLUME = 2

# Number of cans per pack.


cansPerPack = 6

# Calculate total volume in the cans.


totalVolume = cansPerPack * CAN_VOLUME
print("A six-pack of 12-ounce cans contains", totalVolume, "liters.")

# Calculate total volume in the cans and a 2-liter bottle.


totalVolume = totalVolume + BOTTLE_VOLUME
print("A six-pack and a two-liter bottle contain", totalVolume,
"liters.")

1/19/2025 21

21

Commenting Code: 2nd Style


##
# This program computes the volume (in liters) of a six-pack of
# soda cans and the total volume of a six-pack and a two-liter
# bottle
#
## CONSTANTS ##
CAN_VOLUME = 0.355 # Liters in a 12-ounce can
BOTTLE_VOLUME = 2 # Liters in a two-liter bottle
# Number of cans per pack.
cansPerPack = 6
# Calculate total volume in the cans.
totalVolume = cansPerPack * CAN_VOLUME
print("A six-pack of 12-ounce cans contains", totalVolume, "liters.")
# Calculate total volume in the cans and a 2-liter bottle.
totalVolume = totalVolume + BOTTLE_VOLUME
print("A six-pack and a two-liter bottle contain", totalVolume,
"liters.")

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

2.2 Operations and


operands

1/19/2025 24

24

12
1/19/2025

Basic Arithmetic Operations


• Python supports all of the basic arithmetic operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
// Floor division x // y
** Exponentiation x ** y

• You write your expressions a bit differently

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

Mixing numeric types


• If you mix integer and floating-point values in an arithmetic
expression, the result is a floating-point value.
7 + 4.0 # yields the floating value 11.0
• Remember from our earlier example:
• If you mix stings with integer or floating-point values, the result is an error

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

• Sometimes called modulo divide

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")

• What is the result?

1/19/2025 31

31

Integer Division and Remainder Examples


• Handy to use for making change:
• pennies = 1729
• dollars = pennies / 100 # 17
• cents = pennies % 100 # 29

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

Calling functions that return a value


• Most functions return a value. That is, when the function completes its
task, it passes a value back to the point where the function was called.
• For example:
• The call abs(-173) returns the value 173.
• The value returned by a function can be stored in a variable:
• distance = abs(x)
• You can use a function call as an argument to the print function
• Go to the python shell window in Wing and type:
print(abs(-173))

1/19/2025 34

34

17
1/19/2025

Built in Mathematical Functions

1/19/2025 35

35

Python libraries (modules)


• A library is a collection of code, written and compiled by someone
else, that is ready for you to use in your program
• A standard library is a library that is considered part of the language
and must be included with any Python system.
• Python’s standard library is organized into modules.
• Related functions and data types are grouped into the same module.
• Functions defined in a module must be explicitly loaded into your program
before they can be used.

1/19/2025 36

36

18
1/19/2025

Using functions from the Math Module


• For example, to use the sqrt() function, which computes the square
root of its argument:

# First include this statement at the top of your


# program file.
from math import sqrt

# Then you can simply call the function as


y = sqrt(x)

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

Functions from the Math Module

1/19/2025 39

39

Floating-point to integer conversion


• You can use the function int() and float() to convert between integer
and floating point values:
balance = total + tax # balance: float
dollars = int (balance) # dollars: integer
• You lose the fractional part of the floating-point value (no rounding
occurs)

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

• Open IDE, open a new file and type in:


price = 4.35
quantity = 100
total = price * quantity
# Should be 100 * 4.35 = 435.00
print(total)

• You can deal with roundoff errors by


• rounding to the nearest integer
• or by displaying a fixed number of digits after the decimal separator.

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?

• Now consider this expression.


(a + b) * t) / (2 * (1 - t)
• This expression has three “(“ and three “)”, but it still is not correct

• At any point in an expression the count of “(“ must be greater than or


equal to the count of “)”
• At the end of the expression the two counts must be the same

1/19/2025 43

43

2.3 Problem Solving


DEVELOP THE ALGORITHM FIRST, THEN WRITE THE
PYTHON

1/19/2025 44

44

22
1/19/2025

2.3 Problem Solving: First by Hand


• A very important step for developing an algorithm is to first carry out
the computations by hand.
• If you can’t compute a solution by hand, how do you write the
program?
• Example Problem:
• A row of black and white tiles needs to be placed along a wall. For
aesthetic reasons, the architect has specified that the first and last
tile shall be black.
• Your task is to compute the number of tiles needed and the gap at
each end, given the space available and the width of each tile.

1/19/2025 45

45

Start with example values


• Givens
• Total width: 100 inches
• Tile width: 5 inches
• Test your values
• Let’s see… 100/5 = 20, perfect! 20 tiles. No gap.
• But wait… BW…BW “…first and last tile shall be black.”
• Look more carefully at the problem….
• Start with one black, then some number of WB pairs

• Observation: each pair is 2x width of 1 tile


• In our example, 2 x 5 = 10 inches

1/19/2025 46

46

23
1/19/2025

Keep applying your solution


• Total width: 100 inches
• Tile width: 5 inches

• Calculate total width of all tiles


• One black tile: 5”
• 9 pairs of BWs: 90”
• Total tile width: 95”

• Calculate gaps (one on each end)


• 100 – 95 = 5” total gap
• 5” gap / 2 = 2.5” at each end

1/19/2025 47

47

Now devise an algorithm


• Use your example to see how you calculated values
• How many pairs?
• Note: must be a whole number
• Integer part of: (total width – tile width) / 2 x tile width

• How many tiles?


• 1 + 2 x the number of pairs

• Gap at each end


• (total width – number of tiles x tile width) / 2

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)

• Calculate the number of tiles


• Number of tiles = 1 + (2 * number of pairs)

• Calculate the gap


• Gap at each end = (total width – number of tiles * tile width / 2

• Print the number of pairs of tiles


• Print the total number of tiles in the row
• Print the gap

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

• In Python, string literals are specified by enclosing a sequence of


characters within a matching pair of either single or double quotes.
print("This is a string.", 'So is this.')
• By allowing both types of delimiters, Python makes it easy to include
an apostrophe or quotation mark within a string.
message = 'He said "Hello"‘
• Remember to use matching pairs of quotes, single with single, double with
double

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

String Concatenation (“+”)


• You can ‘add’ one String onto the end of another
firstName = "Harry"
lastName = "Morgan"
name = firstName + lastName # HarryMorgan
print(“my name is:”, name)
• You wanted a space in between the two names?
name = firstName + " " + lastName # Harry Morgan
• Using “+” to concatenate strings is an example of a concept called
operator overloading.
• The “+” operator performs different functions of variables of different types

1/19/2025 53

53

String repetition (“*”)


• You can also produce a string that is the result of repeating a string
multiple times.
• Suppose you need to print a dashed line.
• Instead of specifying a literal string with 50 dashes, you can use the *
operator to create a string that is comprised of the string "-" repeated
50 times.
dashes = "-" * 50
• results in the string
"-------------------------------------------------“
• The “*” operator is also overloaded.

1/19/2025 54

54

27
1/19/2025

Converting Numbers to Strings


• Use the str() function to convert between numbers and strings.
• Open IDE, then open a new file and type in:
balance = 888.88
dollars = 888
balanceAsString = str(balance)
dollarsAsString = str(dollars)
print(balanceAsString)
print(dollarsAsString)
• To turn a string containing a number into a numerical value, we use
the int() and float() functions:
id = int("1729")
price = float("17.29")
print(id)
print(price)
• This conversion is important when the strings come from user input.

1/19/2025 55

55

Strings and Characters


• strings are sequences of characters
• Python uses Unicode characters
• Unicode defines over 100,000 characters
• Unicode was designed to be able to encode text in essentially all written
languages
• Characters are stored as integer values
• See the ASCII subset on Unicode chart in Appendix A
• For example, the letter ‘H’ has a value of 72

1/19/2025 56

56

28
1/19/2025

Copying a character from a String


• Each char inside a String has an index number:
0 1 2 3 4 5 6 7 8 9

c h a r s h e r e

• The first char is index zero (0)


• The [] operator returns a char at a given index inside a String:
name = "Harry” 0 1 2 3 4
start = name[0] H a r r y
last = name[4]

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

Some Useful String Methods

1/19/2025 60

60

30
1/19/2025

String Escape Sequences


• How would you print a double quote?
• Preface the " with a “\” inside the double quoted String

print("He said \"Hello\"")

• OK, then how do you print a backslash?


• Preface the \ with another \

print("“C:\\Temp\\Secret.txt“")

• Special characters inside Strings *


• Output a newline with a ‘\n’
**
print("*\n**\n***\n") ***

1/19/2025 61

61

2.5 Input and Output

1/19/2025 62

62

31
1/19/2025

Input and Output


• You can read a String from the console with the input() function:
name = input("Please enter your name")

• Converting a String variable to a number can be used if numeric


(rather than string input) is needed
age = int(input("Please enter age: "))

• 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

• To control the output appearance of numeric variables, use formatted


output tools such as:
print("Price per liter %.2f" %(price))
Price per liter: 1.22
print("Price per liter %10.2f" %(price))
Price per liter: 1.22

• The %10.2f is called a format specifier


10 spaces 2 spaces

1/19/2025 64

64

32
1/19/2025

Syntax: formatting strings

1/19/2025 65

65

Format flag examples


• Left Justify a String:
print("%-10s" %("Total:"))

• Right justify a number with two decimal places


print("%10.2f" %(price))

• And you can print multiple values:


print("%-10s%10.2f" %("Total: ", price))

1/19/2025 66

66

33
1/19/2025

Volume2.py

1/19/2025 67

67

Format Specifier Examples

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

Summary: python overview


• The Python library declares many mathematical functions, such as
sqrt() and abs()
• You can convert between integers, floats and strings using the
respective functions: int(), float(), str()
• Python libraries are grouped into modules. Use the import statement
to use methods from a module.
• Use the input() function to read keyboard input in a console window.
• Use the format specifiers to specify how values should be formatted.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy