patternpythonMinor
Guess the bigger number out of two random integers
Viewed 0 times
randomnumberthebiggertwointegersoutguess
Problem
I want to make my code more efficient by instead of repeating my code again for level two, as the only change from level one to level two is the random numbers change from
```
#The two imports, import modules. They allow me to use functions defined elsewhere such as when I import a random number or
#use sys.exit() to terminate the game
import random
import sys
#Ask the user for name, use in opening comments
user_name=str(input("Please type in your name: "))
#print instructions
print('''Hello {}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {}, we are going to give you two numbers.
Then you must choose which of these numbers you think is bigger or which number is smaller.
Type this number in and if you are right you will get a point.
Get enough points and you can progress to level two!
''' .format(user_name, user_name))
#Set the scores of both user and computer to 0
user_score = 0
comp_score = 0
level = 1
#Only use the loop when the user score is below three
#Then randomly select to either have type_question to be bigger or smaller and this will define which path the program will take
while user_score < 3:
bigorsmall = ['bigger', 'smaller']
type_question = random.choice(bigorsmall)
#Import two random integers, then make sure these integers are not the same
a1 = random.randint(1, 10)
a2 = random.randint(1, 10)
while a1 == a2:
a2 = random.randint(1, 10)
print("\nThe two random values are {} and {}. \n " .format(a1, a2))
#--------------------------------------------------------------------------------------------------
1-10 to 1-100. I think I can make these a variable making max_number = 10 for level one and max_number = 100 for level two and use the same code, halfing the amount of lines I have in this code. However, I am unsure of how to do this as I am not extremely experienced. I have gotten tips to use a for loop, and I was wondering if anyone could help me with this:```
#The two imports, import modules. They allow me to use functions defined elsewhere such as when I import a random number or
#use sys.exit() to terminate the game
import random
import sys
#Ask the user for name, use in opening comments
user_name=str(input("Please type in your name: "))
#print instructions
print('''Hello {}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {}, we are going to give you two numbers.
Then you must choose which of these numbers you think is bigger or which number is smaller.
Type this number in and if you are right you will get a point.
Get enough points and you can progress to level two!
''' .format(user_name, user_name))
#Set the scores of both user and computer to 0
user_score = 0
comp_score = 0
level = 1
#Only use the loop when the user score is below three
#Then randomly select to either have type_question to be bigger or smaller and this will define which path the program will take
while user_score < 3:
bigorsmall = ['bigger', 'smaller']
type_question = random.choice(bigorsmall)
#Import two random integers, then make sure these integers are not the same
a1 = random.randint(1, 10)
a2 = random.randint(1, 10)
while a1 == a2:
a2 = random.randint(1, 10)
print("\nThe two random values are {} and {}. \n " .format(a1, a2))
#--------------------------------------------------------------------------------------------------
Solution
Comments vs documentation
Comments should be used to explain how the code works. Things that don't need to be explained are non-esoteric language features (for example you don't need to comment on what
You generally don't need comments like
that just separate two sections - well organized code (and judicious use of whitespace) should do that just fine.
Documentation should be used to explain what the code is intended to do. This is generally done with a module level docstring and then class/function/method level docstrings as appropriate.
PEP8
In general, unless there is a pressing reason not to (i.e. you're working in a larger code base that has it's own style, or you're doing an assignment for a class that requires a certain style, or you really don't like PEP8 styles), you should try to follow the PEP8 coding conventions. This includes things like naming:
It also includes spacing - for example you almost always want to use a single space to clearly separate operators from their arguments, items in a list, parameters to a function, etc.
This includes indentation - you generally want your comments to be at the same indentation as the thing they're commenting about.
Lastly, line-length. You generally want lines to be, at most, 79 characters long and your docstrings to be, at most, 72 characters long. Your text editor/IDE should have a way to set a ruler that shows you when you've gone too far.
Constants
You should define constants at the top of your file. For example,
Also avoid magic numbers - you have things like
which could be better defined this way
You can also set constants as members of an
Limit the scope of
A
Use functions!
Right now you have a lot of repeated code - we can use functions to consolidate that. Additionally, a named function can make it much more clear what you're trying to do without the use of comments. Right now you have code like
that could be more clearly represented as
All together
Here is your full program, rewritten in a way I think makes sense. Not everything I've changed in here was explicitly mentioned in the review above, but I think it should all be self explanatory from the previous comments
```
import random
import sys
from enum import Enum
user_name=str(input("Please type in your name: "))
print('''Hello {0}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {0}, we are going to give you two numbers.'''
'Then you must choose which of these numbers you think is bigger or which '
'number is smaller.'
'''
Type this number in and if you are right you will get a point.
Get enough points and you can progress to level two!
'''.format(user_name))
# Maps from the current level to the upper score limit
USER_SCORE_LIMIT = {
1: 3,
2: 5
}
SCORE_RANGE = {
1: (1, 10),
2: (1, 100)
}
GAME_MODES = Enum('GAME_MODES', 'BIGGER SMALLER')
def get_two_random_numbers(start, end):
first = random.randint(start, end)
second = random.randint(start, end)
while first == second:
second = random.randint(start, end)
return first, second
def choose_game_mode():
return random.choice(list(GAME_MO
Comments should be used to explain how the code works. Things that don't need to be explained are non-esoteric language features (for example you don't need to comment on what
imports do). In general you want your code to be as self-explanatory as possible, without the use of comments.You generally don't need comments like
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------that just separate two sections - well organized code (and judicious use of whitespace) should do that just fine.
Documentation should be used to explain what the code is intended to do. This is generally done with a module level docstring and then class/function/method level docstrings as appropriate.
PEP8
In general, unless there is a pressing reason not to (i.e. you're working in a larger code base that has it's own style, or you're doing an assignment for a class that requires a certain style, or you really don't like PEP8 styles), you should try to follow the PEP8 coding conventions. This includes things like naming:
- Variables and functions should be named using
snake_casing
- Classes should be named using
PascalCasing
- Constants should be named using
UPPER_SNAKE_CASING
It also includes spacing - for example you almost always want to use a single space to clearly separate operators from their arguments, items in a list, parameters to a function, etc.
This includes indentation - you generally want your comments to be at the same indentation as the thing they're commenting about.
Lastly, line-length. You generally want lines to be, at most, 79 characters long and your docstrings to be, at most, 72 characters long. Your text editor/IDE should have a way to set a ruler that shows you when you've gone too far.
Constants
You should define constants at the top of your file. For example,
BIG_OR_SMALL = ['bigger', 'smaller']Also avoid magic numbers - you have things like
while user_score < 3:which could be better defined this way
# Maps from the current level to the upper score limit
SCORE_LIMIT = {
1: 3,
2: 5
}
...
while user_score < SCORE_LIMIT[level]:You can also set constants as members of an
Enum, which is a convenient way to group related constants.from enum import Enum
...
GAME_MODES = Enum('GAME_MODES', 'BIGGER SMALLER')Limit the scope of
try blocksA
try block exists to do something you know might cause an error. You generally want to put as little as possible inside of that try block so you only catch an error from the specific line you think will cause ittry:
user_num = int(input("Which number is bigger:"))
except ValueError:
print("That is not an integer, please try again.")
else:
while user_num != a1 and user_num != a2:
user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
breakUse functions!
Right now you have a lot of repeated code - we can use functions to consolidate that. Additionally, a named function can make it much more clear what you're trying to do without the use of comments. Right now you have code like
a1 = random.randint(1, 10)
a2 = random.randint(1, 10)
while a1 == a2:
a2 = random.randint(1, 10)that could be more clearly represented as
def get_two_random_numbers(start, end):
first = random.randint(start, end)
second = random.randint(start, end)
while first == second:
second = random.randint(start, end)
return first, second
...
a1, a2 = get_two_random_numbers(1, 10)All together
Here is your full program, rewritten in a way I think makes sense. Not everything I've changed in here was explicitly mentioned in the review above, but I think it should all be self explanatory from the previous comments
```
import random
import sys
from enum import Enum
user_name=str(input("Please type in your name: "))
print('''Hello {0}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {0}, we are going to give you two numbers.'''
'Then you must choose which of these numbers you think is bigger or which '
'number is smaller.'
'''
Type this number in and if you are right you will get a point.
Get enough points and you can progress to level two!
'''.format(user_name))
# Maps from the current level to the upper score limit
USER_SCORE_LIMIT = {
1: 3,
2: 5
}
SCORE_RANGE = {
1: (1, 10),
2: (1, 100)
}
GAME_MODES = Enum('GAME_MODES', 'BIGGER SMALLER')
def get_two_random_numbers(start, end):
first = random.randint(start, end)
second = random.randint(start, end)
while first == second:
second = random.randint(start, end)
return first, second
def choose_game_mode():
return random.choice(list(GAME_MO
Code Snippets
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------BIG_OR_SMALL = ['bigger', 'smaller']while user_score < 3:# Maps from the current level to the upper score limit
SCORE_LIMIT = {
1: 3,
2: 5
}
...
while user_score < SCORE_LIMIT[level]:from enum import Enum
...
GAME_MODES = Enum('GAME_MODES', 'BIGGER SMALLER')Context
StackExchange Code Review Q#98983, answer score: 4
Revisions (0)
No revisions yet.