I made a loop which gives the user the chance to guess the right number. The problem is that my loop is continuing after the user guesses the right or wrong number. I want that the user can try up to three times. If they can't guess the right number within three chances then the loop will be closed.
Here is my code:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
you need to inclement value by 1 otherwise you loop will be continue.
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess_count += 1
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
else:
guess_count = guess_limit
print("you tried maximum time")
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
break# break loop
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
else:
guess_count += 1# increment count
First you should increase the guess_count, Doing that will make the loop automatically exit after 3 tries.
Also, you should include a break if the user guesses correctly. The break keyword exits the loop immediately.
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
break
elif give_number != secret_number:
print("you guess wrong number")
guess_count += 1
except ValueError:
print("only integer or float value allowed")
Related
I'm having a problem understanding which part of my code belongs to a funtions and which does not. My code is messy and I know I need to use functions to clean it up.
The code below is a console game whereby a computer generates a random integer between 1 and 100 and the user user guesses that number with a limited number of guesses.eg. 5 for hard. 10 for easy.
How can I use funtions in this code?
#TODO 1: Generate a random number between 1 and 100
import random
GUESS = random.randint(1, 100)
#TODO 2: Print the guess(,for debugging)
#TODO 3: Choose the difficulty("easy" or "hard")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
#TODO 4: Loop 5 times if the user typed 'hard' or 10 times if the user typed 'easy'
if difficulty == "hard":
try:
#TODO 4.1: User inputs the guesses the random number
print("You have 5 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
except ValueError:
print("Please input a number")
elif difficulty == "easy":
#TODO 4.1: User inputs the guesses the random number
try:
print("You have 10 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
#I probably have to use exceptions
#So im going to do a google search real quick
#value errors
except ValueError:
print("Please input a number")
In pseudo code, here's an example of one function that might be useful:
function CheckGuess (INTEGER guess, INTEGER answer) returns an STRING
if guess > answer
return "too high"
if guess < answer
return "too low"
else
return "exactly"
Now, keeping in mind that a function accepts 0 or more inputs and always returns single output, and that output should always be the same, given the same input, lets see how this can be used as a functional object.
if CheckGuess(7, 10) != "exactly"
guesses = guesses - 1;
This is only one way of dozens that could be useful. Hope this helps!
this could work, though i might have missed some functionality.:
def prompt(prompt):
prompt(input)
def guessing_game:
num_to_guess = random.randint(1,100)
while number_of_guesses > 0:
os.system("cls")
guessed_number = prompt("guess between 1 and 100")
if gessed_number == num_to_guess:
os.system("cls")
number_of_guesses = 0
print("you got it!")
else:
if number_guessed < num_to_guess:
os.system("cls")
print("to low...")
number_of_guesses =- 1
else:
os.system("cls")
print("too high...")
number_of_guesses =- 1
if number_of_guesses == 0:
print("you lost...")
quit()
if this dosent work, check for typos.
Python noob here. Took a swing at the 'guess the number game' this afternoon.
It all looks fine to me but i keep getting a syntax error on line 26:
else player_number >= secret_number:
I've tried everything but I can't figure it out at all.
Thanks for your help.
import random, sys
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print("That's it!! The number was: " + secret_number)
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
else player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print("The correct number was: " + secret_number)
print("Please try again.")
Change your else statement to elif. The else statement takes no expression. Therefore:
elif player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
After actually running the code, I see you are trying to concatenate integer and string, but that won't work. To make it work, use the f' print.
Here is the code:
import random
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print(f"That's it!! The number was: {secret_number}") # f' print here
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print(f"You have {countdown_timer} guesses left.") # here
print("Please enter your next guess: ")
elif player_number >= secret_number:
print("Lower!")
print(f"You have {countdown_timer} guesses left.") #here
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print(f"The correct number was: {secret_number}") # and here
print("Please try again.")
I would replace the whole line with just "else:" and add a comment:
if player_number == secret_number:
...
elif player_number <= secret_number:
...
else:
# player_number >= secret_number
...
So I want to print "Wrong!" every time I get the wrong input. It works but when I type
the right input it still executes the "if" statement despite "guess.capitalize() != secret_word" being false. Can you tell me what I'm doing wrong?
multiple methods is appreciated !
secret_word = "Dog"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess.capitalize() != secret_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Enter your guess: ")
guess_count += 1
print("Wrong!")
else:
out_of_guesses = True
if out_of_guesses:
print("You ran out of guesses")
else:
print("You won!")
I commented the part of your code that is causing the bug:
while guess.capitalize() != secret_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Enter your guess: ")# Here, the user can input correct word or wrong word
guess_count += 1
print("Wrong!") # The code goes down here, regardless of what the user input
else:
out_of_guesses = True
Corrected version:
secret_word = "Dog"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while not out_of_guesses:
if guess_count < guess_limit:
guess = input("Enter your guess: ")# Here, the user can input correct word or wrong word
if guess.lower() != secret_word.lower():
guess_count += 1
print("Wrong!") # The code goes down here, regardless of what the user input
else:
break
else:
out_of_guesses = True
if out_of_guesses:
print("You ran out of guesses")
else:
print("You won!")
HI i think i understand what you are trying to do, i have read your code and restructred it to try give you your desired output.
secret_word = "Dog"
guess_count = 0
while True:
if guess_count != 3:
guess_count +=1
guess = input("Enter your guess: ")
if guess.upper() == secret_word.upper():
print("You Won!")
break
else:
print("Wrong")
continue
else:
print("You ran out of guesses")
break
please let me know if this is not the output you are trying to get.
I'm still quite new to Python so I apologise if this is too easy or stupid, but I was recently given the task to create a number guessing game. The game has 100 numbers, numbered from 1 to 100, and will also have a dice roll numbered 1 to 6 to determine how many tries you get (e.g If the user rolls a 4, the user will get 4 turns to try and guess the number between 1 to 100). So far I managed to complete most of it, however, upon testing the program myself, when I actually get the correct answer it doesn't display a win.
import random
random_number = random.randint(1, 5)#I made the range from 1 to 5 to make my chances of guessing the correct number greater#
guessnum_dice = random.randint(1, 6)
guess_count = 0
guess_limit = guessnum_dice
out_of_guesses = False
win = False
# This name function prints out the users name; this is because the task asks me to save each game's
# statisitics and record them within an external text file. Still haven't figured out how to do that
# as well :(
def name_function():
x = input("Enter your name: ")
print("Hello, " + x)
return
name_function()
user_roll = input("Type \"roll\" to roll the dice: ")
if user_roll == "roll":
print("You have "+str(guessnum_dice) + " guesses. Use them wisely!")
if guessnum_dice == 1:
user_guess = input("Guess the secret number: ")
if user_guess != random_number:
out_of_guesses = True
if guessnum_dice == 2:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
#Here Ive tried making the user's guess equal to the number, but to no success
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 3:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 4:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 5:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 6:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if out_of_guesses:
print("You Lose! The number: " + str(random_number))
if win == True:
print("You won")
And here is the output:
Enter your name: Gary
Hello, Gary
Type "roll" to roll the dice: roll
You have 6 guesses. Use them wisely!
Guess the secret number: 4
Lower
Guess the secret number: 3
Lower
Guess the secret number: 2 ### Here you can see that 2 is the correct answer, but it wont display a-
Guess the secret number: 2 ### -win no matter how many times it gets entered
Guess the secret number: 2
Guess the secret number: 1
Higher!
You Lose! The number: 2
Process finished with exit code 0
Once again I apoligise if this seems confusing as I find it difficult to try and explain my problem. Any advice would be much appreciated
Please consider using loop to go through all guesses instead of using if statements, in this way your code will be more compact and you can change the loop counter as you wish.
Also when you get user input, cast it to integer so that you can compare the numbers, otherwise user input will remain as string. check out below solution:
#This is a guess the number game
import random
print("What is your name?")
myName = input()
print("Well, " + myName + ", I am thinking of a number between 1 and 20")
loopCounter = 0
myNumber = random.randint(1, 20)
while loopCounter < 6:
print("Take a guess.")
guessNumber = input()
guessNumber = int(guessNumber)
loopCounter = loopCounter + 1
if guessNumber < myNumber:
print("Your guess is too low.")
elif guessNumber > myNumber:
print("Your guess is too high.")
else:
loopCounter = str(loopCounter)
print("Well done, " + myName + ", you guessed the number in " + loopCounter + " guesses!")
break
if guessNumber != myNumber:
myNumber = str(myNumber)
print("Nope. The number was " + myNumber)
Hope this helps.
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)