In this code, the user is to guess a number the computer has chosen randomly between 0 and 100.
The problem is that the while loop doesn't get executed at all. Everything was working until I put that code block into the while loop to get it repeated until the user guesses the number or runs out of attempts. How do I get the while loop to work? Please I am a beginner in python.
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
You define number_guessed as False, so the loop does not execute at all. Try while not number_guessed.
This should work:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed == False:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
The error with your code was that when you use a while loop like while somevariable and somevariable equals False, the while loop will not run. You could also just try while not number_guessed
The numbers_guessed is false, and the while loop must be true to run. So change the while loop or the variable.
Code:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while not number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
Related
I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)
I was given an assignment for my computer science class with the goal of creating a number guessing game. I have created the program but I cannot seem to solve some problems that I came across while making it.
The code I wrote is....
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
i = 10
tries = 0
Random_Number = random.randint(1,100)
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Some of the problems I have with this code is that the randomly generated number stays the same even after you have played one game and are on your second. At first, I thought of putting the random.randint(1,100) inside the while loop, but that just creates a random number every time you guess. The second problem is that the 'i' and 'tries' values continue to go down but I need them to reset to their original value every time the user plays a new game.
By a new game I mean when the user answers 'yes' to Play_again.
Just a quick fix, create a 'reset' function, that updates all necessary variables:
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
def reset():
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
i = 10
tries = 0
Random_Number = random.randint(1,100)
return (i, tries, Random_Number)
i, tries, Random_Number = reset()
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Output:
...
Your guess was too low. You have 0 guesses left.
Sorry you have no more guesses left.
Would you like to play again (N/Y)?y
A random number between 1 and 100 has been generated.
You have 10 tries to guess the number.
Whats your guess?:2
Your guess was too low. You have 9 guesses left.
...
I made full code for you check this out:
import random
import sys
def menu():
Play_again = input("Would you like to play again (N/Y)?").lower()
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
game()
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
sys.exit()
else:
print("You have entered an invalid input.")
menu()
def game():
i = 10
tries = 0
Random_Number = random.randint(1,100)
#print(Random_Number)
while i>0:
try:
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
menu()
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
except:
print('Please Enter Numbers only')
print("Sorry you have no more guesses left.")
menu()
if __name__=='__main__':
print("Welcome to the Number Guessing Game!")
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
game()
In addition, I made it to get only numbers.
If there is an error in this code, tell me I'll fix it for you.
import random
random_number = random.randint(1,10) #numbers 1 - 10
guess = None
while True:
guess = input("pick a number from 1 to 10 \n")
guess = int(guess)
if guess < random_number:
print("Too low")
elif guess > 10:
print("pick a number from 1 to 10")
elif guess > random_number:
print("It's high")
else:
print("You won")
play_again = input("Do you want to play again? (y/n) ")
if play_again == "y":
random_number = random.randint(1,10) #numbers 1 - 10
guess = None
else:
print("Thank you for playing!")
break
Because You print "pick a number from 1 to 10" and then follows input label at line 8.
If you type a number greater than 10, it should print at least 3 times
guess = input("pick a number from 1 to 10 \n")
elif guess > 10:
print("pick a number from 1 to 10")
Then the loop repeats
It's not clear why you've hard-coded 10 in the if-else. Rather you can try to continue the loop
while True:
guess = input("pick a number from 1 to 10 \n")
guess = int(guess)
if guess > 10:
continue
My problem with the program is that i it will tell me my variable called "guess" isnI will
Here is the n of saying "Guess lower".
Traceback (most recent call last):
F
guess = int(input("Guess a number: "))
ValueError: invalid literal for int() with base 10: 'hfdg'
And here is the code for the program
import random
random_number = random.randint(1, 10)
tries = 0
print ("Enter yes, or no")
saysalse
while not says_yes or not says_no:
player_input = input("Would you like to play a game?: ")
player_input = player_input.lower()
if player_input == "yes":
says_yes = True
break
elif player_input == "no":
says_no = True
print("See you next time.")
exit()
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 \
and if you guess it right then you win")
guess = int(input("Guess a number: "))
choose a number between 1-10.")
guess = int(input("Guess a number: "))
while int(guess) != int(random_number):
tries to guess the number.")
Look here:
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 \
and if you guess it right then you win")
guess = int(input("Guess a number: "))
while guess > 10 or guess < 1:
print("Please choose a number between 1-10.")
guess = int(input("Guess a number: "))
Pycharm says that error, because it can happen that "says_yes" ist False and the input will noch appear, then guess is not defined, i know you have an exit() but pycharm is pernickety.
HERE YOUR FULL CODE:
import random
random_number = random.randint(1, 10)
tries = 0
print("Enter yes, or no")
says_yes = False
says_no = False
while not says_yes or not says_no:
player_input = input("Would you like to play a game?: ")
player_input = player_input.lower().strip()
if player_input == "yes":
says_yes = True
break
elif player_input == "no":
says_no = True
print("See you next time.")
exit()
else:
print("You have to think about it again!")
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 and if you guess"
" it right then you win")
while True:
raw_guess = input("Guess a number: ")
try:
guess = int(raw_guess)
except ValueError:
print("Try it again, this was not a number!")
else:
if guess > 10 or guess < 1:
print("Please choose a number between 1-10.")
elif guess > random_number:
print("Guess lower")
tries += 1
elif guess < random_number:
print("Guess higher")
tries += 1
else:
break
print("It took you " + str(tries) + " tries to guess the number.")