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
...
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.
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+
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)
Beginner in Python. I've been attempting to make my game give the user a 'play again?' option once the initial game is complete. The replay works if I failed to guess the number after 6 tries, however if I managed to guess the number and try to replay nothing happens.
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Thanks in advance for any tips.
You can also define your game in a separate function. I'd do something like this:
import random
def play_game():
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
if __name__ == '__main__':
playGame = 'y'
while playGame == 'y':
play_game()
playGame = input('Would you like to play again? [y/n] ').lower()
print("Goodbye!")
Just add a break at the if where you're 'restarting' the game:
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
#Break here to exit while loop
break
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Hope this helps you!
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.")