What am I doing wrong in this game? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to take up my first scripting language: python. I'm currently making a little game where you guess a predetermined number from 1-100. It also tells you if the right answer is bigger or smaller. Currently my code always returns that the right number is smaller, while it is not.
edit: thanks a lot for helping me!
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
print(rightnumber)
gok = int(input("type your guess here and press enter"))
def compareguess():
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess()
def guessAgain():
int(input("try again. type your guess and press enter."))
compareguess()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()

You can pass gok as a parameter to avoid global variables.
The problem is:
When you take the input again: int(input("try again. type your guess and press enter.")), you don't assign the value to anything. So gok remains the same and it is always bigger or smaller
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
gok = int(input("type your guess here and press enter"))
def compareguess(gok):
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess(gok)
def guessAgain():
gok=int(input("try again. type your guess and press enter."))
compareguess(gok)
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
Also, don't use recursion. Instead, use a while loop. A shortened code without recursion:
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
while True:
gok = int(input("type your guess here and press enter"))
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
break
else:
print("wrong! the right number is bigger.")

The problem is with the scope of the parameters. The first guess is stored globaly in gok. Whether it is smaller or bigger, compareguess will print a correct message.
But when you call guessAgain you don't save the new guess anywhere, so the value of gok is still the old one. Even if you would save it, the scope wouldn't be correct so you won't see the new value in compareguess.
So a possible solution would be to pass gok as a parameter to compareguess (I also added rightnumber as a parameter).
def compareguess(gok, rightnumber):
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
And would now run -
while rightnumber != gok:
gok=int(input("try again. type your guess and press enter."))
compareguess(gok, rightnumber)

try this code
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
print(rightnumber)
gok = int(input("type your guess here and press enter"))
def compareguess(gok):
if gok == rightnumber:
print("WOW! you guessed right!")
elif gok > rightnumber:
print("wrong! the right number is smaller :)")
else:
print("wrong! the right number is bigger.")
compareguess(gok)
def guessAgain():
gok = int(input("try again. type your guess and press enter."))
compareguess(gok)
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()

your compareguess functiuon
def compareguess():
if gok < rightnumber:
print("wrong! the right number is smaller :) ")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger. ")
your guessAgain function
def guessAgain():
global gok
gok = int(input("try again. type your guess and press enter."))
compareguess()
if rightnumber == gok:
print("that was it! you won!")
else:
guessAgain()

You could use this.
It keeps asking until you type the correct number.
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = random.randint(1, 100)
print(rightnumber)
def guess():
gok = int(input("type your guess here and press enter: "))
if gok > rightnumber:
print("wrong! the right number is smaller :)")
guess()
elif gok == rightnumber:
print("WOW! you guessed right!")
print("that was it! you won!")
else:
print("wrong! the right number is bigger.")
guess()
guess()

Related

Implementing "Guess the number" game

This is my first post in StackOverFlow and I'm sure that I can find for 100% percent an answer for it, but I'd really like to start my adventure with programming and know that this community might help me with it.
My questions are:
I wrote that first piece of code but I'd like to add here a function where the user writes the guess number bigger than the first one.
I am troubled with adding the additional function if for this situation - I do understand that it wouldn't suppose to be if, but elif.
Is anyone has any idea how to suppose to look-alike??
import random
top_range = input("Write a number bigger then 0: ")
if top_range.isdigit() or top_range[0] == "-":
top_range = int(top_range)
if top_range <= 0:
print('Write a number bigger then 0')
quit()
else:
print('Write a number bot a word')
quit()
random_number = random.randint(0, top_range)
guesses = 0
while True:
guesses += 1
user_guess = input("Guess the number : ")
if user_guess.isdigit():
user_guess = int(user_guess)
else:
print('Write another number.')
continue
if user_guess == random_number:
print('You did it!')
break
else:
if user_guess < random_number:
print('The number is bigger then that')
else:
print('The number is smaller than that')
print('You did it in', guesses, "guesses!")
Add a first if, then use elif for the other choices. I've also simplify a bit the first if
while True:
guesses += 1
user_guess = input("Guess the number : ")
if not user_guess.isdigit():
print('Write another number.')
continue
user_guess = int(user_guess)
if user_guess > top_range:
print("That is higher than top range, try again")
elif user_guess == random_number:
print('You did it!')
break
elif user_guess < random_number:
print('The number is bigger then that, try again')
else:
print('The number is smaller than that, try again')

Heads or Tails in Python

The if and elif conditions aren't working and I am not even getting an error. The code is intended to match the users input to what the computer selects and then make a call, if the user won or lost.
import random
def flip():
return random.choice(["Heads", "Tails"])
Users_Selection = (input("Choose: Heads or Tails?"))
print("Flipping the coin. Please wait!")
print ("It a", flip())
if flip()=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif flip()=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")
All help is genuinely appreciated!
Everytime you call flip, it generates a new random output so you must store the value of flip in a variable.
c = flip()
print("It's a ", c)
if c=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif c=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")

Python "Guess The Number" game giving unexpected results

i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")

Python Guess game how to repeat

I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code
def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
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()
It's because your game code isn't in the function. Try it in this manner:
<import statements>
def game():
<insert all game code>
def main():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
game()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
There's a few problems with your code that I'd like to point out.
The main one being that your game does not run again when typing yes. All it will do is run main() which will print your game and then ask you if you want to retry once again. It's easier if you put your game inside a definition that way you can call it whenever necessary.
Also, I don't know if it's just me, but if you guess the correct number, it will still ask you to guess a number. You need to exit your loop by putting your play_again() method in your else block.
Below is the code. I've polished it up a little just for optimization.
import random #imports random number function
def main():
print("Welcome to the number guessing game!")
game = "your game"
print(game)
run_game()
play_again()
def run_game():
counter = 1
number = random.randint(1, 10)
while counter > 0 and counter <= 5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess > number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess != number and guess < number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was " + str(number))#Prints this out when you guessed the number
print("it took you " + str(counter) + " attempts!")#tells you how many attempts it took you to guess the number
play_again()
if counter == 2:
print("4 attempts left before program ends")
if counter == 3:
print("3 attempts left before program ends")
if counter == 4:
print("2 attempts left before program ends")
if counter == 5:
print("1 attempts left before program ends")
def play_again():
while True:
retry = input("Would you like to play again?(yes or no) : ")
if retry == "yes":
main()
if retry == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories