Guessing random number project - python-3.x

I'm a newbie of coding. I'm trying to create a guessing random number game by python. The thing is I get stuck at limited users by 5 turns guessing only. Here is my code so far. Thank you
print("""
WELCOME TO GUESSING NUMBER GAME!!!
You have 5 turns to guess a random number. Good luck!
""")
def play():
import random
random_numnber = random.randint(0, 20)
guess_count = 0
while True:
try:
guess = int(input("Please enter an integer from 1 to 20: "))
guess_count += 1
except ValueError:
print("Invalid Input\n")
continue
else:
break
while random_numnber != guess and guess_count < 5:
if int(guess) < random_numnber and int(guess_count) < 5:
print("Your number is too low\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) > random_numnber and int(guess_count) < 5:
print("Your number is too high\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) == random_numnber and int(guess_count) < 5:
print("Congratulation! You Win!\n")
break
else:
print("You have guessed 5 times and all Wrong. Good luck on next game!")
break
while True:
answer = input("Do you want to play? ")
if answer == 'yes' or answer == 'y':
play()
elif answer == 'no' or answer == 'n':
break
else:
print("I don't understand\n")

This is how I would go about doing this, I have modified your code and omitted some trivial error handling for non-integer inputs, etc.
The trick is that the code section between the # *** comments will be exited automatically if the guess_count value exceeds the maximum_tries, so we can actually remove a lot of the conditionals you were performing in-line which cluttered the real logic we care about.
You can also see that the only way that we can reach the line where we print "All out of guesses" is if the user has not already guessed the correct number.
Finally, since you mentioned you are just starting out I included a main() function as well as the Pythonic block at the end, which is just a special way to tell Python which part of the program you want to start with when you run the script. Happy coding!
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()

def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()

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!

I am confused to why my python guessing game is not working properly when I ask to play again

I am trying to get it to ask for me to play again and only accept y or n but I am confused as to why it is not working correctly. I am also getting the count value wrong as I am trying to break out of the while loop answer when I have the answer correct.
#Guessing game
import random
def guess():
playAgain = 'y'
while playAgain != 'n' and playAgain != 'no':
if playAgain == 'y' or playAgain == 'yes':
randomNum = random.randint(1, 2)
answer = 'false'
count = 0
while answer != 'true':
count = count + 1
print("Can you guess the random number?")
guess = int(input())
if guess > randomNum:
print("Too high, guess again.")
if guess < randomNum:
print("Too low, guess again.")
if guess == randomNum:
print("You guessed the number! It too you " + str(count) + " tries.")
answer == 'true'
print("Do you want to play again? (y or n)")
playAgain= input()
else:
print("You must enter y or n")
print("Do you want to play again? (y or n)")
playAgain= input()
guess()
print("Thank you for playing.")
At first glance there are two easy fixes;
You can fix the typo at line 23: answer = 'true'
You can add if playAgain == "n": break at line 26 (below playAgain= input())

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!')

Why doesn't my hangman game work the way it's supposed to

import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()

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