80 likes | 211 Vues
Practice 1. Write a program that gets text from the user. Count the number of uppercase letters and print this out. Ex: “Hi There!” -> “2 uppercase letters”. Solution 1. text = raw_input ("Please enter some text: ") upper_count = 0 for i in range(0, len (text), 1):
E N D
Practice 1 • Write a program that gets text from the user. Count the number of uppercase letters and print this out. • Ex: “Hi There!” -> “2 uppercase letters”
Solution 1 text = raw_input("Please enter some text: ") upper_count = 0 for i in range(0, len(text), 1): if text[i].lower() != text[i]: # if text[i].upper() == text[i]: upper_count += 1 print "I found", upper_count, "upper case letters. "
Solution 2 text = raw_input("Please enter some text: ") upper_count = 0 for letter in text: if letter >= 'A' and letter <= 'Z': upper_count += 1 print "I found", upper_count, "upper case letters. "
Compare solution 1 & 2 for i in range(0, len(text), 1): if text[i].lower() != text[i]: upper_count += 1 for letter in text: if letter >= 'A' and letter <= 'Z': upper_count += 1
Practice 2 • “The farm” book The Farm by Mary Fried Here is the pig. oink-oink Here is the cow. moo-moo Here is the horse. nee-nee Here is the farm. Diaosaurs by Nanet George I see two dinosaurs. I see four dinosaurs. I see six dinosaurs. I see eight dinosaurs. I see ten dinosaurs. A dinosaur family!
Solution 1 (using ONE list) animals = (("pig", "oink-oink"), ("cow", "moo-moo"), ("horse", "nee-nee")) #animals = [["pig", "oink-oink"], ["cow", "moo-moo"], ["horse", "nee-nee"]] #using a nested sequence for animal in animals: print "Here is the", animal[0] + ". " + animal[1] + ". ” print "Here is the farm."
Solution 2 (using TWO lists) print "The Fram by Mary Fried" animals = ("pig", "cow", "horse") sounds = ("oink-oink", "moo-moo", "nee-nee") for idx in range(len(animals)): print "Here is the " + animals[idx] + ". " + sounds[idx] + "." print "Here is the farm."
What do you get? print "The Fram by Mary Fried" animals = ("pig", "cow", "horse") sounds = ("oink-oink", "moo-moo", "nee-nee") for animal in animals: for sound in sounds: print "Here is the " + animal + ". " + sound + "." print "Here is the farm."