JCJeff, on 12 May 2012 - 01:14 PM, said:
Sorry, if I post here too much but I have yet another problem.
The question I want to solve is:
1. A soccer team is looking for girls from ages 10 to 12 to play on their team. Write a program
to ask the user’s age and if male or female (using “m” or “f”). Display a message
indicating whether the person is eligible to play on the team.
2. Bonus: Make the program so that it doesn’t ask for the age unless the user is a girl.
Can someone help me? I want to answer both separately
age = raw_input("How old are you?")
if age == 10 or 11 or 12:
gender = raw_input("Are you a boy or girl?")
if gender == "boy" or "girl":
print "you are eligible to play!"
if age != 10 or 11 or 12:
print "sorry,you cannot play."
Firstly, in if statements when you separate them with 'or'/'and' then you have to write an entire different clause. I know this is slightly unintuitive (especially in Python) because its different from natural language, but it'd be something like
if age == 10 or age == 11 or age == 12
A more concise way to do it though would be to say
if age in range(10, 13):
Secondly, if you only want to make it ask if the user is male then you'd want to ask that first.
gender = raw_input("Are you a boy or girl? ")
if gender == "boy":
print "You are eligible to play"
elif gender == "girl":
age = raw_input("How old are you? ")
if age in range(10, 13):
print "You are eligible to play"
else:
print "You can't play. Sorry!"
else:
print "You can't play. Sorry!"
An even better way to do this (where you aren't repeating yourself quite so much) would be to have a function (something like canPlay) which when called, asks the user the relevant questions and returns true (if they can play) and false (if they can't). You can then just call that function and print depending on what it returns. The advantage of this is that if you want to change your messages you only have to do it in one place instead of multiple (the disadvantage being, of course, that you can't have a different error message for girls to boys or whatever).