Guess a random number between 1 and 100
up vote
8
down vote
favorite
I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.
import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You won!!!')
break
elif i < num:
print('Try Higher')
elif i > num:
print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')
python python-3.x random number-guessing-game
add a comment |
up vote
8
down vote
favorite
I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.
import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You won!!!')
break
elif i < num:
print('Try Higher')
elif i > num:
print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')
python python-3.x random number-guessing-game
2
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33
add a comment |
up vote
8
down vote
favorite
up vote
8
down vote
favorite
I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.
import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You won!!!')
break
elif i < num:
print('Try Higher')
elif i > num:
print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')
python python-3.x random number-guessing-game
I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.
import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You won!!!')
break
elif i < num:
print('Try Higher')
elif i > num:
print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')
python python-3.x random number-guessing-game
python python-3.x random number-guessing-game
edited Aug 11 '15 at 0:28
Jamal♦
30.2k11115226
30.2k11115226
asked Aug 11 '15 at 0:22
Keanu Jones
150127
150127
2
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33
add a comment |
2
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33
2
2
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33
add a comment |
2 Answers
2
active
oldest
votes
up vote
6
down vote
accepted
Proper integer conversion
Right now, as it stands, you're just converting any user input to a integer, using the int
function. What do you suppose happens if the user enters something like "abc"
?
What you need to do is set up a try
-except
block, like this:
try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")
To set up something like this in your code, you'd change your code to something like this:
...
while True:
print("Guess a number between 1 and 100.")
guess = input()
try:
integer_guess = int(guess):
...
except ValueError:
...
Tracking the number of "rounds"/"tries"
Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... )
loop, like this:
rounds = ...
for _ in range(rounds):
...
(This has been implemented below, for reference.)
Design
This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
An example function call might look like this:
number_guessing_game(1, 100, 6)
In short, all of your code becomes the following:
import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
number_guessing_game(1, 100, 6)
Hope this helps!
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep thetry:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, thetry: except: else:
construction, putting theif: elif: elif
test in theelse
clause, would fit well (in the initial example, theinput
call should be outside thetry
clause on the same grounds). An alternative toelse
would be to usecontinue
within theexcept
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).
– Daniel Andersson
Aug 11 '15 at 14:25
add a comment |
up vote
5
down vote
guess = input()
i = int(guess)
Why are you splitting this on to two different lines? You can just merge the int()
onto the line above it, and pass input()
into it like this:
guess = int(input())
As Greg Hewgill mentioned in the comments, rather than saying this:
print('if you gussed less than 6 times you won')
You should actually count up and tell the user if they won.
This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:
num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1
Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts
variable:
if attempts < 6:
print("You won!")
else:
print("You lost!")
Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.
That is done like this:
ATTEMPTS_FOR_LOSE = 6
Then, you just substitute the 6
for ATTEMPTS_FOR_LOST
in the conditional snippet I showed a little above.
add a comment |
protected by Jamal♦ Nov 20 at 1:25
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
6
down vote
accepted
Proper integer conversion
Right now, as it stands, you're just converting any user input to a integer, using the int
function. What do you suppose happens if the user enters something like "abc"
?
What you need to do is set up a try
-except
block, like this:
try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")
To set up something like this in your code, you'd change your code to something like this:
...
while True:
print("Guess a number between 1 and 100.")
guess = input()
try:
integer_guess = int(guess):
...
except ValueError:
...
Tracking the number of "rounds"/"tries"
Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... )
loop, like this:
rounds = ...
for _ in range(rounds):
...
(This has been implemented below, for reference.)
Design
This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
An example function call might look like this:
number_guessing_game(1, 100, 6)
In short, all of your code becomes the following:
import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
number_guessing_game(1, 100, 6)
Hope this helps!
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep thetry:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, thetry: except: else:
construction, putting theif: elif: elif
test in theelse
clause, would fit well (in the initial example, theinput
call should be outside thetry
clause on the same grounds). An alternative toelse
would be to usecontinue
within theexcept
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).
– Daniel Andersson
Aug 11 '15 at 14:25
add a comment |
up vote
6
down vote
accepted
Proper integer conversion
Right now, as it stands, you're just converting any user input to a integer, using the int
function. What do you suppose happens if the user enters something like "abc"
?
What you need to do is set up a try
-except
block, like this:
try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")
To set up something like this in your code, you'd change your code to something like this:
...
while True:
print("Guess a number between 1 and 100.")
guess = input()
try:
integer_guess = int(guess):
...
except ValueError:
...
Tracking the number of "rounds"/"tries"
Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... )
loop, like this:
rounds = ...
for _ in range(rounds):
...
(This has been implemented below, for reference.)
Design
This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
An example function call might look like this:
number_guessing_game(1, 100, 6)
In short, all of your code becomes the following:
import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
number_guessing_game(1, 100, 6)
Hope this helps!
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep thetry:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, thetry: except: else:
construction, putting theif: elif: elif
test in theelse
clause, would fit well (in the initial example, theinput
call should be outside thetry
clause on the same grounds). An alternative toelse
would be to usecontinue
within theexcept
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).
– Daniel Andersson
Aug 11 '15 at 14:25
add a comment |
up vote
6
down vote
accepted
up vote
6
down vote
accepted
Proper integer conversion
Right now, as it stands, you're just converting any user input to a integer, using the int
function. What do you suppose happens if the user enters something like "abc"
?
What you need to do is set up a try
-except
block, like this:
try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")
To set up something like this in your code, you'd change your code to something like this:
...
while True:
print("Guess a number between 1 and 100.")
guess = input()
try:
integer_guess = int(guess):
...
except ValueError:
...
Tracking the number of "rounds"/"tries"
Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... )
loop, like this:
rounds = ...
for _ in range(rounds):
...
(This has been implemented below, for reference.)
Design
This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
An example function call might look like this:
number_guessing_game(1, 100, 6)
In short, all of your code becomes the following:
import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
number_guessing_game(1, 100, 6)
Hope this helps!
Proper integer conversion
Right now, as it stands, you're just converting any user input to a integer, using the int
function. What do you suppose happens if the user enters something like "abc"
?
What you need to do is set up a try
-except
block, like this:
try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")
To set up something like this in your code, you'd change your code to something like this:
...
while True:
print("Guess a number between 1 and 100.")
guess = input()
try:
integer_guess = int(guess):
...
except ValueError:
...
Tracking the number of "rounds"/"tries"
Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... )
loop, like this:
rounds = ...
for _ in range(rounds):
...
(This has been implemented below, for reference.)
Design
This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
An example function call might look like this:
number_guessing_game(1, 100, 6)
In short, all of your code becomes the following:
import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an integer: ")
try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')
except ValueError:
print("You must enter a valid integer.")
print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))
number_guessing_game(1, 100, 6)
Hope this helps!
answered Aug 11 '15 at 0:48
Ethan Bierlein
12.8k242136
12.8k242136
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep thetry:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, thetry: except: else:
construction, putting theif: elif: elif
test in theelse
clause, would fit well (in the initial example, theinput
call should be outside thetry
clause on the same grounds). An alternative toelse
would be to usecontinue
within theexcept
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).
– Daniel Andersson
Aug 11 '15 at 14:25
add a comment |
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep thetry:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, thetry: except: else:
construction, putting theif: elif: elif
test in theelse
clause, would fit well (in the initial example, theinput
call should be outside thetry
clause on the same grounds). An alternative toelse
would be to usecontinue
within theexcept
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).
– Daniel Andersson
Aug 11 '15 at 14:25
4
4
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses.
– user3374348
Aug 11 '15 at 10:57
You should keep the
try:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, the try: except: else:
construction, putting the if: elif: elif
test in the else
clause, would fit well (in the initial example, the input
call should be outside the try
clause on the same grounds). An alternative to else
would be to use continue
within the except
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).– Daniel Andersson
Aug 11 '15 at 14:25
You should keep the
try:
block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, the try: except: else:
construction, putting the if: elif: elif
test in the else
clause, would fit well (in the initial example, the input
call should be outside the try
clause on the same grounds). An alternative to else
would be to use continue
within the except
clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though).– Daniel Andersson
Aug 11 '15 at 14:25
add a comment |
up vote
5
down vote
guess = input()
i = int(guess)
Why are you splitting this on to two different lines? You can just merge the int()
onto the line above it, and pass input()
into it like this:
guess = int(input())
As Greg Hewgill mentioned in the comments, rather than saying this:
print('if you gussed less than 6 times you won')
You should actually count up and tell the user if they won.
This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:
num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1
Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts
variable:
if attempts < 6:
print("You won!")
else:
print("You lost!")
Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.
That is done like this:
ATTEMPTS_FOR_LOSE = 6
Then, you just substitute the 6
for ATTEMPTS_FOR_LOST
in the conditional snippet I showed a little above.
add a comment |
up vote
5
down vote
guess = input()
i = int(guess)
Why are you splitting this on to two different lines? You can just merge the int()
onto the line above it, and pass input()
into it like this:
guess = int(input())
As Greg Hewgill mentioned in the comments, rather than saying this:
print('if you gussed less than 6 times you won')
You should actually count up and tell the user if they won.
This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:
num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1
Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts
variable:
if attempts < 6:
print("You won!")
else:
print("You lost!")
Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.
That is done like this:
ATTEMPTS_FOR_LOSE = 6
Then, you just substitute the 6
for ATTEMPTS_FOR_LOST
in the conditional snippet I showed a little above.
add a comment |
up vote
5
down vote
up vote
5
down vote
guess = input()
i = int(guess)
Why are you splitting this on to two different lines? You can just merge the int()
onto the line above it, and pass input()
into it like this:
guess = int(input())
As Greg Hewgill mentioned in the comments, rather than saying this:
print('if you gussed less than 6 times you won')
You should actually count up and tell the user if they won.
This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:
num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1
Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts
variable:
if attempts < 6:
print("You won!")
else:
print("You lost!")
Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.
That is done like this:
ATTEMPTS_FOR_LOSE = 6
Then, you just substitute the 6
for ATTEMPTS_FOR_LOST
in the conditional snippet I showed a little above.
guess = input()
i = int(guess)
Why are you splitting this on to two different lines? You can just merge the int()
onto the line above it, and pass input()
into it like this:
guess = int(input())
As Greg Hewgill mentioned in the comments, rather than saying this:
print('if you gussed less than 6 times you won')
You should actually count up and tell the user if they won.
This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:
num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1
Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts
variable:
if attempts < 6:
print("You won!")
else:
print("You lost!")
Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.
That is done like this:
ATTEMPTS_FOR_LOSE = 6
Then, you just substitute the 6
for ATTEMPTS_FOR_LOST
in the conditional snippet I showed a little above.
edited May 23 '17 at 12:40
Community♦
1
1
answered Aug 11 '15 at 0:47
SirPython
11.9k32790
11.9k32790
add a comment |
add a comment |
protected by Jamal♦ Nov 20 at 1:25
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2
One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost.
– Greg Hewgill
Aug 11 '15 at 0:33