I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!
I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?
As far as I understand it, you want to pick a new random integer in every loop step.
I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
try:
antwoord = int(antwoord)
except:
print ("You need to type in a number")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 months ago.
from fileinput import close
from random import Random, random
print('Do you want to play a game?')
input1 = input("yes or no? ")
if input1 == "yes" or input1 == "Yes":
print("You have 3 tries to guess a random integer between 0-10. If you guess right
you win. If not I do. Ready?")
import random
def repeat():
number = random.randint(1,10)
print(number)
guess1 = input('Your first guess: ')
if guess1 == number:
print('You are correct! You only needed one try!')
else:
print('Wrong two tries left!')
guess2 = input('Your second guess: ')
if guess2 == number:
print('You are correct! You needed two tries!')
else:
print('Wrong one try left!')
guess3 = input('Your third and last guess: ')
if guess3 == number:
print('You are correct! It took you all three tries!')
else:
print('You are wrong! You lost! The number was:')
print(number)
input2 = input('Do you want to play again? Yes or No? ')
if input2 == 'Yes' or 'yes':
repeat()
else:
close()
else:
close()
repeat()
I have no clue where the mistake is, but when I guess number correctly it still says its wrong.
You need to convert all guesses into integers to compare since the default input type is string.
from fileinput import close
from random import Random, random
print('Do you want to play a game?')
input1 = input("yes or no? ")
if input1 == "yes" or input1 == "Yes":
print("You have 3 tries to guess a random integer between 0-10. If you guess right you win. If not I do. Ready?")
import random
def repeat():
number = random.randint(1,10)
print(number)
guess1 = int(input('Your first guess: '))
if guess1 == number:
print('You are correct! You only needed one try!')
else:
print('Wrong two tries left!')
guess2 = int(input('Your second guess: '))
if guess2 == number:
print('You are correct! You needed two tries!')
else:
print('Wrong one try left!')
guess3 = int(input('Your third and last guess: '))
if guess3 == number:
print('You are correct! It took you all three tries!')
else:
print('You are wrong! You lost! The number was:')
print(number)
input2 = input('Do you want to play again? Yes or No? ')
if input2 == 'Yes' or 'yes':
repeat()
else:
close()
else: close() repeat()
I'm trying to write my first program that just gets an input from the user, selects a random number from 1 - 10, and checks to see if the user's number and computer's number matched.
Here's the code I tried:
def Num_Guess():
print("Hello! Welcome to the \"Guessing Game!\"")
import time
time.sleep(2)
print("Input a number from 1-10 and see if the computer has the same number!")
time.sleep(2)
User_Guess = input("Pick a number between 1 and 10: ")
def int_check(User_Guess):
if User_Guess.isnumeric() == True:
User_Guess = int(User_Guess)
def range_check(User_Guess):
if User_Guess == range(1,10):
print("Great! Your guess was", User_Guess, end='')
print("!")
return User_Guess
else:
print("Sorry, please pick a number between 1 and 10.")
time.sleep(2)
#Deletes the variable so that the global version does not override the local one.
del User_Guess
User_Guess = input("Pick a number between 1 and 10: ")
int_check(User_Guess)
range_check(User_Guess)
else:
print("Sorry, please pick a NUMBER between 1 and 10.")
time.sleep(2)
del User_Guess
User_Guess = input("Pick a number between 1 and 10: ")
int_check(User_Guess)
int_check(User_Guess)
time.sleep(2)
#Picks a random number between 1 and 10.
import random
n = random.randint(1, 10)
print("The computer picked" , n , end='')
print("!")
time.sleep(2)
if User_Guess == n:
print("The numbers match! You and the computer both picked" , User_Guess, end='')
print("!")
elif not User_Guess == n:
print("The numbers did not match. You picked" , User_Guess , "and the computer picked" , n , end='')
print(".")
time.sleep(2)
def Reset_Quit():
rq = input("Restart or quit? (r/q): ")
if rq == "r":
print("\n")
Num_Guess()
if rq == "q":
print("Quiting...")
time.sleep(2)
quit()
else:
print("Sorry, please say either \"r\" or \"q\".")
time.sleep(2)
Reset_Quit()
Reset_Quit()
Num_Guess()
What I'm trying to accomplish is:
Checking if the user's input is numeric or not. If yes, it will move on to the next step which is converting the string to an integer. If it is not, then it will simply make the user re-enter their input.
The next step will be checking if the input is within the range of 1 - 10. If it is, it will move on to comparing the user's input and the computer's to see if they match. If it is not, it will make the user redo their input and have it go through the numeral checking process again.
The final step is making the reset/quit promptly to not allow numbers or any other character that could cause the program to crash other than "r"/"R" or "q"/"Q".
I understood what the problem is.
In your range_check function, you are trying to match the user input with a range (which is a generator object) using ==. So instead use in keyword -
def range_check(User_Guess):
if User_Guess in range(1,11): # Here was the error
print("Great! Your guess was", User_Guess, end='')
...
Edit:
The program asks user to enter a number from 1-10, but program logic only accepts numbers 1-9. Rest of your code also uses the logic for including numbers 1-9 only. So correct the user input prompt to "number between 0-10" or "number from 1-9".
If you want to include 10 also:
use range(1, 11) and randint(1, 11)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!
#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()
print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)
#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
guess = int(input())
if type(guess) != int:
print ("You did not enter a number, please re-enter")
continue
if guess < secretNumber:
print ("The number you guessed was too low")
elif guess > secretNumber:
print ("The number you guessed was too high")
else:
break
if guess == secretNumber:
print ("Oh yeah, you got it")
else:
print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))
print ("You took " + str(guessesTaken) + " guesses.")
Use a try and except:
for guessesTaken in range(1, 7):
try:
guess = int(input())
except ValueError:
print ("You did not enter a number, please re-enter")
continue
So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.
You can try a simple while loop that waits until the user has entered a digit. For example,
guess = input("Enter a number: ") # type(guess) gives "str"
while(not guess.isdigit()): # Checks if the string is not a numeric digit
guess = input("You did not enter a number. Please re-enter: ")
That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).
You can then convert the digit to an integer as before:
guess = int(guess)
For example, consider the following cases:
"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer
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 had a problem in Python. I was trying to make an addition calculator but a problem popped up. My code is attached.
prompt = input("Do you want to use this calculator? Y for yes and N for no ")
if prompt == 'n' :
print ("Maybe next time. ")
if prompt == 'y':
numberone = input("What is your first number? ")
numbertwo = input("What is your second number? ")
print ("Your equation is ",numberone, "+ ",numbertwo, )
answer = (numberone * numbertwo)
print ("Your answer is ",answer, )
When I print the answer it comes out as two numbers combined. For example if I'm using 9+10, it'll come out as 910. I don't know what to do to fix it.
input gets the input from the user and returns it as a string.
You need to convert the input to a number. I presume you want the numbers to be int, but you could just replace int with float if you need to.
prompt = input("Do you want to use this calculator? Y for yes and N for no ")
if prompt == 'n' :
print ("Maybe next time. ")
elif prompt == 'y':
numberone = int(input("What is your first number? "))
numbertwo = int(input("What is your second number? "))
print ("Your equation is ",numberone, "+ ",numbertwo, )
answer = (numberone + numbertwo)
print ("Your answer is ",answer, )