Python 3 number guessing game - python-3.x

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()

Related

Guessing random number project

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()

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

Python while loop through program not working

import random
replay = 1
while replay == 1:
replay = replay - 1
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
count = 0
score = 0
while count == 0:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again == "yes" or "YES":
replay = replay + 1
elif again == "no" or "NO":
break
This is my code, except it doesn't do what I want it to do. After you guess the correct number, it doesn't see to properly loop through the game again when you say yes or no. It just goes through the final if statement again.
Why won't it go through the entire program again?
Your code will always be evaluated to true
if again == "yes" or "YES":
Change it to:
if again.lower() == "yes":
Or
if again in ("YES", "yes", "y",..)
When it is true, you need to break from you second loop:
if again.lower() == "yes":
replay = replay + 1
break
When it is false, don't break but exit the program using:
exit()
Since replay is only used to exit your code, you don't need it if you use exit().
Code would then be:
import random
while True:
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
score = 0
while True:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again.lower() == "yes":
break
elif again.lower() == "no":
exit()

Repeating a whole algorithm

I am a real newbie to Python, I am taking it for GCSE at my school and I have been given an assignment to complete. I completed all of the requirements for this simple code but am not sure how to repeat it. Could someone please show me a simple way of repeating the code?
Thanks
import random
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")
Easiest way of doing it would be to put it in a while True loop with a conditional break:
import random
while True:
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")
choice = input("Would you like to continue? y/n")
if choice == "n":
break
Note, randint(1,100) will return a number from 1-99 inclusive, and you are actually asking the user for a guess 2-99 inclusive the way you have phrased it.

How do you restart a python guess a number game?

I'm a newbie at python, so i couldn't figure out how to make this code repeat at the beginning again. Here is my code:
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Thanks guys, please respond soon,
This must have been the code you've been looking around for
import random
inplay = 0
x = ""
def in_play():
global inplay, guessesTaken
guessesTaken = 0
if inplay == True:
play()
else:
inplay = True
play()
def play():
global guessesTaken
while inplay == True:
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
elif guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
in_play()
elif guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
in_play()
in_play()
Now that was something basic but for a newbie, we totally know how it feels
Just don't Copy Paste it but try to understand what the code does and why it does it
Put your current code in a function, and then invoke it as many times as you want. For example:
import random
def main():
n_games = 5
for n in range(n_games):
play_guessing_game()
def play_guessing_game():
# Your code here.
print("Blah blah")
main()
Even better would be to accept n_games as a command-line argument (sys.argv[1]). Even better than that would be to stop writing interactive guessing games (rant: why do people teach this stuff?) and instead learn how to write a function that does binary search.
put your code in a function, then create another function that asks the user if he would like to play again.
def main():
game = "your game"
print(game)
play_again()
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) > ")
if play_again == "yes"
main()
if play_again == "no"
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()

Resources