Download oct15

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Law of large numbers wikipedia , lookup

Proofs of Fermat's little theorem wikipedia , lookup

Addition wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
CS 101 – Oct. 15
• Common elements in solutions
–
–
–
–
Types of variables
Traversing values in a list
Assigning vs. checking if equal
Printing things on the same line
• Examples and practice 
Variables
• Python loves variables. And Python understands
that a variable can be used for different purposes:
– Number (both integer and real)
– Text
– True or False
radius = 2.5
name = “Martha”
leap = True
• Caution: if you want to divide two numbers, you
should use real numbers. For example, one-third
should be 1.0/3.0 because 1/3 is dividing integers,
which equals 0.
Traversing a list
• We want to visit each element. Two ways to do
this:
L = [ 5, 4, 7, 3, 2, 6, 1]
for number in L:
print L
for i in range (0, 7):
print L[i]
= versus ==
• In Python (and other languages), we need to
distinguish between:
– Assigning a value to a variable:
– Asking if two quantities are equal
For example,
if hours == 40:
overtime = False
x=5
x == 5
Output
• The “print” statement is designed to display a line
of text, and then go on to the next line.
Sometimes we want to continue output on the
same line.
• Two approaches
– Put comma at end of statement
print “$ ”,
– Tell Python you want to print several things.
However, if you are printing both text and numbers,
you need to put str( ) around the number.
– See list.py example.
Examples
• Ask the user for the length and width of a
rectangle. Output the area and perimeter.
• Ask the user what 7+5 is. Tell user if the
answer is correct or not.
• Count how many numbers in a list equal 5.
Rectangle
# rectangle.py
# Find area and perimeter of user’s rectangle.
length = input(“What is the length?”)
width = input(“What is the width?”)
area = length * width
perimeter = 2 * (length + width)
print "The area is " + str(area)
print "The perimeter is " + str(perimeter)
User Quiz
# quiz.py
# See if the user knows what 7+5 is.
answer = input(“What is 7 plus 5?”)
if answer == 12:
print "Good job!"
else:
print "Sorry, that’s not correct."
Count the 5’s
# count5.py
# Count the 5’s in a list
L = [ 5, 4, 2, 5, 1, 2, 5 ]
fives = 0
for number in L:
if number == 5:
fives = fives + 1
print "I found " + str(fives) + " fives."