1. Recap Python
programming of the
previous week
• Python script files rules: one statement per line,
each statement starting in the 1st column
• A simple program contains 3 steps: Input,
Processing, Output
• Input involves assigning values to variables. It can
be done with assignment lines (such as a = 12) or
by reading the values from the keyboard (such as a
= int(input(‘Enter the value of a:’)) ). Note that
int() and input() are Python functions.
• Processing involves operations with the variables
• Output to the black screen involves the use of the
print() function
Slides are adapted from prof Radu I Campeanu
3. Assignment statements
• In a program, a variable is a named item, such as a, used to hold a value.
• An assignment statement assigns a value to a variable, such as a = 4.
• ‘=‘ has nothing to do with mathematics. In computer programming it means
assignment, i.e. it gives the value 4 to the variable a.
• a = b means that the value of b is copied into a; as a result both variables a and
b have the same value.
• a = a+1 means that the value of a is incremented by 1. An alternative is to write
a +=1 (the meaning of ‘+=‘ is increment by the value on the right)
4. Objects
• Python variables are also called objects.
• Each Python object has three properties: value, type, and identity.
- Value: A value such as 4 or "abcdef".
- Type: The type of the object, such as integer or string.
- Identity: A unique identifier that describes the object
(i.e. its address in the principal memory).
a=4
print(a) # Output: 4
print(type(a)) # Output: <class ‘int’>
print(id(a)) # Output: 140728879073924
5. Floating-point numbers
• Floating-point numbers are real number, like 98.6 or 0.0001.
• The built-in function float() is used for these numbers, which have decimals.
#P1 calculate hours to cover the distance
miles = float(input('Enter a distance in miles: '))
hours_to_fly = miles / 500.0 #500 miles/hour is the speed to fly
hours_to_drive = miles / 60.0 #60 miles/hour is the speed to drive
print(miles, 'miles would take:')
print(hours_to_fly, 'hours to fly')
print(hours_to_drive, 'hours to drive’)
Input/Output:
Enter a distance in miles: 450
450.0 miles would take:
0.9 hours to fly
7.5 hours to drive
6. Scientific notation
• Scientific notation is useful for representing floating-point numbers that are much greater
than or much less than 0, such as 6.02x1023
• 6.02x1023 is written as 6.02e23
• Float-type objects can be stored on a 32 bits (or 4 bytes) computer if their values are
between 2.3x10-308 and 1.8x10308
• Outside this interval the float-type object produces underflow/overflow.
• Ex. print(2**1024) will produce an overflow error (‘2**1024’ means 2 to the
power 1024). Note that print() accepts mathematical expressions, which are executed before
the display of the result.
7. Formatting floating-point output
• Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers
such as the value of Pi = 3.14159265359…
• Python has the method format() which allows the reduction of the number of decimals
#P2
pi_v = 3.141592653589793
print('Default output of Pi:', pi_v)
print('Pi reduced to 4 digits after the decimal:', end=' ')
print('{:.4f}'.format(pi_v))
Output:
Default output of Pi: 3.141592653589793
Pi reduced to 4 digits after the decimal: 3.1416
8. Arithmetic Expressions
• An expression is a combination of items, like variables, operators, and parentheses, that evaluates
to a value. For example: 2 * (x + 1).
• A common place where expressions are used is on the right side of an assignment statement, as in
y = 2 * (x + 1).
• The arithmetic operators are: +, -, *, /, %, **
• % is the modulo operator producing the remainder of an int division
• ** is the exponent, or power operator
• In a long expression the following precedence rules will apply:
- operations inside parentheses are executed first
- unary minus and the exponent are executed next (ex. x* -2, 2 * x**2)
- next are *,/,% in the left-to-right order
- last are +, - in the left-to-right order
9. Examples
• total_cost = down_payment + payment_per_month * num_months
• 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4.
• 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0.
• 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1.
• 20 / 10 is 2.0 (Division with ‘/’ produces a float)
• 50 / 50 is 1.0
• 5 / 10 is 0.5
• 20//10 is 2 (‘//’ is the floored division operator; produces an int)
• print(12 - 1 / 2 * 3 % 4 + 10 / 2 * 4) produces 30.5
10. Example 1 - money
The program shown below shows the calculation of the number of $5 bills for a certain integer
amount. What is the output if the input is 19?
#P3
amount_to_change = int(input())
num_fives = amount_to_change // 5
num_ones = amount_to_change % 5
print('Change for $', amount_to_change)
print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar coin(s)’)
Ans:
Change for $ 19
3 five dollar bill(s) and 4 one dollar coin(s)
11. Example 2 - time
The program shown below extracts the number of hours from an input of minutes. What will be
the output for 275 ?
#P4
minutes = int(input('Enter minutes:'))
hours = minutes // 60
minutes_remaining = minutes % 60
print(minutes, 'minutes is', end=' ')
print(hours, 'hours and', end=' ')
print(minutes_remaining, 'minutes.n', end=' ‘)
Input/Output
Enter minutes: 275
275 minutes is 4 hours and 35 minutes
12. Digits in an integer
The last digit in 23 is obtained by: 23%10
The last 3 digits in 1234 are obtained by:
1234%1000
The first digit in 23 is obtained by: 23//10
The first digit in 1234 is obtained by: 1234//1000
13. Example 3 - Telephone
number
#P5
nr = int(input('Enter a 10 digit integer:'))
tmp = nr // 10000 #tmp will have the value 103458
mid = tmp % 1000 #mid will have the value 458
first = nr // 10000000 #first will have the value 103
last = nr % 10000 #last will have the value 8231
print('(',first,') ',mid,'-',last) #notice the brackets and -
Input/Output:
Enter a 10 digit integer: 1034588231
( 103 ) 458 - 8231
14. Using modules
• Programmers often write code in more than just a single script file. Collections of logically
related code can be stored in separate files, and then imported for use into a script that
requires that code.
• A module is a file containing Python code that can be used by other modules or scripts.
• A module is made available for use via the import statement.
• Once a module is imported, any object defined in that module can be accessed using dot
notation.
• Python comes with a number of predefined modules, such as math and random.
15. Using the random module
• Python has a randrange() function as part of the module random. This function creates a
random integer between the function parameters.
import random
print(random.randrange(1,10)) # the dot notation
Output:
6 # a random number between 1 and 10
• An alternative is:
from random import randrange
print(randrange(1,10))
Output:
8 # another random number between 1 and 10
16. Equation Solutions using the
math module
The solutions for the equation ax2 + bx + c = 0 are:
𝑥1 =
−𝑏 + 𝑑
2𝑎
and 𝑥2 =
−𝑏 − 𝑑
2𝑎
, where d = b2 - 4ac
Write a Python program which enters from the keyboard the values of a, b, c (as integers) and then calculates and
shows x1 and x2.
#P6
import math
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = int(input('Enter the value of c:'))
d = b*b - 4*a*c;
x1 = (-b + math.sqrt(d))/2/a
x2 = (-b – math.sqrt(d))/2/a
print('x1=', x1)
print('x2=', x2)
17. Using the math module
Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the
absolute value of (x minus y), and the square root of (x to the power of z).
#P7
import math
x=float(input()) # enter 5.0
y=float(input()) # enter 1.5
z=float(input()) # enter 3.2
v1=x**z
v2=x**(y**z)
v3=math.fabs(x-y)
v4=math.sqrt(x**z)
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(v1,v2,v3,v4))
Output:
172.47 361.66 3.50 13.13
18. Using the random module
• Write a Python program which rolls two dice. This program should use the module random.
#P8
import random
a = random.randrange(1,6)
b = random.randrange(1,6)
print(‘the sum is ‘, a+b)
Possible Output:
the sum is 10
19. Using Constants in Python
• Constants are variables which have values that cannot be changed during the execution of the program
• In other programming languages such as C constants are written in capital letters. In Java one uses the reserved
word final in front of the constant to ensure that its value cannot be changed.
• Python does not have a way to enforce that the value of a constant is not changed. A good method to signal that
certain variables are constants is to create a constants module.
20. Creating and using the constants module
The time of a free falling object from a certain height is given by the following
formula: time = (2 ∗ height / g), where g is the gravitational constant.
In this program let us compare the times for falls on Earth and Mars.
constants.py # user defined module
# Gravitational constants for various planets
earth_g = 9.81 # m/s**2
mars_g = 3.71
========================================================
fall_time.py
#P9
# Find seconds to drop from a height on some planets.
import constants
import math # module available in Python
height = int(input('Height in meters: ')) # Meters from planet
print('Earth:', math.sqrt(2 * height / constants.earth_g), 'seconds')
print('Mars:', math.sqrt(2 * height / constants.mars_g), 'seconds’)
# notice the dot notation for functions and constants
21. Class exercise - Distance
between two points
The distance between point (x1, y1) and point (x2, y2) is given by the formula:
(x2 − x1)∗∗2 + (y2 − y1)∗∗2 .
All these variables have floating - point numbers.
Write a Python program which reads the coordinates of the 2 points and shows the value of
the distance, shown as a floating – point number with 3 decimals.
For example if the 4 numbers entered are 1.1, 2.2, 4.4 and 5.5
The output should be: Points distance: 4.667