Pythonquick 1 15
Pythonquick 1 15
with Python
Python Review. Modified slides from Marty Stepp and Moshe Goldstein
1
Programming basics
code or source code: The sequence of instructions in a program.
2
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
interpret
source code output
Hello.py
3
The Python Interpreter
5
Integer division
When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
More examples:
35 / 5 is 7
84 / 10 is 8
156 / 100 is 1
6
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
7
Math commands
Python has useful commands (or called functions) for performing
calculations.
Constant Description
Command name Description
e 2.7182818...
abs(value) absolute value
pi 3.1415926...
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
>>> x = 7
>>> x
7
>>> x+7
14
>>> x = 'hello'
>>> x
'hello'
>>>
print
print : Produces text output on the console.
Syntax:
print "Message"
print Expression
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
Prints several messages and/or expressions on the same line.
Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
12
Example: print Statement
•Elements separated by
commas print with a space
between them >>> print 'hello'
•A comma at the end of the
hello
statement (print ‘hello’,) >>> print 'hello', 'there'
will not print a newline hello there
character
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
14
Input: Example
print "What's your name?"
name = raw_input("> ")
% python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 31