pythonQuick
pythonQuick
Programming
with Python
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be
used in a particular programming language.
output: The messages printed to the user by a program.
2
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile
source code byte code outpu
Hello.java execute
Hello.class t
interpret
source code outpu
Hello.py t
3
The Python Interpreter
•
Python is an interpreted >>> 3 + 7
language
10
•
The interpreter provides >>> 3 < 15
an interactive True
environment to play with
the language >>> 'print me'
'print me'
•
Results of expressions are
>>> print 'print me'
printed on the screen
print me
>>>
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication, division
% modulus, a.k.a. remainder
** exponentiation
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
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
A variable that has been given a value can be used in expressions.
x + 4 is 9
10
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 1
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
will not print a newline 'hello', 'there'
character hello there
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
1
Input: Example
print "What's your name?"
name = raw_input("> ")
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
16
range
The range function specifies a range of
integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
17
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
18
if
if statement: Executes a group of statements only if a
certain condition is true. Otherwise, the statements are
skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
19
if/else
if/else statement: Executes one block of statements if a
certain condition is True, and a second block of statements if it is
False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print
"Welcome to
Mars
University!
"
else:
print "Your
application
is denied."
Multiple conditions 21
Example of If Statements
import math
x = 30
if x <= 15 : y >>> import ifstatement
= x + 15 y = 0.999911860107
>>>
elif x <= 30
In interpreter
:
y = x + 30
else :
y=x
print ‘y = ‘,
Inprint
file ifstatement.py
math.sin(y)
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
2
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
%python forloop1.py
% python forloop2.py
1
0
7
1
13
2
2
3
4 [0,1, …, n-1]
range(N) generates a list of numbers
More Data Types
Everything is an object
Everything means
>>> x = 7
everything, >>> x
including 7
functions and >>>
classes (more on x=
'hello'
this later!) >>>
Data type is a x
property of the 'hello'
>>>
object and not
of the variable
Numbers: Integers
Integer – the
equivalent of a C long >>> 132224
Long Integer – an 132224
unbounded >>> 132323 **
2
integer value. 17509376329L
>>>
Numbers: Floating
Point
int(x) converts x to >>> 1.23232
1.2323200000000001
an integer
>>> print 1.23232
float(x) converts x
1.23232
to a floating >>> 1.3E7
point 13000000.0
The interpreter >>> int(2.0)
2
shows >>> float(2)
a lot of digits 2.0
Numbers: Complex
+ is overloaded to do
concatenation >>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
String Literals
Can use single or double quotes, and
three double quotes for a multi-line
string
insert>
Can usually just use %s for everything,
Ordered Pairs of values
Unordered list
Python Collections (Arrays)
There are four collection data types in the Python
programming language:
• List is a collection which is ordered and changeable.
Allows duplicate members.
• Set is a collection which is unordered, unchangeable*,
and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and
changeable. No duplicate members.
Lists
Ordered collection of data
Data can be of different types
list.insert(i,x)
Insert item at a given position.
Similar to a[i:i]=[x]
list.remove(x)
Removes first item from the list with value x
list.pop(i)
Remove item at position I and return it. If no index I is given then
list.count(x)
Return the number of time x appears in the list
list.sort()
Sorts items in the list in ascending order
list.reverse()
Reverses items in the list
Sets
A set is another python data structure that is an unordered
collection with no duplicates.
>>> setA=set(["a","b","c","d"])
>>> setB=set(["c","d","e","f"])
>>> "a" in setA
True
>>> "a" in setB
False
Dictionaries