import random.randint guess game - python

problem1 = else not working when i type for example some character it crash
problem2 = when i win(guess number) it wont do anything (it should print (more in code))
import random
print("guess number 1,5")
player = int(input("type guess: "))
pc = random.randint(1, 5)
attemp = 1
while player != pc:
attemp = +1
if player != pc:
print("your guess", int(player), "pc", int(pc))
player = int(input("type guess: "))
pc = random.randint(1, 5)
elif player == pc:
print(
"you win with number",
int(player),
"you had",
int(attemp),
"attempts",
)
else:
print("please type int num only")
hráč = int(input("type type: "))
pc = random.randint(1, 5)

There are a few different places where the code doesn't work as intended.
int(input("type guess: ")) will crash if you type in something that is not an integer, because int(...) tries to convert it to an integer and fails. The easiest way to fix this is to catch the exception and ask again for a number in a loop:
while True:
try:
player = int(input("type guess: ")) # If this line fails, break won't be executed
break # If the conversion went well we exit the loop
except ValueError:
print('Invalid number')
while player != pc will exit the loop as soon as the user inputs the right number, and the code that prints the success message will not be executed. To fix this, change the loop in a while True and insert a break after you print the success message:
while True:
[...]
elif player == pc:
print("you win with number", [...])
break
You may also notice that the if...elif branches inside the loop cover every possible condition, so the final else part will never be executed. This is not a problem, since we are already handling the input error part when reading the number, so we can remove the else part completely. To simplify the code even more, the condition in the elif isn't necessary, since it's the opposite of the condition in the if, so the logic can be reduced to this:
<read number from user>
while True:
if player != pc:
<print failure message, get new number from the user and new random number>
else:
<print success message>
break
Finally, there is a small mistake in your code:
attemp = +1 probably doesn't do what you want it to do, in that it sets attemp to be equal to +1. I'm assuming you meant attemp += 1, which increments the value by 1
The final code becomes:
import random
print("guess number 1,5")
while True:
try:
player = int(input("type guess: "))
break
except ValueError:
print('Invalid number')
pc = random.randint(1, 5)
attemp = 1
while True:
attemp += 1
if player != pc:
print("your guess", int(player), "pc", int(pc))
while True:
try:
player = int(input("type guess: "))
break
except ValueError:
print('Invalid number')
pc = random.randint(1, 5)
else:
print(
"you win with number",
int(player),
"you had",
int(attemp),
"attempts",
)
break
This is not the cleanest possile way to do it (for example, reading a number from the user is a perfect candidate for a separate function, or you could restructure the logic so that in each iteration of the while True loop you first ask for a number, check it against the random number, print the right message and break if necessary), but I don't want to modify the code too much

Related

How to get my random number guessing game to loop again upon user input and how to create an error trap?

So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)

Python - Loop Escaping unexpectedly and not iterating over list as expected

import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2

Function in Python game not breaking and won't continue to next function

For a class we have to make a game where a person will enter an upper integer and a lower integer for a range. Then a random number is picked from in between those two numbers. The player would then guess a number and the game would end when you guessed the right number. In the function for my range I have a loop that will only end when you enter a correct range. It will then clear the console and continue to the guessing part of the game. The problem is once you enter a correct range it will clear the screen, then execute the wrong part of the loop and make it impossible to continue. What I have programmed so far is below, I started Python about 2 months ago.
**import time, os, random
#The beginning where you enter a range
def game_loop():
got_an_int = False
while got_an_int == False:
user_input1 = input("Enter the upper bound integer of the range: ")
user_input2 = input('Enter the lower bound integer of the range: ')
try:
user_input1 = int(user_input1)
user_input2 = int(user_input2)
print("Good job, that is a correct range.")
got_an_int = True
clear()
break
except:
print("That is not a correct range. Try again.")
#To continue after entering a correct range
def clear():
time.sleep(3)
os.system('clear')
time.sleep(1)
game_begin()
#Random Number Generator
def random_num(a,b):
random.randint(user_input1,user_input2)
#Where you begin the game
def game_begin():
guess_right = False
random_num = random_num(user_input1,user_input2)
while random_num != guess_right:
guess = input('Guess an integer in your range: ')
total_guess = [] + 1
try:
guess = int(guess)
if random_num > guess:
print("Too Low.")
guess_right = False
if random_num < guess:
print('Too High.')
guess_right = False
guess = int(guess)
if random_num == guess:
print("You got it! Good job.")
guess_right = True
the_end()
except:
print("That is not an int. Try again")**
You've got multiple problems, but the most glaring one is a combination of a few things:
random_num = random_num(user_input1, user_input2)
First, this line re-assigns the random_num symbol to be the result of calling random_num. After this line happens, any future calls to random_num won't work, because the function is "gone". Second, both user_input1 and user_input2 are not in scope in the game_begin function (they belong to the game_loop function).
Both of these problems are hidden because you're using "naked" excepts:
try:
...
except:
print(...)
You should only catch the Exceptions you're expecting and handle them appropriately, or make it so those exceptions won't happen.
In the end, I was able to get it to mostly work with the following. Additional problems I encountered are mentioned in the comments.
import time, os, random
def game_loop():
got_an_int = False
while got_an_int == False:
user_input1 = input("Enter the upper bound integer of the range: ")
user_input2 = input('Enter the lower bound integer of the range: ')
try:
user_input1 = int(user_input1)
user_input2 = int(user_input2)
print("Good job, that is a correct range.")
got_an_int = True
clear()
# Move game_begin call here and use parameters, so that randint call works
game_begin(user_input1, user_input2)
break
except:
print("That is not a correct range. Try again.")
def clear():
time.sleep(3)
os.system('clear')
time.sleep(1)
# Remove this - not needed
# def random_num(a,b):
# random.randint(user_input1,user_input2)
def game_begin(in1, in2):
guess_right = False
# No longer overwriting variable/func symbol
# Also, reverse order since range is taken Highest first then Lowest
random_num = random.randint(in2, in1)
# Initialize total_guess to 0
total_guess = 0
while random_num != guess_right:
guess = input('Guess an integer in your range: ')
# Can't add list and ints. I assume you wanted to keep a running total?
# Lists aren't how you would do that.
total_guess += 1
try:
guess = int(guess)
if random_num > guess:
print("Too Low.")
guess_right = False
if random_num < guess:
print('Too High.')
guess_right = False
guess = int(guess)
if random_num == guess:
print("You got it! Good job.")
guess_right = True
# This function doesn't exist, so the loop won't ever actually end
# NameError exception is raised
the_end()
except:
print("That is not an int. Try again")

Could not convert string to float in input

#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)

Python variable increment while-loop

I'm trying to make the variable number increase if user guessed the right number! And continue increase the increased one if it is guessed by another user. But it's seem my syntax is wrong. So i really need your help. Bellow is my code:
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it. The number is now increase'
number += 1 # Increase this so the next user won't know it!
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
You can do it without "running" variable, it's not needed
#!/usr/bin/python
# Filename: while.py
number = 23
import sys
try:
while True:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it. The number is now increase')
number += 1 # Increase this so the next user won't know it!
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
except ValueError:
print('Please write number')
except KeyboardInterrupt:
sys.exit("Ok, you're finished with your game")
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it. The number is now increase'
number += 1 # Increase this so the next user won't know it!
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
# Do anything else you want to do here
print 'Done'

Categories