4

I'm trying to teach my son how to program & I gave him a challenge that I can't do myself.

He has to prompt the user to enter A, B, or C. Depending on their choice, he'll print some results & other stuff. While we got this working, I'm trying to do some error handling & check for cases where the input is not A, B, or C. The code is listed below. I certainly appreciate any guidance you can offer.

print "************************************************************"
print "*                                                          *"
print "*            Welcome to the cinemas                        *"
print "*                                                          *"
print "************************************************************"
print "*                                                          *"
print "*  What movie would you like to see ?                      *"
print "*                                                          *"
print "*  A) Star Wars                                            *"
print "*  B) Bourne Identity                                      *"
print "*  C) The Hunger Games                                     *"
print "*                                                          *"
print "************************************************************"
movie=raw_input()
while(movie!="A","B","C"):
    print "************************************************************"
    print "*                                                          *"
    print "*            Welcome to the cinemas                        *"
    print "*                                                          *"
    print "************************************************************"
    print "*                                                          *"
    print "*  What movie would you like to see ?                      *"
    print "*                                                          *"
    print "*  A) Star Wars                                            *"
    print "*  B) Bourne Identity                                      *"
    print "*  C) The Hunger Games                                     *"
    print "*                                                          *"
    print "************************************************************"
    movie=raw_input()

print "************************************************************"
print "*                                                          *"
print "*  How many tickets would you like ?                       *"
print "*                                                          *"
print "************************************************************"
quantity =input()
cost = 7.5
if movie =="A":
    print "You are seeing Star Wars"
    price = cost*quantity
    print "You owe ", price
elif movie =="B":
    print "You are seeing Bourne Identity"
    price = cost*quantity
    print "You owe ", price
elif movie =="C":
    print "You are seeing The Hunger Games"
    price = cost*quantity
    print "You owe ", price 
11
  • 4
    Python has multi-line string literals (triple quotes, """blah""") - use them rather than a load of print statements! (Better yet, generate those strings automatically - you are changing very little). Commented Jan 21, 2013 at 3:39
  • 1
    Also note that this program has a classic problem of repeating yourself, not only in the strings but in your logic too. Basing your program around a good data structure (a dict of {"A": "Star Wars", "B": "Bourne Identity", "C": "The Hunger Games"} would seem appropriate here. Commented Jan 21, 2013 at 3:42
  • 1
    And as a final note, using input() in 2.x is a bad idea! If you want an integer of the user, then use int(raw_input()) instead! Commented Jan 21, 2013 at 3:42
  • 1
    @sidi it eval's the input. You're better off using something like ast.literal_eval(raw_input(... or when the desired type is known, explicitly use that one Commented Jan 21, 2013 at 3:46
  • 2
    @sidi Potentially, anything that gets typed in there gets executed. Anything could happen. It's exactly why input() was removed from 3.x in that form (it functions like raw_input() from 2.x). Commented Jan 21, 2013 at 3:48

3 Answers 3

7

You want to do while movie not in ("A", "B", "C").

movie != "A", "B", "C" checks whether movie is equal to the three-element tuple ("A", "B", "C"), which it never will be.

Sign up to request clarification or add additional context in comments.

Comments

1

Here are a couple of better ways to structure your loop to avoid repetition.

First way is to set the movie to an invalid value, this means the loop will always execute at least once

movie = None
while movie not in ("A", "B", "C"):
    print "************************************************************"
    print "*                                                          *"
    print "*            Welcome to the cinemas                        *"
    print "*                                                          *"
    print "************************************************************"
    print "*                                                          *"
    print "*  What movie would you like to see ?                      *"
    print "*                                                          *"
    print "*  A) Star Wars                                            *"
    print "*  B) Bourne Identity                                      *"
    print "*  C) The Hunger Games                                     *"
    print "*                                                          *"
    print "************************************************************"
    movie = raw_input()

The second way is to use a while True: loop

while True:
    print "************************************************************"
    print "*                                                          *"
    print "*            Welcome to the cinemas                        *"
    print "*                                                          *"
    print "************************************************************"
    print "*                                                          *"
    print "*  What movie would you like to see ?                      *"
    print "*                                                          *"
    print "*  A) Star Wars                                            *"
    print "*  B) Bourne Identity                                      *"
    print "*  C) The Hunger Games                                     *"
    print "*                                                          *"
    print "************************************************************"
    movie = raw_input()
    if movie in ("A", "B", "C"):
        break

Then you can work on storing the movies in a variable as Alex suggests

Comments

1

Also, instead of printing each line, you could use a multi-line string:

welcometext = """
************************************************************
*                                                          *
*            Welcome to the cinemas                        *
*                                                          *
************************************************************
*                                                          *
*  What movie would you like to see ?                      *
*                                                          *
*  A) Star Wars                                            *
*  B) Bourne Identity                                      *
*  C) The Hunger Games                                     *
*                                                          *
************************************************************"""

That way, your program can be pretty compact:

print welcometext
movie = raw_input(">>")
while movie.upper() not in ("A","B","C"):
    print welcometext
    movie = raw_input(">>")

If you'd like to do something a bit more advanced:

movies = {
    "A": "Star Wars", 
    "B": "Bourne Identity", 
    "C": "The Hunger Games", 
    "D": "Kill Bill"
}

welcometext = """
************************************************************
*                                                          *
*            Welcome to the cinemas                        *
*                                                          *
************************************************************
*                                                          *
*  What movie would you like to see ?                      *
"""

for letter, movie in movies.items():
    welcometext += "*  {}) {: <52} *\n".format(letter, movie)

# ( <52 is for padding 52 spaces, \n is for the newline )

welcometext += """*                                                          *
************************************************************"""

movieletter = ''
while movieletter.upper() not in movies:
    print welcometext
    movieletter = raw_input(">>")

moviename = movies[movieletter.upper()]
print "You have selected {}!".format()

Then later on you could add prices etc to the movies dict too. Enjoy!

8 Comments

I know I suggested it, but one flaw, dicts are unordered, you might want to use collections.OrderedDict() or a list of tuples. Also, while movieletter.upper() not in movies: would be a good idea. It'd also make more sense just to set movieletter = None at the start, not print the welcometext, and let the loop deal with it, rather than repeating yourself.
Also, repeated concatenations are bad, use str.join() instead: "\n".join(["* {}) {:<52} *".format(key, item) for key, item in movies.items()])
@Lattyware Ah, I just read the comments. (I'm slow to reply) Great minds :) You're right about the order - if this was important then he could run it through sorted (i.e. letter, movie in sorted(a.items(), key=lambda x: x[0]):) or list of tuples (as well as an OrderedDict()).
@Lattyware I thought I'd try and keep it as simple as possible - if you use join then you really need to understand generator expressions/list comprehension. I don't think this is a particularly performance critical situation :)
@AlexL, I think plenty of people use join() without understanding generator expressions/list comprehension. In particular it's pretty common to use it with a list which is what you would be doing using dict.items() in Python2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.