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'
Related
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
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)
So I am trying to get my Ask_Number to cooperate with my guessing game. For some reason the game code wont reconize that the Response to the Ask_Number is an interger. I've tried to define response as well and that just ends up breaking the code in a different way. I am going insane with this stuff. Here is the code:
import sys
def ask_number(question, low, high):
"""Ask for a number from 1 to 100."""
response = int(input(question))
while response not in range(low, high):
ask_number("Try again. ", 1, 100)
break
else:
print(response)
return response
ask_number("Give me a number from 1-100: ", 1, 100)
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible. OR ELSE!!!\n")
le_number = ask_number
guess = int(input("Take a Friggin Guess: "))
tries = 1
# guessing loop
while guess != le_number:
if guess > le_number:
print("Lower Idgit....")
else:
print("Higher Idgit...")
if tries > 5:
print("Too bad Idgit. You tried to many times and failed... What a shocker.")
print("The number was", le_number)
input("\n\nPress the enter key to exit Idgit")
sys.exit()
guess = int(input("Take a guess:"))
tries += 1
print("You guessed it! The number was", le_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit Idgit")
If you guys could help me shed some light that would be great.
This is confusing:
response = int(input(question))
while response not in range(low, high):
ask_number("Try again. ", 1, 100)
break # will leave the loop after 1 retry
else: # so the while is superflous
print(response) # and the else part is never executed if you break
return response # from a while, only if it evaluates to false
and this:
le_number = ask_number
does not execute the function - you need to call it:
le_number = ask_number("some question", 5,200) # with correct params
# or
while guess != ask_number("some question", 5,200): # with correct params
It would be better to do "more" inside the function. The function of this function is to provide you with a number - all that is needed to do so is inside it - you can easily test/use it and be sure to get a number from it (unless the user kills your program, dies or the computer crashes):
def ask_number(question, low, high):
"""Ask for a number from low to high (inclusive)."""
msg = f"Value must be in range [{low}-{high}]"
while True:
try:
num = int(input(question))
if low <= num <= high:
return num
print(msg)
except ValueError:
print(msg)
ask_number("Give me a number: ",20,100)
Output:
Give me a number: 1
Value must be in range [20-100]
Give me a number: 5
Value must be in range [20-100]
Give me a number: tata
Value must be in range [20-100]
Give me a number: 120
Value must be in range [20-100]
Give me a number: 50
This way only valid values ever escape the function.
For more infos please read the answers on Asking the user for input until they give a valid response
the_given_number = ask_number("Give me a number: ",20,100)
# do something with it
print(200*the_given_number) # prints 10000 for input of 50
I tried this on both pyCharm and IDLE. Both have same results. I don't understand why if the while statement is set to true it prints out the first print line infinitely.. even when I set it to false after the user guesses the number correctly.
import random
def Main():
number = random.randint(1,100)
playing = True # figure out stupid True infinite loop ~~
print("Welcome !\n")
while (playing):
print("Guess A Number Between 1 & 100: ")
guess = int(input("Your Guess: "))
if guess == number:
print("Congratulations !") # maybe add a 'your number was' thing ~
playing = False
elif guess > number:
print(int(input("Guess Lower: ")))
else:
print(int(input("Guess Higher: ")))
if __name__ == "__main__":
Main()
The only thing inside the while loop is that print() statement. Fix your indentation.
This is an extrapolation of what you need to do, using a function to make clear you have to perform the whole set of actions inside the while loop:
import random
def Main():
number = random.randint(1,100)
playing = True # figure out stupid True infinite loop ~~
print("Welcome !\n")
while (playing):
RunGameCycle()
def RunGameCycle():
""" Everything inside this function is what should happend each loop,
but wasn't because you haven't indented properly """
print("Guess A Number Between 1 & 100: ")
guess = int(input("Your Guess: "))
if guess == number:
print("Congratulations !") # maybe add a 'your number was' thing ~
playing = False
elif guess > number:
print(int(input("Guess Lower: ")))
else:
print(int(input("Guess Higher: ")))
if __name__ == "__main__":
Main()
#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)