I'm fairly new to Python so I'm not sure how to go about this. I have created this random number guessing game, and I have it down except for the fact that the game is supposed to never end. Once the user guesses the number, the game should start over. Here is my code.
import random
num = random.randint(1, 100)
def main():
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != guess:
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
break
main()
main()
while True:
main()
This makes your main method run until you stop it.
You put a break statement in your else. If you remove it it will work. But you also have to put your num statement inside your main.
This should do the job:
def main():
num = random.randint(1, 100)
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != "guess":
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
main()
main()
All lines down from def main(): must be indented four spaces. Maybe it's just a problem with the copy paste, but I find myself really uncomfortable looking at improperly indented Python code.
Remove the print statement right after while num != "guess": not sure what it does
Remove the quotes around guess as right now you're checking a number against a string
Now, to implement your functionality, you should move the num = random.randint(1, 100) line into the function to choose a new number. Then, call the function while true:
while True:
main()
Related
The aim of this code is to get the computer to generate a random number and let the user try and guess what that number is in however many tries they choose. However, when they fail to guess correctly the program is supposed to print "You have failed in (x) tries" just once. Unfortunately this line keeps looping over and over again. Where have I gone wrong?
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
print (f"You have guessed {random_number} correctly")
guess(10)
It was looping forever because the incrementation of tries was done in the else block and there is no break keyword in else block too.
So, move tries = tries+1 in the if tries <limit: block and put break inside the else block as shown below:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
tries = tries + 1 # <--- move here
else:
print(f"You have failed in {limit} tries")
break; # <--- put break
print (f"You have guessed {random_number} correctly")
guess(10)
You need to keep a check of the tries.
You need to print the statement only in the user input is correct:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while tries<limit:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print (f"You have guessed {random_number} correctly")
break
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
guess(10)
You can use a for loop:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
found=False
for i in range(limit):
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
found=True
break
if found:
print (f"You have guessed {random_number} correctly")
else:
print(f"You have failed in {limit} tries")
guess(10)
There are multiple logical errors in your code,
the condition you are using in the while loop, guess != random_number, is to check if a number has been guessed correctly or not, not to check if the total number of guesses are exhausted.
No matter what happens, when the code will exit the while loop it will show the user that he/she has guessed correctly
Changing your code to take this into consideration will fix your problem. Below is a possible solution:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
# Flag to check if the user is guessing the right or wrong value
# Default assumption is that user is guessing incorrectly
UserGuess = False
while tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
# Changing flag and stopping the loop if the user guesses correctly
UserGuess = True
break
tries = tries + 1
if UserGuess:
print (f"You have guessed {random_number} correctly")
else:
print (f"You have failed in {limit} tries")
guess(10)
I'm trying to make a simple number guesser program, it works pretty well however if I enter 'a' twice instead of a valid int it crashes out. Can someone explain what I'm doing wrong here.
import random
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
if type(guess) != int:
guess = int(input("That isn't a number, try again: "))
elif guess not in range (1,11):
guess = int(input("This is not a valid number, try again: "))
else:
break
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
input_sanitiser()
if guess > number:
print("This number is too high!")
input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")
if __name__ == "__main__":
main()
You want to check the input before trying to convert it to int:
int(input("This is not a valid number, try again: "))
I would write:
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
pass
else:
break
Side note: the code isn't working as expected:
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser() # <<<<<<<<<<
while guess != number:
Note that input_sanitiser does not modify the variable guess in main, you need some other way round, like processing the input then returning the result from input_sanitiser, like this:
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
continue # keep asking for a valid number
if guess not in range(1, 11):
print("number out of range")
continue
break
return guess
def main():
number = random.randrange(1,10)
guess = input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
guess = input_sanitiser()
if guess > number:
print("This number is too high!")
guess = input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")
def var (guess):
return guess
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
while True:
try:
guess = num
print("you guessed the right number!")
break
except:
print("try again")
break
So for this program I am trying to figure out how to have the user input a number and to guess what number (1 through 10) the program generated. It seems that every time I input a value it always gives me the "you guess the right number!" string even if I input a value higher than 10.
EDIT: Why would someone downvote my question o_o
You need to get user's input inside while loop so that user's input got updated with each iteration.
import random
num = (random.randint(1,10))
while True:
try:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("you guessed the right number!")
break
else:
print("try again")
except:
print('Invalid Input')
try/except is for exception handling, Not matching values. What you are looking for is if statments, For example:
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
if guess == num:
print("You guessed the right number!")
else:
print("Try again")
I think you may have intended to continue looping until the right number is guessed, In which case, This will work:
import random
num = (random.randint(1,10))
while True:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("You guessed the right number!")
break
else:
print("Try again")
I'm having difficulties telling the player that the player already guessed the number.
This is my code:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
def get_guess(already_guessed):
guess = input()
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = get_guess(input("Try again.\n\n"))
You never updating your already_guessed variable you could add it to your get_guess function. And also you have too many input. Try that:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
already_guessed = []
def get_guess(already_guessed):
if guess in already_guessed:
print("You already guessed that number.")
else:
already_guessed.append(guess)
return already_guessed
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = int(input("Try again.\n\n"))
already_guessed = get_guess(already_guessed)
You don't maintain a list of guesses seen, but you try to use it.
You pass input in place of the already_guessed list at the end.
Your input statement flow is not consistent with game play.
Your termination doesn't tell the player that s/he won, and you use a redundant break statement.
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
seen = []
def get_guess(already_guessed):
guess = int(raw_input("Your guess?"))
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
seen.append(guess)
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
guess = get_guess(seen)
print "You win!"
I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)