2/12/2014 1
CSCI 1101B Introduction to Python Mohammad T . Irfan New office - - PDF document
CSCI 1101B Introduction to Python Mohammad T . Irfan New office - - PDF document
2/12/2014 CSCI 1101B Introduction to Python Mohammad T . Irfan New office hours: M 10-12, Th 3-5 2/4/14 Basic Elements of Python 1 2/12/2014 Statement print Welcome to Python print Whats your name? total = 0
2/12/2014 2
Statement
print ‘Welcome to Python’ print “What’s your name?” total = 0 x = [10, 20, 5] for number in x: total = total + number print total
Function (example from lab)
Header Body – must use indentation
Function name Parameters
def oddEven():
xStr = raw_input('Enter a number: ') x = int(xStr) if x%2 == 0: print x, 'is even' else: print x, 'is odd'
More on functions later
- n ...
2/12/2014 3
Objects
Scalar – 4 types
int (example: -10000, 200, 53) float (example: -37.59, 28.0) bool (example: True, False) None
Non-scalar
String (example: “hello”, “57”) And many other ... (You will define and create
your own non-scalar objects later on)
Expressions
Arithmetic
x + y x – y x * y x/y
Caution: when x and y are both int, then the result is
also int (Python 2.7 truncates all decimal digits after the decimal point) – it’s called “integer division”
Better practice: Use x//y when x and y are both int
// operator specifically means integer division
x % y: remainder of the division x/y for int x & y x ** y: x raised to the power y comparison: == (equal), != (not eq), >, >=, <, <=
Precedence – usual
2/12/2014 4
Expressions
Logical operators (on bool)
a and b a or b not a
Variable: named storage space
def area(): pi = 3.14159 r = 10 area = pi * r**2 print area
You don’t need to specify type of a variable –
it’s automatically determined
Naming a variable
Must start with a letter (upper or lower case) or _,
may contain digits
Use sensible names. Cannot use reserved words.
Variables and assignment
Note the indentation
2/12/2014 5
Conditional Statements
if-else
An if block can be optionally
associated with an else block def oddEven():
x = int(raw_input('Enter a number: ')) if x%2 == 0: print x, 'is even' else: print x, 'is odd'
Note the indentation
2/12/2014 6
if-elif-else
if block, followed by any number of elif blocks,
followed by an optional else block def showMinimum(x, y, z): if x < y and x < z: print x, 'is min' elif y < z: print y, 'is min' else: print z, 'is min‘
Note: parameter passing to a function To “call” this function from JES, load it first and
then enter the following command into the black window
showMinimum (20, 30, 5)
if statements can be nested
Recap
2/12/2014 7
Scalar vs. non-scalar types
12
Integers Floats Strings
- 12
31,364
0.01 12.998 34,654.01 1.01 Mark Bowdoin College 85 5th Street NW Inside the computer, these are all just bits
Quiz
What would be the output of the following?
print 1/2
2/12/2014 8
Values & names with the same value are interchangeable!
>>> print 12 * 3 36 >>> value = 12 >>> print value 12 >>> print value * 3 36 >>> name = "Mark" >>> print name Mark >>> print name * 3 MarkMarkMark >>> print "Mark" * 3 MarkMarkMark
Non-scalar Type: String
2/12/2014 9
String
Examples
“Hello and welcome” “Bowdoin College”
Assignment statement
college = “Bowdoin College”
What is the difference between “57” and 57?
Main difference is representation You can apply all arithmetic operators on 57
57 + 2 57 * 2
Arithmetic operations are meaningless for
“57”
“57” + 2
# ERROR
“57” * 2
# ‘5757’
2/12/2014 10
Operations on String
college = “Bowdoin College” Length of a string
len(college)
# 15 Indexing
college[2]
# ‘w’
college[-1]
# ‘e’
college[-2]
# ‘g’ Slicing
college[0:2]
# ‘Bo’
college[0:len(college)]
# ‘Bowdoin College’ Splitting
college.split()
# ['Bowdoin', 'College']
Taking a string as input
x = raw_input (‘Enter your name’) y = raw input (‘How old are you?’)
Suppose user enters 20 as his/her age y’s value is “20”, not 20 if you want to convert string “20” to number 20,
y = int(y) # Can use a different variable name on LHS
2/12/2014 11
Iterative Statements/ Loops
for loop
General form (not actual code)
for loop_variable in sequence:
body of for loop
Visualization of for loop
Use boxes to replace the for loop
2/12/2014 12
range function
sequence is commonly specified using the
built-in range function with 3 parameters:
start (optional, default is 0) end (must, actually ends before this value) increment (optional, default is 1)
Examples
range(10, 70, 20)
# [10, 30, 50]
range (0, 5, 1)
# [0, 1, 2, 3, 4]
range (0, 5)
# [0, 1, 2, 3, 4]
range (5)
# [0, 1, 2, 3, 4]
for loop example: Finding the average – 2 ways average.py
Caution: integer division!
Better to write: avg = float(total)/len(x)
Loop variable: Choose any name you want