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+
Related
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
...
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)
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.")
I'm just starting out on python and I'm wondering exactly why my variable guesses is not defined. I feel as if it's a indentation issue but once I change the indentation I usually come upon a syntax error any help understanding this issue would be greatly appreciated.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
This doesn't throw any errors on my computer. Note you'll have to call the game() function if you want to actually run the code.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
game() # to run the code