elif function error in code - python

I am brand new to Python and am trying to build a text based game.
The first question is "How old are you?"
How can I use if/else statements to print a certain message when the user doesn't input his age.
for instance if the user inputs a character instead of a letter I want to print "please enter a digit, not characters" or if the user inputs a digit smaller than 12 I want to print "You are not old enough" and if the user inputs a digit greater or equal to 12 I want to say "Welcome"
I have written some code to try and do this myself and spent about 4 hours on it but can't figure it out.
This is my block of code:
input_age = raw_input("What is your age, " + input_name + "? ")
if len(input_age) == 0:
print("You didn't enter anything")
elif input_age < 12 and input_age.isdigit():
print("Sorry, you are not old enogh to play")
elif input_age >= 12 and input_age.isdigit():
print ("Welcome")
else:
print("You entered a character or characters instead of a digit or digits")
For some reason the elif on line 4 gets skipped or something because even if i enter 4 as my age it still carries on and prints "Welcome" instead of "You are not old enough"

#roganjosh is right, raw_input returns a string, so you have to do the below:
input_age = raw_input("What is your age, " + input_name + "? ")
if not input_age:
print("You didn't enter anything")
elif input_age.isdigit():
if int(input_age) < 12 :
print("Sorry, you are not old enogh to play")
elif int(input_age) >= 12:
print ("Welcome")
if not input_age.isdigit():
print("You entered a character or characters instead of a digit or digits")

Related

Python program for soccer odds

match = input('Enter match? ')
odd1 = input("Enter tip for home: ")
if(not odd1.replace(".","").isnumeric()):
print("Sorry home tip is not numeric")
exit(0)
if(float(odd1)<=1):
print("Odd cannot be less than one")
exit(0)
odd2 = input("Enter tip for draw: ")
if(not odd2.replace(".","").isnumeric()):
print("Sorry draw tip is not numeric")
exit(0)
if(float(odd2)<=1):
print("Odd cannot be less than one")
exit(0)
odd3 = input("Enter tip for away: ")
#isnumberic() is it number
if(not odd3.replace(".","").isnumeric()):
print("Sorry your tip is not numeric")
exit(0)
if(float(odd3)<=1):
print("Odd cannot be less than one")
exit(0)
print("Thank you, your odd is: ")
print("Match: ", match)
print("Home: ", odd1)
print("Draw: ", odd2)
print("Away: ", odd3)
Generally replace(val1, val2) method changes old value with a new one which is second argument. Why in this code checks if number is float. If I type float number in odd1 without replace, I am getting the message Sorry home tip is not numeric?
odd1.replace(".","") means that change every dot in the string odd1 into to nothing (means delete it) generally .replace() is used to search about a char in a string and replace it with another
for example
s = "Hello. world"
r = s.replace(".", ",")
print(r)
this code replace every dot in the string s with a comma
and then .isnumeric() tests if the value of odd1 after replacing is a number or not

How to run python loop until correct input string is entered [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...

Having user input take string and int? (Python)

prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?
I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.
If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.
prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True:
if user_input == 'quit':
break
age = int(user_input)
if age < 3:
price += 5
elif age < 12:
price += 10
else:
price += 15
print(f"Your ticket is ${price}")
user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")

Getting error message when trying to break out of a while loop in Python

I'm trying to write code that includes the following:
1) Uses a conditional test in the while statement to stop the loop.
2) Uses an active variable to control how long the loop runs.
3) Use a break statement to exit the loop when the user enters a 'quit' value.
Here is my code:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"
Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.
You are converting the user's input to a number before checking if that input is actually a number. Go from this:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
To this:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
This will check for a request to exit before assuming that the user entered a number.
You convert age to an integer with int() so it will never equal 'quit'. Do the quit check first, then convert to integer:
age = input(prompt)
if age == 'quit':
break;
age = int(age)
...
This now checks if it's equal to a string literal first, so that in the case it is, it breaks correctly. If not, then continue on as usual.
You are casting the string "quit" to integer, and python tells you it's wrong.
This will work :
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
Just for the sake of showing something different, you can actually make use of a try/except here for catching a ValueError and in your exception block, you can check for quit and break accordingly. Furthermore, you can slightly simplify your input prompt to save a couple of lines.
You can also force the casing of quit to lowercase so that you allow it to be written in any casing and just force it to a single case and check for quit (if someone happens to write QuIt or QUIT it will still work).
while True:
age = input("What is your age?\nEnter 'quit' to exit: ")
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
except ValueError:
if age.lower() == 'quit':
break
As proposed in a comment above you should use raw_input() instead of input in order to handle the user input as a string so that you can check for the 'quit' string. If the user input is not equal to 'quit' then you can try to manage the input string as integer numbers. In case the user passes an invalid string (e.g. something like 'hgkjhfdjghd') you can handle it as an exception.
Find below a piece of code that demonstrates what I described above:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
except Exception as e:
print 'ERROR:', e
print("Please enter a valid age.")

Using the value for a function in another function

I'm making a mastermind game and I've just started and hit a stumbling block. I need to allow the user to choose the number of pegs in the game and then allow the user to guess the code. I am trying to check the length of the guess and make sure it's the same as the number of pegs that they chose. Here is my code so far:
def pegs():
numberOfPegs = input("Please enter the number of pegs in the game between 3 and 8 ")
if numberOfPegs < 3:
return ("Make sure you enter a number between 3 and 8")
elif numberOfPegs > 8:
return ("Make sure you enter a number between 3 and 8")
else:
return ("Thank you, you are playing with", numberOfPegs, "pegs")
def checker():
guess = raw_input("Please enter your guess as letters ")
if len(guess) != pegs:
print "Wrong number!"
else:
return 1
print pegs()
print "\n"
print checker()
And the checker() always returns "Wrong number" even when the amount of letters in the guess I input is the same as the number of pegs i've chosen and I can't figure out why.
Thanks!
The return line in your pegs() should return the number of pegs so that you can save that value and use it again from the top level of your program:
def pegs():
...
return numberOfPegs
Have the function print what you want before returning. Then, in your main program:
npegs = pegs()
checker(npegs) # send the number of pegs to the checker function
And define checker appropriately:
def checker(pegs):
...
Edit to add: Check out this explanation of scope in Python.
def get_pegs():
numberOfPegs = input("Please enter the number of pegs in the game between 3 and 8 ")
if numberOfPegs < 3:
print ("Make sure you enter a number between 3 and 8");
return 0;
elif numberOfPegs > 8:
print ("Make sure you enter a number between 3 and 8");
return 0;
else:
print ("Thank you, you are playing with ", numberOfPegs, " pegs");
return numberOfPegs;
def checker(pegs):
guess = raw_input("Please enter your guess as letters ")
if len(guess) != pegs:
print "Wrong number!"
else:
print "Number ok"; #for debugging, remove later
return 1
pegs = get_pegs();
print "\n"
result = checker(pegs);

Categories