How do you restart a python guess a number game? - python-3.x

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

Related

Counting and Error Handling Block Guessing Game

Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!

Number guessing game that requires suggestions for completion

how do I get the difficulty level to work? I have found other codes similar but the difficulty is based on the group of number that it will choose the number from i.e. easy(1,10), medium (1,50), hard (1,100). I need to know how to make it work for the number of guesses. It keeps telling me I don't have easy,medium, or hard defined. how do I define them in way to make this code work?
I can get through it asking for my name then it will ask for the difficulty level and when I type e,m,or,h this is what it gives me: Traceback (most recent call last): File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 58, in guesses = get_guesses(level) File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 50, in get_guesses if diffuculty == hard: NameError: name 'diffuculty' is not defined
here is the objectives for the code:
You are to ask the user if they wish to play the game or continue playing the game after they have guessed the number
You are to ask the user if they want easy, medium or HARD (Easy = unlimited guesses, Medium = 10 guesses, HARD = 5 guesses)
Once the game begins play you are to tell the user that you have picked a number and they are to guess what that number is
your application is to accept the players guess and if their guess is larger than the number you had picked then tell them that, if their guess is smaller then tell them that as well.
The game continues to play until the player picks the number you had originally picked or they have ran out of guesses. I also need to have an exception.
Here is my code so far:
This is a guessing the number game.
import random
this statement will allow the options for playing and quiting the game.
play = True
while play:
difficulty = 0
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
easy = random.randint (1,100)
easy = random.randint (1,100)
easy = random.randint (1,100)
prompts the user to select a difficulty to play on
def select_level():
while True:
level = str(input("Would you like to play on easy, medium, or hard? \n"
"Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
if level != "e" and level != "m" and level != "h":
print("Invalid input!\n")
if level == "e" or level == "m" or level == "h":
break
return level
function that prompts the user to guess depending on chosen difficulty
def guess_number(level):
if level == "e":
(easy == 500)
if level == "m":
(medium == 10)
if level == "h":
(hard == 5)
return guesses
selects number of guesses depending on difficulty selected
def get_guesses(level):
if difficulty == easy:
print ("Okay, " + myName + ". You have unlimited guesses")
if difficulty == medium:
print ("Okay, " + myName + ". You have 10 guesses.")
if diffuculty == hard:
print ("Okay, " + myName + ". You have 5 guesses.")
elif level != "e" and level != "m" and level != "h":
print ("Invalid input!")
get_guesses()
return guesses
level = select_level()
guesses = get_guesses(level)
print('Well, ' + myName + ', I am thinking of a number can you guess it?')
while guessesTaken < level:
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 the number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
Here's the object oriented approach :
from random import randint
class Guessing_Game () :
def __init__ (self, users_name) :
self.difficulty = 10
self.name = users_name
self.start_the_game ()
def start_the_game (self) :
my_secret_number = randint (1, self.difficulty)
print ('Well, ' + self.name + ', I am thinking of a ', end = '')
print ('between 1 and ' + str (self.difficulty) + '.')
print ('Can you guess it?')
self.guess_the_number (my_secret_number)
def guess_the_number (self, the_secret_number) :
still_playing = True
while still_playing == True :
answer = int (input ('Take a guess : '))
if answer == the_secret_number :
print ('That is exactly correct! You win!')
still_playing = False
else :
if answer > the_secret_number :
print ('Sorry, you are too high.')
if answer < the_secret_number :
print ('Sorry, you are too low.')
if self.play_again () == True :
self.start_the_game ()
def play_again (self) :
self.difficulty = self.difficulty * 2
answer = input ('Would you like to play again? ')
if answer [0].lower () == 'y' : return True
return False
users_name = input ('Please enter your name : ')
my_game = Guessing_Game (users_name)

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Python 3 number guessing game

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

Resources