While loop guessing number game python - python-3.x

So I think I understand why the code is not running past the while statement, but I don't know how to get it to recognize the guess part of it and run through it. I've searched through several questions on the looping part, but I can't actually see execution of it.
num_answer = int(input('What should the answer be? '))
guesses = int(input('How many guesses? '))
answer = int(input('Guess a number: '))
while answer != num_answer and guesses != guesses:
answer = int(input('Guess a number: '))
if answer < num_answer:
print('The number is higher than that.')
guesses += 1
answer = int(input('Guess a number: '))
elif answer > num_answer:
print('The number is lower than that.')
guesses += 1
answer = int(input('Guess a number: '))
elif answer == num_answer:
print('You win!')
elif guesses > guesses and answer != num_answer:
print("You lose; the number was", num_answer, ".")

You are trying to compare a variable to itself.
"guesses != guesses"
is always going to return false so your "while" is never going to be run.
You could change you guesses variable into two separate.
num_answer = int(input('What should the answer be? '))
guessesMax = int(input('How many guesses? '))
answer = int(input('Guess a number: '))
while answer != num_answer and guessesMax != guessesCount:
answer = int(input('Guess a number: '))
if answer < num_answer:
print('The number is higher than that.')
guessesCount += 1
answer = int(input('Guess a number: '))
elif answer > num_answer:
print('The number is lower than that.')
guessesCount += 1
answer = int(input('Guess a number: '))
elif answer == num_answer:
print('You win!')
elif guessesCount == guessesMax and answer != num_answer:
print("You lose; the number was", num_answer, ".")
Also changed your last elif with a "==". But it is useless because when
guessesCount == guessesMax
the while will not be executed ;)
EDIT:
You need to add
guessesCount = 0
On top for it to work.
Also in your while
answer = int(input('Guess a number: '))
is executing twice, either you put it in the beggining of your loop or in each "if, elif, else" but now in both ;)

Related

Counting and Error Handling Block Guessing Game

Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!

How to access the variable delcared inside a function outside the function in Python 3?

I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')

How do i make my input take all int and str type of data

I'm trying to get a guessing game with the user input as an answer and if the user type exit the game will show the amount of time the player tried but the program won't run because it can only take either interger or string type.
import random
while True:
number = random.randint(1,9)
guess = int(input('guess the number: '))
time = 0
time += 1
if guess == number:
print('you guessed correct')
elif guess < number:
print('your guessed is lower than the actual number')
elif guess > number:
print('your guessed is higher than the actual number')
elif guess == 'exit':
print(time)
break
something like this
import random
time = 0
number = random.randint(1,9)
while True:
guess = input('guess the number: ')
time += 1
if guess == "exit":
print(time)
break
elif int(guess) < number:
print('your guessed is lower than the actual number')
elif int(guess) > number:
print('your guessed is higher than the actual number')
elif int(guess) == number:
print('you guessed correct')
print(time)
break
note that time and number have to be initializate outside the while loop, because if not, we would get different random numbers for each iteration, and also time would be initializate to 0 each time.
You can test the input as a string first before converting it to an integer:
while True:
response = input('guess the number: ')
if response == 'exit':
break
guess = int(response)
# the rest of your code testing guess as a number

While Loop complication in guess the number game

So I am making a guess the number game in Python 3
After the whole process, I want my while loop to generate another number so that I can start the game again without running the program again.
Please let me know what I'm doing wrong, and if you could provide me with some insight on how to use the while loop, it'll be much appreciated.
Here's the code :
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
Not sure if the code you pasted was a typo (on indentation), but I may have accidentally changed your implementation.
Regardless, you should just add another while loop, and a break condition when the user gets it right.
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
In doing so, the code will keep looping to guess the correct number until they are correct. And then generate a new number to guess. However this code will never end unless you add another breaking condition (such as setting a flag the while loop will check to break out of the outer loop.
I wrote some quick code that prompts the user if they want to continue playing or not and then loops through and continues the game with a new number if they want to. I also fixed some minor bugs. Your count kept getting reset in the loop so it would always say you found it in 1 try.
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()

Python 3 number guessing game

I created a simple number guessing game, but every time I don't type in a number the system crashes. Can someone please help!
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
guess = int(guess)
if guess > randNum:
print("your guess is too high")
elif guess < randNum:
print("your guess is too low")
elif guess == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
I took a quick look at your code and one thing which stands out is that on Line 10, you cast the input to an int without checking if the input is indeed an int.
The system crashes because Python cannot typecast characters to integers when you type cast them. You should explicitly write a condition to check for characters i.e. if the input string is anything except numbers, your code should print something like "Try Again" or "Invalid Input".
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
if guess.isdigit():
if int(guess) > randNum:
print("your guess is too high \n")
elif int(guess) < randNum:
print("your guess is too low \n")
elif int(guess) == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
else:
print("Invalid Input! Try a number. \n")
Try this code. I hope it helps. And from next time try to upload code instead of images. ;-)
import random
def game():
computer = random.randint(1, 10)
# print(computer)
user = int(input("Please guess a number between 1-10: "))
count = 0
while count < 5:
if computer > user:
count += 1
print("You guessed too low!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number!: "))
elif computer < user:
count += 1
print("You guessed too high!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number: "))
else:
print("YOU WON!!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
if count == 5:
print("Bummer, nice try...the number was actually " + str(computer) + "!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
else:
print("I'm sorry that's an invalid entry! Restart the game to try again!")
game()

Resources