I am trying to create a simple Python project. It's a minigame about guessing a number.

It's a game where the computer will pick a random number from 1 to 10.

  • The player needs to guess it correctly.
  • Every wrong attempt will give you a clue.
  • 3 clues and the player will lose.

I've built the code and it works just fine. Here's the code :

total = 0
guessme = 0

def GuessNum(guess):
    global total
    global guessme
    prime = [2, 3, 5, 7]

    if total == 0:
        randnum = random.randint(1,10)
        guessme = randnum

    total += 1

    if guess == guessme:
        print("You are correct!")
        guessme = 0
        total = 0
        if total == 1:
        if guessme % 2 == 0:
            print("The number is even")
            print("The number is odd")
        elif total == 2:
        if guessme > 5:
            print("The number is greater than 5")
            print("The number is smaller than 5")
        elif total == 3:
        if guessme in prime:
            print("The number is prime")
            print("The number is not a prime")
        guessme = 0
        total = 0
        print("You failed to guess the number.")

Are there ways to make this code much more efficient or shorter? I am still new at programming so I would love to learn new things.

  • \$\begingroup\$ How are you taking input from the user? Also since you are using a function try to use return instead of global variables. \$\endgroup\$
    – Roni Saiba
    Commented Dec 1, 2020 at 18:09
  • 1
    \$\begingroup\$ Printing The number is smaller than 5 when the number is 5 is, hm, tricky. \$\endgroup\$
    – greybeard
    Commented Dec 1, 2020 at 20:51

1 Answer 1


The code is fairly okay and readable. Since you highlighted performance, my review would not touch on some areas that are lacking.

Prefer random.random() to generate pseudorandom numbers

import timeit

test1 = '''
import random

test2= '''
import random
int(10 * random.random())

tt1 = timeit.repeat(stmt=test1, repeat=5, number=1)
print('randint time taken: ', min(tt1))

tt2 = timeit.repeat(stmt=test2, repeat=5, number=1)
print('random.random() time taken: ', min(tt2))

On running the above program, the following results were gotten. NOTE: The results might vary on your computer, but there is still some difference.

randint time taken = 2.1700000005546375e-06

random.random() time taken = 6.056000074750045e-06

Though the difference is insignificant, it might mean a lot when the range increases.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.