Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 Variables Python loves variables. And Python understands that a variable can be used for different purposes: –Number (both integer and real)radius = 2.5 –Textname = “Martha” –True or Falseleap = 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.

3 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]

4 = versus == In Python (and other languages), we need to distinguish between: –Assigning a value to a variable: x = 5 –Asking if two quantities are equalx == 5 For example, if hours == 40: overtime = False

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 statementprint “$ ”, – 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.

6 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.

7 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)

8 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."

9 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."


Download ppt "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."

Similar presentations


Ads by Google