Lecture 3 - Introduction To Computer Data Processing Using Python
Lecture 3 - Introduction To Computer Data Processing Using Python
COMPUTING
─ Arithmetic expressions
>>> print(3 + 4) # Prints 7
>>> print(7 * 8) # Prints 56
>>> print(45 / 4) # Prints 11.25
>>> print(2 ** 10) # Prints 1024
─ Logical expressions
>>> print(1==2) # Prints False
>>> print(5>3 and '5'>'3’) # Prints True
─ String expressions
>>> r = 'Hello'
>>> print(r + 'World’) # Prints HelloWorld
>>> print(r * 3) # Prints HelloHelloHello
TYPES AND TYPE CONVERSION
• The operations in Python must match the type of
data in order to make sense
• Sometimes Python automatically converts types
>>> x=0b100 # x is binary data
>>> print(x==4) # Prints True
• We can also convert data from one type to another
using suitable type conversion operations
>>> x='127'
>>> y=127
>>> print(x+x)
127127
>>> print(y+y)
254
>>> print(str(y)+x) # 127127
EXAMPLE: BITWISE OPERATIONS
import math
# Inputting the side lengths, first try
sideA = int(input('Length of side A? '))
sideB = int(input('Length of side B? '))
# Calculate third side via Pythagorean
Theorem hypotenuse = math.sqrt(sideA**2 +
sideB**2) print(hypotenuse)
0-18
ERRORS IN PYTHON PROGRAMS
• Syntax errors
- Omissions
>>> print(5 +)
SyntaxError: invalid syntax
- Typing errors (typos)
>>> pront(5)
NameError: name 'pront' is not defined
• Semantic errors
– Incorrect expressions or wrong types like
>>> total_pay = 'Jun Li' + extra_hours * rate
• Runtime errors
- Unintentional divide by zero
EXAMPLE: MARATHON TRAINING ASSISTANT
PROGRAM
# Marathon training assistant.
import math
# This function converts a number of minutes
and # seconds into just seconds.
def total_seconds(min, sec):
return min * 60 + sec
# This function calculates a speed in miles per
# hour given a time (in seconds) to run a
single # mile.
def speed(time):
return 3600 / time
MARATHON TRAINING ASSISTANT
# Prompt user for pace and mileage.
pace_minutes = int(input('Minutes per mile? '))
pace_seconds = int(input('Seconds per mile? '))
miles = int(input('Total miles? '))
# Calculate and print speed.
mph = speed(total_seconds(pace_minutes,pace_seconds))
print('Your speed is ' + str(mph) + ' mph')
# Calculate elapsed time for planned workout.
total = miles *
total_seconds(pace_minutes,pace_seconds)
elapsed_minutes = total // 60
elapsed_seconds = total % 60
print('Your elapsed time is ' + str(elapsed_minutes) +
' mins ' + str(elapsed_seconds) + ' secs')
EXAMPLE MARATHON TRAINING DATA
9 14 5 6.49819494584 46 10
8 0 3 7.5 24 0
7 45 6 7.74193548387 46 30
7 25 1 8.08988764044 7 25