Skip to main content
added 2154 characters in body
Source Link
Aviv Cohn
  • 321
  • 1
  • 7

Readability

Firstly, Python doesn't require parentheses ((..)) around conditionals. So you can just say:

Thirdly, logical separation of code into paragraphs greatly helps readability. A 'paragraph' should make a single 'point', and then you should have a blank line before the next paragraph.

Handling unwelcome scenarios

You should handle corner cases in your code.

Than you can safely use get_user_int anywhere in your code. You can pass into it a custom message.

Result

Combining everything I mentioned, here's a possible outcome:

# In this program, the user must try to guess a random number generated by the computer
from random import randint

def guess_game():
    replay = 1   
    # Replay allows a user to replay the game without having to call the function again. 
    # The values are: 1 = Replay, any other character = End
    while replay == 1:       
        lives = get_user_int("How many lives would you like? ")
        max_value = get_user_int("Please choose the largest number that can be generated: ")
        rand_num = randint(0, max_value)
        num_of_guesses = 1  #keeps track of the number of guesses made by the user
        
        while num_of_guesses <= lives:
            guess = get_user_int("Please enter your guess: ")
            if guess == rand_num:
                print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
                break
            else:
                print("Unlucky, that guess was incorrect. You have", (lives-num_of_guesses), "lives remaining.\n")
            num_of_guesses += 1
            
        if num_of_guesses > lives:
            print("You have run out of guesses. The correct answer was:", rand_num)
            
        replay = int( input("\nWould you like to play again? Enter 1 for yes, any other character for no: ") )
        if replay != 1:
            print("Thank you for playing. See you next time")


def get_user_int(message='Enter a number: '):
    while True:
        try:
            return int(input(message))
        except ValueError:
            print('Enter a valid number.')
        
            

guess_game()

Firstly, Python doesn't require parentheses ((..)) around conditionals. So you can just say:

Thirdly, you should handle corner cases in your code.

Than you can safely use get_user_int anywhere in your code. You can pass into it a custom message.

Readability

Firstly, Python doesn't require parentheses ((..)) around conditionals. So you can just say:

Thirdly, logical separation of code into paragraphs greatly helps readability. A 'paragraph' should make a single 'point', and then you should have a blank line before the next paragraph.

Handling unwelcome scenarios

You should handle corner cases in your code.

Than you can safely use get_user_int anywhere in your code. You can pass into it a custom message.

Result

Combining everything I mentioned, here's a possible outcome:

# In this program, the user must try to guess a random number generated by the computer
from random import randint

def guess_game():
    replay = 1   
    # Replay allows a user to replay the game without having to call the function again. 
    # The values are: 1 = Replay, any other character = End
    while replay == 1:       
        lives = get_user_int("How many lives would you like? ")
        max_value = get_user_int("Please choose the largest number that can be generated: ")
        rand_num = randint(0, max_value)
        num_of_guesses = 1  #keeps track of the number of guesses made by the user
        
        while num_of_guesses <= lives:
            guess = get_user_int("Please enter your guess: ")
            if guess == rand_num:
                print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
                break
            else:
                print("Unlucky, that guess was incorrect. You have", (lives-num_of_guesses), "lives remaining.\n")
            num_of_guesses += 1
            
        if num_of_guesses > lives:
            print("You have run out of guesses. The correct answer was:", rand_num)
            
        replay = int( input("\nWould you like to play again? Enter 1 for yes, any other character for no: ") )
        if replay != 1:
            print("Thank you for playing. See you next time")


def get_user_int(message='Enter a number: '):
    while True:
        try:
            return int(input(message))
        except ValueError:
            print('Enter a valid number.')
        
            

guess_game()
Source Link
Aviv Cohn
  • 321
  • 1
  • 7

Welcome to Python :)

Firstly, Python doesn't require parentheses ((..)) around conditionals. So you can just say:

while replay == 1:

Secondly, too many comments make the code look messy and the reader learns to ignore them. Avoid commenting obvious code, for example:

random = randint(0, max_value)  #Generates a random int between 0 and max_value

The comment is unnecessary. The code is self-explanatory enough, and if the reader doesn't know what randint does, it's time he/she learns it by themselves anyway. Assume the reader knows the language.

Thirdly, you should handle corner cases in your code.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." Martin Fowler

For example, a possible corner case in your program is invalid user input. What happens when the user types 'bla' as a guessed number? A ValueError is raised and crashes your program. You can handle these situations using one of two approaches.

Preferable approach:

try:
    number = int(input())
except ValueError:
    print('Enter a valid integer.')
else:
    # ... rest of the code. runs if the try block succeeded.

Less preferable:

number = input()
if not isinstance(number, int):
    print('Enter a valid integer.')
else:
    # ... rest of the code

Even better, this could be put into a loop to allow the user to retry. It can even be made into a handy function!

def get_user_int(message='Type a number: '):
    while True:
        try:
            print(message)
            return int(input())  # breaks out of the loop
        except ValueError:
            print('Enter a valid integer.')

Than you can safely use get_user_int anywhere in your code. You can pass into it a custom message.

Good luck :)