I have made this code for a project and i have run into a problem with the while loop becasue it just repeat the first input function, here is the code, i would aprriecate it if someone could point out my problem and help me fix my code, thnx
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
The else block of the while would be executed only if roll_agn became non-'yes' inside the loop. You never change it inside the while loop, so it loops forever.
Your else statement is unindented (outside of the loop), so the variable within is never reset, so the condition that the while loop requires is always True, hence an infinite loop. You just need to indent this:
elif dice ==12:
...
else:
^ roll_agn = input()
Your indentation is off as others have pointed out. Here are a few suggestions on how to improve your code a little further
import random
while True:
try:
dice = int(input ('Please choose a 4, 6 or 12 sided dice: ')) # this input should be an int
if dice in (4, 6, 12): # checks to see if the value of dice is in the supplied tuple
print(random.randint(1,dice))
choice = input('Roll again? Enter yes or no: ')
if choice.lower() == 'no': # use .lower() here so a match is found if the player enters No or NO
print('Thanks for playing!')
break # exits the loop
else:
print('that is not 4, 6 or 12')
except ValueError: # catches an exception if the player enters a letter instead of a number or enters nothing
print('Please enter a number')
This will work no matter what the player enters.
Related
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.
I was trying to write code to solve a question:
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Keep track of how many guesses the user has taken, and when the game ends, print this out.
The code that I wrote was:
import sys
import random
x=random.randint(1,9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
pass
else:
sys.exit()
Here’s what it looks like when run:
Hello there! Please enter a number between 1 and 9 including the extremes.
4
Too high. Please try again.
3
Too high. Please try again.
2
You guessed it right!
it took you 3 turns.
Do you want to play again? Yes or No?
yes
Okay, Please enter a number between 1 and 9 including the extremes.
6
Too high. Please try again.
4
Too high. Please try again.
2
You guessed it right!
it took you 6 turns.
Do you want to play again? Yes or No?
See, the code gives perfect results when the for loop is first executed. It gives weird results when we try to run this “game” for the second time by saying yes when it asks us the question: Do you want to play again? Yes or No?.
Is it possible to put i=0 when python reaches the 4th last line and the for loop starts again from i=0 so that I do not get weird results?
Or is there some other easier method remove this bug?
You can use while loop for the task. And you should add exception handling method for getting an input.
import random
cond = True
while cond:
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
x=random.randint(1,9)
for i in range (10):
z=int(input())
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
import sys
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
break
else:
cond = False
sys.exit()
First of all, you pick the random number only once, so it's always going to be the same.
Secondly, your game should be in while loop instead of for loop (if you want to allow player to restart after they guessed).
turns = 0
while True:
secret_number = random.randint(1,9)
print('Please enter a number between 1 and 9 including the extremes.')
guess = input()
turns += 1
if int(guess) < secret_number:
print("Too low")
elif int(guess) > secret_number:
print("Too high")
else:
print("You guessed in {} turn(s)".format(turns))
You continue the loop, and assign turns = 0 if user wants to keep playing, or you break if he doesn't.
All imports should go at the top of the file. Then, put a while loop so the player can restart after every game; this way, the variable x is also reset after every game. Also, the first print should be put outside the while and for loop, so it's printed only one time (the last if will print a new prompt at the beginning of a new game).
Your code at this point should look like this:
import random
import sys
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
while True:
x=random.randint(1,9)
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
else:
sys.exit()
I'd write it like this, probably.
from itertools import count
from random import randint
def run_game():
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
return response_string.lower() == 'yes'
if __name__ == "__main__":
while run_game():
pass
But, for simplicity in understanding:
from itertools import count
from random import randint
if __name__ == "__main__":
playing = True
while playing:
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
if response_string.lower() != 'yes':
playing = False
break
The whole of your code is embedded within the for loop and the counter is never reset. If you want to reset i within the for loop, you have to define it outside the for loop so that it has a global scope.
I have created a program where the user can select a certain sided dice then it rolls and outputs the number generated, it then asks if the user wants to roll again and by using a while loop. i have wrote the program and for some reason it keeps on repeating the input dice side number prompt and i don't know why, here is the code
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
I suspect it is something to do with the while loop or the indentation, but I have been fiddling with it for like 3o mins and i cant get it to work properly, so if someone could help me out here it would be appreciated, Thanks !
The indentation on else: roll_agn=input is such that it only runs after you exit the while loop - but the while loop can never end until you run the else clause, therefore infinite loop.
Here is a cleaned-up, better-structured version:
# assumes Python 3.x
from random import randint
def get_int(prompt):
while True:
try:
return int(input(prompt)) # if Python 2.x use raw_input instead of input
except ValueError:
# not an int
pass
def get_yn(prompt):
while True:
value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
if value in {'y', 'yes'}:
return True
elif value in {'n', 'no'}:
return False
def roll(sides):
return randint(1, sides)
def main():
while True:
sides = get_int("Number of sides on die (4, 6, or 12)? ")
if sides in {4, 6, 12}:
print("You rolled a {}".format(roll(sides)))
else:
print("U no reed gud?")
if not get_yn("Play again (y/n)? "):
print("Thanks for playing!")
break
if __name__=="__main__":
main()
It looks like you have indentation problems with the if statements. Try lining up elif with if.
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
I cannot get the following to function. I need validation by adding
else:
print("Type only 4, 6, or 12.")
However doing this on the code does not work:
def dicegame():
#This defines the dicegame coding so I can call it later on
number=int(input("Hello. Enter either 4,6 or 12 to determine what sided dice you want to use "))
import random
if number=="4" or "6" or "12":
print("You have rolled a", number, "sided dice with the number", random.randint(1,number))
#These if loops direct the program to the correct coding down to what the user inputs (ie. 4, 6 or 12)
print("Would you like to roll again?")
answer=input("Enter either yes or no.")
if answer == ("yes"):
dicegame()
if answer == ("no"):
print("Ok, goodbye")
#Program prints "Would you like to roll again?
#Using input, user can reply to what the program prints, labelled with the variable 'answer'
dicegame()
The loop breaks once adding the else loop for my validation.
I don't see a loop, but one thing is wrong:
instead of
if number=="4" or "6" or "12":
use
if number in (4, 6, 12):
Note that number has already been casted to int
try
if number==4 or number==6 or number==12:
or
if number in [4, 6, 12]:
'6' is always true - so you always fulfil the condition...
You also have to remove the quotation marks since you write number=int(...).
I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
if ans=='Q':
print("Now I'll see if I can break your score...")
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:
myScore = 0
while ans := input("Roll...").lower() == "r":
# ... do something
else:
print("Now I'll see if I can break your score...")