I am having trouble with my monster_room function. No matter what the input is, it will always choose the elif choice (elif choice > 5:...). Here is the function:
def monster_room():
print "This is the monster room! How many monsters do you see?"
choice = raw_input("> ")
if choice < 5:
dead("More than that idiot!")
elif choice > 5:
print "More than you thought right?!"
print "Do you go to the Alien room or Frankenstien room?"
choice_one = raw_input("> ")
if choice_one == "alien":
alien_room()
elif choice_one == "frankenstien":
frankenstien_room()
else:
print "Type alien or frankenstien, DUMMY!"
monster_room()
else:
print "Type a number!"
monster_room()
How do I get it to read the input? Also this is my first project and I know it's very basic and probably looks rough so other tips I am open to as well. If you need the full code (99 lines) just let me know! Thanks!
You need to parse your input data to a number type using int() because raw_input() returns a string.
choice = int(raw_input("> "))
As #Joran Beasley metniioned to be on the save side you shuld use a try except block:
try:
choice = int(raw_input("> "))
except ValueError:
print "Type a number!"
monster_room()
you'll get to the "type a number!" section even if you input 5 since you're not allowing a >= or <= scenario.
I do agree, though, you have to convert the input to an int or float.
Casting the input to int will solve it (it's a string when you use it). Do this:
choice = int(raw_input("> "))
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last month.
New to Python. Working on a program and I want to add a loop so that if they don't put in 1 or 2 then they are asked to try again until they do it right. In my assignment, I'm making a cafe. I want to ask the user if they are dining in or ordering take out (1 or 2) and each option offers a different response. 1 for example would output "Thank you for dining in with us" and 2 would output: "Thank you for choosing take out". If they put anything other than 1 or 2, I want it to prompt them to try again until they put the right response in. This would be a loop right?
This is what I have so far and the loop part I have is a complete mess and doesn't run at all.
print("Will you be dining in or ordering take out?")
while True:
try:
where = input("For Dine In, Type 1. For Take Out, Type 2: ")
if where == "1":
print("Thank you for dining in with us. Please fill out the following: ")
elif where == "2":
print("Thank you for choosing take out. Please fill out the following: ")
else:
print("Invalid response, please type 1 or 2: ")
except
What am I doing wrong?
The error in your code is that except is supposed to have a block after it -- but you do not need try/except at all since nothing you're doing is expected to raise an exception. Just break the loop once you have a valid response.
print("Will you be dining in or ordering take out?")
while True:
where = input("For Dine In, Type 1. For Take Out, Type 2: ")
if where == "1":
print("Thank you for dining in with us. Please fill out the following: ")
break
elif where == "2":
print("Thank you for choosing take out. Please fill out the following: ")
break
else:
print("Invalid response, please type 1 or 2: ")
Try this:
print("Will you be dining in or ordering take out?")
while True:
try:
where = input("For Dine In, Type 1. For Take Out, Type 2: ")
if where == "1":
print("Thank you for dining in with us. Please fill out the following: ")
elif where == "2":
print("Thank you for choosing take out. Please fill out the following: ")
else:
print("Invalid response, please type 1 or 2: ")
except:
pass
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have some codes below, the choice takes only integer input but prints out something special if the input is not an integer. However, the codes below to treat this issue seems a little bit lengthy. Anyway to fix it?
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You're greedy!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()
Try something like:
try:
how_much = int(choice)
except ValueError:
dead('Man, learn to type a number.')
and look up Easier to ask for forgiveness than permission for the rationale.
You can use the str.isdigit() to check if its a number, using try...except statement for this is not recommended because it makes your code messy and could cause errors in the long run. But if it's only that it'll work too.
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if choice.isdigit(): #Checks if it's a number
how_much = int(choice)
else:
dead("Man, learn to type a number.")
return
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You greedy bastard!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()
Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break
I am trying to make a simple guessing game, but the program exits when the user answers, 'yes', that they know how to play. I don't understand why the 'break' makes the program exit rather than continue to the rest of the code. Extreme newbie, in case you can't tell :P
Thanks for all the help!
import random
import time
def calculat(times):
p = "."
for nums in range(times):
print p
time.sleep(.2)
print p * 2
time.sleep(.2)
print p * 3
time.sleep(.2)
print p * 2
time.sleep(.2)
print p
time.sleep(.6)
print "Welcome to Guess!"
print "Press [Enter] to continue!"
raw_input()
while True:
know = raw_input("Do you know how to play? Enter [yes] or [no]\n")
know = know.upper()
if know == "YES":
break
elif know == "NO":
print " "
print "-INSTRUCTIONS-"
print "Here's how the game works. A number 1 to 100"
print "is generated randomly. Your goal is to guess"
print "as many numbers as possible before you run"
print "out of guesses. You have 10 guesses.Good luck!"
print "Have fun!"
else:
print "Please enter [yes] or [no]!"
while True:
score = 0
number = randint(1,100)
newnum = 1
for tries in range(0,9):
if newnum == 1:
print "Okay, I have a number 1 to 100! What is it?"
else:
print "Guess again! What's the number?"
while True:
try:
guess = input()
if guess <= 100 and guess >= 1:
break
else:
print "You must guess an integer, 1 - 100!"
except:
print "You must guess an integer, 1 - 100!"
if guess == number:
print "Heyo! That's correct!"
score = score + 1
number = randint (1,100)
newnum = 1
if tries != 9:
print "Press [Enter]! Guess another number!"
raw_input()
elif guess < number:
if tries != 9:
print "Darn, that guess was less than the number! Try again!"
print "Press [Enter] to continue!"
raw_input()
elif guess > number:
if tries != 9:
print "Whoa, that guess is too big! Try again!"
print "Press [Enter] to continue!"
raw_input()
print "That's it! Let me calculate your final score! [Press Enter]"
raw_input()
calculate(4)
print "Final Score: " + score
print "Good job!"
raw_input()
print "Would you like to play again? [yes] or [no]?"
play = raw_input()
play = play.upper()
if play == "NO":
print "Okay then, press enter to exit!"
raw_input()
break
elif play == "YES":
print "Yey! Let me think of a new number!"
calculate(2)
else:
print "You couldn't even say yes or no. Get out."
raw_input()
break
Oh yeah, the rest of the code could be broken, too. I haven't gotten past the instructions part.
It ends the program because it immediately encounters an error after the instructions are finished. You've imported random but then tried to use randint, unqualified. You've got to qualify it as random.randint or use from random import randint.
I assume you mean the break statement to escape from the first infinite loop. When I run your code, that break statement works just fine and control proceeds to the second infinite while loop.
However, your program then crashes on the first call to randint() because you aren't importing it correctly. Since the randint() function is from outside of your program (it's in the random module), you need to qualify the calls to randint() as random.randint() - so for the first call, you could use number = random.randint(1, 100). Alternatively, you could import randint using from random import randint, rather than import randint. That way, you would be able to call randint() directly.
I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"
How would I get it to start again?
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while not game(phrase):
print("Incorrect.")
print("Correct")
main()
The output is identical.
Even the following Style works!!
Check it out.
def Loop():
r = raw_input("Would you like to restart this program?")
if r == "yes" or r == "y":
Loop()
if r == "n" or r == "no":
print "Script terminating. Goodbye."
Loop()
This is the method of executing the functions (set of statements)
repeatedly.
Hope You Like it :) :} :]
Try a loop:
while 1==1:
[your game here]
input("press any key to start again.")
Or if you want to get fancy:
restart=1
while restart!="x":
[your game here]
input("press any key to start again, or x to exit.")
Here is a template you can use to re-run a block of code. Think of #code as a placeholder for one or more lines of Python code.
def my_game_code():
#code
def foo():
while True:
my_game_code()
You could use a simple while loop:
line = "Y"
while line[0] not in ("n", "N"):
""" game here """
line = input("Play again (Y/N)?")
hope this helps
while True:
print('Your game yada-yada')
ans=input('''press o to exit or any key to continue
''')
if ans=='o':
break
A simple way is also to use boolean values, it is easier to comprehend if you are a beginner (like me). This is what I did for a group project:
restart = True
while restart:
#the program
restart = raw_input("Press any key to restart or q to quit!")
if restart == "q":
restart = False
You need to bury the code block in another code block.
Follow the instructions below:
Step 1: Top of code def main()
Step 2: restart = input("Do you want to play a game?").lower()
Step 3: Next line; if restart == "yes":
Step 4: Next line; Indent - main()
Step 5: Next line; else:
Step 6: Indent - exit()
Step 7: Indent all code under def main():
Step 8: After all code indent. Type main()
What you are doing is encapsulating the blocks of code into the main variable. The program runs once within main() variable then exits and returns to run the main varible again. Repeating the game. Hope this helps.
def main():
import random
helper= {}
helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Do not go where the path may lead, go instead where there is no path and leave a trail.",
"You will face many defeats in life, but never let yourself be defeated.",
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"In the end, it's not the years in your life that count. It's the life in your years.",
"Never let the fear of striking out keep you from playing the game.",
"Life is either a daring adventure or nothing at all."]
helper['sad']= ["Dont cry because it’s over, smile because it happened.",
"Be yourself; everyone else is already taken",
"No one can make you feel inferior without your consent.",
"It’s not who you are that holds you back, its who you think you're not.",
"When you reach the end of your rope, tie a knot in it and hang on."]
answer = input ('How do you feel : ')
print("Check this out : " , random.choice(helper[answer]))
restart = input("Do you want a new quote?").lower()
if restart == "yes":
main()
else:
exit()
main()
How to rerun a code with user input [yes/no] in python ?
strong text
How to rerun a code with user input [yes/no] in python ?
strong text
inside code
def main():
try:
print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
num1 = float(input("Enter 1st number: "))
op = input("Enter operator: ")
num2 = float(input("Enter 2nd number: "))
if op == "+":
print(num1 + num2)
elif op =="-":
print(num1 - num2)
elif op =="*":
print(num1 * num2)
elif op =="/" :
print(num1 / num2)
elif op =="%":
print(num1 % num2)
elif op =="//":
print(num1 // num2)
elif op == "^":
print(num1 ** num2)
else:
print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")
except ValueError:
print("Invalid Input, please input only numbers")
restart = input("Do you want to CALCULATE again? : ")
if restart == "yes":
main()
else:
print("Thanks! for calculating keep learning! hope you have a good day :)")
exit()
main()
strong text
You maybe trying to run the entire code with an option for user to type "yes" or "no" to run a program again without running it manually.
This is my code for a 'calculator' in which i have used this thing.
Is that your solution?
By the way this is a reference link from where i learnt to apply this function.
https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s