Why my random number game doesn't work right? - python

guys! I'm new here. Nice to meet you!
I have the following problem. My random number generator always do exactly the same number. I have a guess why it's happening, but I'm not sure. Can you, please, explain what I'm doing wrong and just write some words about my code at all? Thanks!
import random
def begin():
r_num = random.randint(1, 10)
p_num = int(input('Enter your number: '))
ch = (r_num, p_num)
if ch[0] == ch[1]:
print(ch[0])
print("You've won! Excellent!")
play_again = input("Do you want to play again? y/n")
if play_again == 'y' or play_again == 'Y':
begin()
elif play_again == 'n' or play_again == 'N':
print('Goodbye!')
elif ch[1] < ch[0]:
print(ch[0])
print("Your number is lower than it must be!")
begin()
elif ch[1] > ch[0]:
print(ch[0])
print("Your number is higher than it must be!")
begin()
def start():
gen = input('Print generate to begin playing! \n')
if gen == 'generate':
print('Success!')
begin()
else:
print('Fail!')
start()
print('Welcome to my first Python game! Guess random generated number from 1 to 10!')
start()

The code works perfectly fine and so you genuinely must just have had incredibly good/bad luck (depending on which way you think about it). Try running the code in a different IDE - it's the only thing I can think of that may be causing the issue. Try running the script again?

Related

Why doesn't my function exit if the game is played more than once?

I'm practicing Python by making a simple guessing game. It seems to work well, however if the user plays more than once the program won't quit even if the answer to Play again? (y/n): is n. I'm thinking it has to do with the recursion but I'm not sure how to fix it.
Any pointers?
(The print(key) was just to make winning the game fast for debugging.)
import random
def guess():
while True:
get = input("Enter a number between 1 and 9: ")
try:
num = int(get)
break
except ValueError:
print("Please input an integer.")
return num
def run_game():
count = 0
key = random.randint(1, 9)
replay = None
print(key)
while True:
num = guess()
count += 1
if num == key:
print("Correct!")
print("Total guesses:", count)
replay = input("Play again? (y/n): ")
if replay == 'y':
run_game()
elif replay == 'n':
print("Thanks for playing!")
return
elif num > key:
print("Too high!")
else:
print("Too low!")
run_game()
You're running the function again recursively, but you don't exit after calling, so when the user quits from the second round, he goes back to the first round.
What you're missing is a return after your call to run_game.
ex.
if replay == 'y':
run_game()
return

how to get game to restart when user types 'yes'?

how do I make it restart when the user types "yes"
import random
answer=(random.randint (1,100))
play_again="yes"
tries=(0)``
guess=int(input("I'm thinking of a number between 1 and 100 "))
tries+=1
while play_again=="yes":
if (guess<answer):
guess=int(input("its higher than "+str(guess)+" "))
tries+=1
elif (guess>answer):
guess=int(input("it's lower than "+str(guess)+" "))
tries+=1
elif (guess==answer):
print("well done! You guessed the number in "+str(tries)+" guesses!")
play_again=input("would you like to play again?")
how do I make the game restart after the user wins when they type "yes"?
use two loops. one outer with play_again == "yes" and one inner with guess != answer.
while play_again == "yes":
# get input
while guess != answer:
# if lower:
# get guess
# if higher
# get guess
# get play_again
You can do this , create a function !
import random
import sys
def main():
# your code here
while True:
play_again = input("play again? :") # For python 2 raw_input()
if play_again == "yes":
main()
else:
sys.exit()
Something like this !
I hope this helps you!!
With a function that calls itself
def main():
# your code goes here
if input('Play again?') == 'yes':
main()

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

Could This Python Program Be Simplified Or Better Written?

Okay so I have been learning quite a bit of Python over the past few days, two or three, and I decided to take my knowledge and create something simple, but sort of entertaining, so I created a Guessing Game.
After about 30 minutes of creating this program and getting it to work 100% I was wondering if there was anything I could have done better, etc. I want to make sure I learn from any mistakes so I appreciate it!
So here is the code:
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
while yourGuess != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
else:
if yourGuess == randomNumber:
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame == "N" or playGame == "n":
print("Okay Thanks Anyways!")
break
Thanks Again!
Instead of
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
I kind of like
if playGame.lower() == "y":
# ...
I even better like:
def quit():
print("Okay Thanks Anyways!")
actions = {"y": guessingGame}
actions.get(playGame.lower(), quit)()
from random import randint
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's no integer!")
def play():
secret = randint(1,10)
while True:
guess = getInt("Take a guess (1-10):")
if guess==secret:
print("Congrats, you beat The Guess Game!")
break
else:
print("D'oh! You guessed wrong. Try again!")
def main():
while True:
inp = input("Would you like to play The Guessing Game? (Y/N)").lower()
if inp=="y":
print("Okay, let's play!")
play()
elif inp=="n":
print("Alright. Thanks anyways!")
break
else:
print("You don't follow directions too good, eh?")
if __name__=="__main__":
main()
A few things I noticed:
You should handle the case where user tries to guess something that doesn't look like a number, say the letter 'a' for example.
Python style guide says to prefer lower_with_underscores over CamelCase for variable names.
The line yourGuess = int(input("Take A Guess, Numbers 1 Through 10: ")) is unnecessarily duplicated, see below for one possible way to refactor that part.
General cleanup:
import random
def guessing_game():
random_number = random.randint(1, 10)
assert random_number in range(1, 11)
your_guess = None
while your_guess != random_number:
try:
your_guess = int(input("Take A Guess, Numbers 1 Through 10: "))
except ValueError:
print("That wasn't a number")
continue
if your_guess != random_number:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
print("Congrats You Beat The Guess Game!")
break
play_game = None
while play_game not in ['y', 'n']:
play_game = input("Would You Like To Play The Guessing Game (Y/N): ").lower()
if play_game == "y":
print("Okay Lets Play!")
guessing_game()
else:
assert play_game == "n":
print("Okay Thanks Anyways!")
I imagine you could use a "break" statement inside a while loop, as in
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
while True:
yourGuess = input("Take A Guess, Numbers 1 Through 10: ")
if !yourGuess.isdigit():
print ("That's not a number!")
elif int(yourGuess) not in range(1,10):
print("I said between 1 and 10!")
elif int(yourGuess) != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
break
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame.lower() == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame.lower() == "n":
print("Okay Thanks Anyways!")
break
Read the Pep 8 documentation on naming conventions and Python's style of coding.
import random
def guessing_game(x=1, y=10):
"""
A simple number guessing game.
"""
while int(input("Take A Guess, Numbers 1 Through 10: ")) \
!= random.randrange(x, y):
print("DOH! You Did Not Guess Right, TRY AGAIN")
print("Congrats You Beat The Guess Game!")
if input("Would You Like To Play The Guessing Game (Y/N): ") == 'Y':
print("Okay Lets Play!")
guessing_game()
else:
print("Okay Thanks Anyways!")
if __name__ == '__main__':
guessing_game(1, 10)

How to restart a simple coin tossing game

I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.

Categories