Every time I put in a number, it only prints the first input everytime instead of it being random. This is the code I used:
import random
import sys
answer = True
while answer:
question = input("Roll the di to get your fortune: ")
answers = random.randint(1,6)
if question == "":
sys.exit()
elif answer == 1:
print("You will get a new friend. ")
elif answer == 2:
print("You will go to disneyland. ")
elif answer == 3:
print("You will receive kindess.. ")
elif answer == 4:
print("Your will get a dog. ")
elif answer == 5:
print("You will suffer. ")
elif answer == 6:
print("You will have bad luck. ")
roll()
I really need help, I cant seem to figure out what I am doing wrong.
As a side note, you could make your code easier to work with if you replace your elifs with a dictionary of responses:
import random
import sys
responses = {
1: "You will get a new friend. ",
2: "You will go to disneyland. ",
3: "You will receive kindess.. ",
4: "Your will get a dog. ",
5: "You will suffer. ",
6: "You will have bad luck. "
}
answer = True
while answer:
question = input("Roll the di to get your fortune: ")
answer = random.randint(1,6)
if question == "":
sys.exit()
else:
print(responses[answer])
roll()
Change these lines in your code :
elif answer == 1:
print("You will get a new friend. ")
elif answer == 2:
print("You will go to disneyland. ")
elif answer == 3:
print("You will receive kindess.. ")
elif answer == 4:
print("Your will get a dog. ")
elif answer == 5:
print("You will suffer. ")
elif answer == 6:
print("You will have bad luck. ")
to these:
elif answers == 1:
print("You will get a new friend. ")
elif answers == 2:
print("You will go to disneyland. ")
elif answers == 3:
print("You will receive kindess.. ")
elif answers == 4:
print("Your will get a dog. ")
elif answers == 5:
print("You will suffer. ")
elif answers == 6:
print("You will have bad luck. ")
Where you went wrong: You were using answer variable defined as True in your conditions. In Python, True has a value of 1 this is why it was always running the condition "You will get a new friend. ". Also, you were storing the random dice digits in answers variable. Hope you understood!
You have a typo here where you're assigning to answers instead of answer:
answers = random.randint(1,6)
The True value you assigned to answer is the only one it will ever have; True is considered equal to 1 which is why you only ever get the first answer.
Using answer as your loop condition as well as for the die roll is a little confusing -- once you fix the typo above, it kind of works because all of the die rolls are "truthy", but it would work just as well (and be less prone to causing mistakes like this one) to use while True for the loop rather than using a variable whose value can never be false. Note that if you hadn't set answer = True at the start of your script, you would have spotted the answers typo immediately because checking answer == 1 would have raised a NameError. In general, the fewer variables you have to keep track of, and the less time you have to keep track of them for, the fewer chances there are for something to go wrong!
You don't need the question variable either since you immediately break the loop if it's empty and don't do anything else with it -- and for that matter you don't really need to keep track of answer and have a bunch of if statements based on it, since all you're really doing is picking one out of six possibilities -- there's a function called random.choice that makes that easy!
import random
while True:
if not input("Roll the die to get your fortune: "):
break
print(random.choice([
"You will get a new friend. ",
"You will go to disneyland. ",
"You will receive kindess.. ",
"Your will get a dog. ",
"You will suffer. ",
"You will have bad luck. ",
]))
Roll the die to get your fortune: ok
You will suffer.
Roll the die to get your fortune: ok
You will receive kindess..
Roll the die to get your fortune: ok
You will suffer.
Roll the die to get your fortune: ok
You will receive kindess..
Roll the die to get your fortune: ok
Your will get a dog.
Roll the die to get your fortune: ok
You will have bad luck.
Roll the die to get your fortune: ok
You will go to disneyland.
Roll the die to get your fortune:
You have an extra s when you roll the die on answers.
It should be:
answer = random.randint(1,6)
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 months ago.
I was doing the study drills for this chapter and I've stumbled upon this problem that I can't seem to figure out, maybe I'm missing something.
Here's the code:
# write a small adventure game similar to ex31
print("""You enter a dungeon and you find yoursfelf in front of three doors.
Do you go through door #1, door #2 or door #3?""")
dungeon_door = input(">> ")
if dungeon_door == '1' or '2':
print("You stumble upon a goblin. What do you do?")
print("1 - Try to kill the goblin with your shoe.")
print("2 - Try to talk things out.")
print("3 - Exit through the door you came from.")
goblin = input(">> ")
if goblin == '1':
print("You actually manage to kill the goblin. Dude you're a beast!")
print("You have to choose between two doors, do you pick the left one or the right one?")
final_door = input(">> ").lower()
if final_door == 'left':
print("This door leads to the treasure chamber. Dungeon cleared, congrats!")
elif final_door == 'right':
print("After you open to door an enormous one-eyed monster eats you. This dungeon was too much for you, try again.")
else:
print(f"What does {final_door} even mean? You're kicked out of the dungeon, bye.")
elif goblin == '2':
print("""Can you speak Ghukliak? Don't think so. The goblin doesn't understand you, you're dead.
The dungeon was too much for you, bye.""")
elif goblin == 3:
print("The door is somehow locked. The goblin takes this chance to kill you. The dungeon was too much for you, bye.")
else:
print(f"What does {goblin} even mean? You're kicked out of the dungeon, bye.")
elif dungeon_door == '3':
print("Well, it's your lucky day. This door leads directly to the treasure chamber. Dungeon cleared, congrats!")
else:
print(f"What does {dungeon_door} even mean? You're kicked out of the dungeon, bye.")
So part of the code works fine, the only problem I have is when I ask the user to make the first choice.
When I input '3' as the answer or something completely different from the suggested answers, I get the output as if the user has answered with '1' or '2'. I hope I have been clear enough.
I know it's a bit long and boring, sorry and TIA!
Your logic is wrong here:
if dungeon_door == '1' or '2':
Should be:
if dungeon_door == '1' or dungeon_door == '2':
Or
if dungeon_door in ('1', '2'):
And you forgot quotes around the 3
elif goblin == 3:
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
Hello everyone so I started working on a dice rolling game that rolls the dice then displays the value and asks if the user would like to re-roll. I know how to do all that but I wanted to put in a part that would loop if the user put in a value that was not Y(Yes) or N(No). So I created another while statement to accomplish this. If you input an invalid response the program asks you to type Y or N. Then if you type an invalid response again it keeps asking until the expected value is entered. Here is the code and I'll highlight the part where I don't understand. I commented why I think it works but I'm not sure. If someone could explain why it works I appreciate it thanks a lot!
import random
value = random.randint(1, 2)
run = True
while run:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = input("Do you want to play again? (Y or N) \n")
if answer == "Y":
continue
if answer == "N":
print("Thanks for playing \n")
exit()
# after you type an invalid response it's stored in variable answer
# the program then goes to answer2 input which asks please enter Y or N
# if the program then detects an invalid answer it goes back to the top
# of the while statement and uses answer ones response which is still
# an invalid response???? I'm guessing since answer is always invalid and the
# decisions only two options that are yes or no it goes back to the top of the 2nd while loop
# Not sure tho.
# 2nd while loop
while answer != "Y" or "N":
answer2 = input("Please enter Y or N \n")
while answer2 == "Y":
print("You roll a six sided dice \n")
print("The dice landed on " + str(value) + "\n")
answer2 = input("Do you want to play again \n")
continue
if answer2 == "N":
print("THanks for playing")
exit()
I've commented out why I think it works but
import random
value = random.randint(1, 2)
def getans():
while True:
answer = raw_input("Do you want to play again? (Y or N) \n")
if answer == "Y":
return True
elif answer == "N":
return False
else:
print ("Please enter Y or N \n")
continue
while True:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = getans()
if answer == True:
continue
elif answer == False:
print("Thanks for playing \n")
exit()
else:
print ("this will never run")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no)
I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.
import random
import sys
guesses_taken = 0
number = random.randint(1, 99)
name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")
answer = input("Would you like to play a guessing game? (yes/no) ").lower()
while True:
if answer == "no":
print("\nToo bad, goodbye!\n")
sys.exit()
elif answer == "yes":
print(f"\nOkay, let's play!")
break
else:
print("\nSorry, I didn't get that.")
while True:
print("\nI'm thinking of a number between 1 and 99!")
while guesses_taken < 6:
guess = input("Take a guess: ")
guesses_taken += 1
if int(guess) > number:
print("\nYour guess is too high!\n")
elif int(guess) < number:
print("\nYour guess is too low!\n")
else:
print("\nArgh..you guessed my number! You win! -__-")
break
while guesses_taken >= 6:
print("\nHa ha. You took too many guesses! I win! ^__^")
break
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
sys.exit()
The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
else:
guesses_taken = 0
number = random.randint(1, 99)
Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.
This question already has answers here:
Loop until a specific user input is received in Python [duplicate]
(3 answers)
Closed 4 years ago.
A quick snippet of the code below. I tried messing around with another answer posted on here, but it didn't seem to work at all. I'm not sure what I'm doing wrong. Using Python 3 on Xubuntu 18.04 LTS. Here's the code:
while True:
try:
print("Your room is DARK, yet a light flashes red. What do you do?")
print("")
print("1. Look around.")
print("2. There's a lamp somewhere...")
print("3. Go back to bed.")
print("")
ans = int(input(">>> "))
if ans == 1:
print("")
print("Too dark to see... better find a light...")
time.sleep(2)
if ans == 2:
print("")
print("Fumbling, you turn on your nightstand lamp...")
break
if ans == 3:
print("")
print("You sleep away the troubles... but you can't stay asleep...")
time.sleep(1)
print("")
print("Back to the world of the living...")
if ans == str('q'):
sys.exit(0)
except ValueError:
print("")
So, when the user inputs "q", I want the program to close. I can't seem to get it to do it at all.
The problem is with your line where you say int(input(">>> ")) which is converting what the user enters to an integer each time. What you should do is take in the user input as a string and then check if it is a valid number for 1, 2, & 3 or if it equals q.
Example:
ans = input(">>> ")
if ans == '1':
# Do something
elif ans == '2':
# Do something
elif ans == '3':
# Do something
elif ans == 'q':
sys.exit(0)
You're typecasting the q to an integer at input: ans = int(input(">>> ")) and then trying to typecast it back to a string at if ans == str('q'): Better solution would be to keep the input as a string in ans (remove the int() typecast and explicitly typecast it as an int with int() in each case.
Update: My original solution was wrong. The corrected one asks if the string is a digit and then evaluates it as an int. This is more verbose and I therefore recommend Karl's solution. But in case you're wedded to typecasting the string as an int I'm leaving this posted.
while True:
try:
ans = input(">>> ")
if ans.isdigit() and int(ans) == 1:
...
elif ans.isdigit() and int(ans) == 2:
...
elif ans.isdigit() and int(ans) == 3:
...
elif ans == 'q':
sys.exit(0)
except ValueError:
print("")
Then you don't even need to call str() at all.
I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.