Transcript here
Python Programming - Goals
By the end of this unit, you will be able to:
• Understand the difference between
interactive and script mode in IDLE
• Understand variables, subroutines, loops
and branches, strings, and lists in Python
• Get input from the user and display output
• Draw simple graphics
• Understand the importance of proper
software documentation and testing
Interactive and Script Modes in IDLE
• IDLE is the Python programming environment we will use in this
class
• IDLE has two modes: interactive (called shell in "The Way of the
Program") and script
• In interactive mode, you type a command and it is executed right
away.
• In script mode, you write a set of commands into a file (called a
Python script, ending in .py) and then execute the script:
Two ways to run IDLE
• There are two shortcuts on your desktop, one for
IDLE, the other "IDLE for graphics". IDLE for
graphics starts IDLE in a special mode that is
required for the Livewires graphics package that
we use.
when you start IDLE, it looks like this:
when you start "IDLE for graphics", it looks like this:
(If your graphics program doesn't work, this could be the reason!)
Variables in Python
Programs use variables when they need to ”remember”
some information. A variable allows you to give a name
to a piece of information stored in a computer. You can
then read the value, or set it to something different in
another part of your program.
myName = "Mr. Judkis" # set the value
print myName
myAge = 22
myAge = myAge + 1
# get the value
# set the value
# get it and set it
You cannot get a value before it has been set! Python will
complain:
>>> foo = foo + 1
NameError: name 'foo' is not defined
Rules and Guidelines for Variables
Rules for naming variables:
• Variables can contain only letters, numbers, and underscores
• Variables cannot begin with numbers
• Variables cannot be any of the Python reserved words (listed
below)
Guidelines for naming variables:
• Names should be descriptive – score instead of s (except
for variables that are used only briefly)
• Variable names should be consistent within the program:
high_score and low_score or highScore and lowScore
• Variable names shouldn’t start with underscores or uppercase
letters
• Variable names shouldn’t be too long - generally no longer
than 15 chars
Reserved Words in Python
the following words are all special:
•
•
•
•
•
•
•
•
•
and
assert
break
class
continue
def
del
elif
else
•
•
•
•
•
•
•
•
•
except
exec
finally
if
in
lambda
not
or
pass
•
•
•
•
•
•
print
raise
return
try
while
yield
Do the following variable names obey the rules? The guidelines?
•
•
•
•
•
•
blah
x
routeLength
first-name
lambda
last_name
•
•
•
•
•
•
24_hour_count
twentyFourHourCountValue
_height
Width
while
length
Integers, Floats, and Strings
• An int is an integer number.
my_int = 7
• A float (floating point) is a number that includes some fractional part,
using a decimal point.
my_float = 3.1415926
• You can do arithmetic with integers and floats, and you can combine
them:
>>> print my_int + my_float
10.1415926
• A string is a sequence of ASCII characters. You can’t do arithemetic on
a string.
my_str = "howdy"
• You can convert some strings to integers or floats:
my_str = "3213"
my_int = int(my_str)
• You can convert any integer or float to a string:
my_int = 3213
my_str = str(my_int)
• Adding integers and/or floats does the arithmetic, but adding strings
concatenates them (sticks them together):
>>> print my_str + " pardner"
howdy pardner
Integers, Floats, and Strings - 2
• If you try to convert a string into an int or float and there’s a problem,
Python will let you know:
>>> int("hi there")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in -toplevelint("hi there")
ValueError: invalid literal for int(): hi there
• If you try to combine numbers and strings in some way that doesn’t
make sense, Python will let you know:
>>> print "hi there" + 7
Traceback (most recent call last):
File "<pyshell#4>", line 1, in ?
print "hi there" + 7
TypeError: cannot concatenate 'str' and 'int' objects
• Why is this okay?:
>>> print "hi there" + str(7)
hi there7
Okay, now you try it. . .
Getting input from the user: raw_input()
string_val = raw_input("prompt",)
raw_input() always gives you what the user entered as a
string. If you want to get an integer or floating point
number, it’s up to you to do the conversion:
int_val = int(raw_input("enter integer:",))
– or –
int_val = raw_input("enter integer:",)
int_val = int(int_val)
float_val = float(raw_input("enter float:",))
– or –
float_val = raw_input("enter float:",)
float_val = float(float_val)
Giving output: the print statement
Separate values to be printed by commas:
print "The values are", min, "and", max,"."
Python will insert spaces between each value, and print:
The values are 6 and 10 .
Or, you can concatenate values to create your own string, controlling
the spacing yourself:
print "The values are " + str(min)
+ " and " + str(max) + "."
Python will print:
The values are 6 and 10.
In script mode, a comma at the end of the print statement will keep the
next output on the same line:
Code:
print “My name is”,
print “Johnny”
print “My name is”
print “Johnny”
Output:
My name is Johnny
My name is
Johnny
Comments
• Your python scripts should always start off with the program
name, a brief description of what it does, your name, and the date.
Like this:
# guess_num.py
# Picks a random number, then asks the user
# to guess it
# Ima Programmer 12/23/05
• Also include comments whenever the code may not be easy to
understand, like this:
# use the pythagorean formula to calculate
# the distance between the points
distance = math.sqrt((x1 –x2)**2 + (y1-y2)**2)
Program File Structure
# program file name
# brief description of what it does
# your name, date created
Then import statements
Then all subroutine definitions
Finally, the "main line" of the code
put a blank line between each subroutine, and between each
section. put additional blank lines anywhere they improve
readability
Assignment and Equality
=
A single equal sign
means assignment: The value on the
right is assigned to the variable on the left:
counter = 88
numTries = numTries + 1
==
Double equal
tests for equality: the expression is True if
the values on either side are equal:
if yourName == "Mr. Judkis":
print "So handsome!"
else:
print "meh"
Other comparisons:
counter = 10
while counter > 0:
print counter
counter = counter – 1
print "Blast off!"
Greater than
>
Greater
than/equal
>=
Less than
<
Less than/equal
<=
Not equal
<>
Not equal
!=
Example
if yourIQ > 120:
print "perfect for AAHS!"
elif yourIQ >= 100:
print "perfect for MAST"
elif yourIQ >= 80:
print "maybe CHS"
else:
print "definitely HTHS. . . sorry"
Combining logical tests
Testing for several different conditions:
resp = raw_input("Do you want to quit?")
if resp == "Yes" or resp == "yes":
print "Bye!"
Don't do this:
resp = raw_input("Do you want to quit?")
if resp == "Yes" or "yes":
print "Bye!"
It won't do what you want it to do!
Arithmetic
Op
Example
Augmented
Assignment
Add
+
x = x + 5
x += 5
Subtract
-
x = x – 5
x -= 5
Multiply
*
x = x * 5
x *= 5
Divide
/
x = x / 5
x /= 5
Modulus
(remainder)
%
x = x % 5
x %= 5
Exponentiation
**
x = x ** 3
x **= 3
for loop
We saw this in RUR-PLE – a loop that runs the indented
block of code a set number of times.
for count in range(500):
print "I will not be late to class"
This is also sometimes known as a
counting loop. Compare this to the
while loop. . .
while loop
number = 1
while number < 1000:
print number,
number *= 2
1 2 4 8 16 32 64 128 256 512
The following program makes you guess a password:
guess = ""
while guess != "Fizzing Whizbee":
guess = raw_input("what is the password?“, )
print "You may enter."
The while is a conditional loop – it runs until some condition
is not true
Guessing Game, Take 1:
import random
print "I'm thinking of a number between 1 and 20."
numToGuess = random.randint(1,20)
userGuess = int(raw_input("Give a guess:"))
while userGuess != numToGuess:
print "Nope, try again"
userGuess = int(raw_input("Give a guess:"))
print "You got it!"
break
The break statement immediately pops you out of the for or while loop
your program is in, regardless of how many times you’ve run through it, or
whether the loop condition is true or false. Think of it as a jailbreak. . .
Guessing Game, Take 2:
import random
print "I'm thinking of a number between 1 and 20."
numToGuess = random.randint(1,20)
while True:
userGuess = int(raw_input("Give a guess:"))
if userGuess == numToGuess:
print "You got it!"
break
else:
print "Nope, try again"