Coin Flip Game Basic Help

I am working on the coin flip game function on the basic requirements. When i try to run the code below I get an error saying that randint is not defined. But it is a function isn’t it? the same way we dont need to define print. Pls help. Also if there are any other problems or improvements to be made to achieve the basic requirements. This is the link to the question Computer Science Independent Project #1 – Coin Flip

print("Welcome, you are about to guess the outcome of a coin flip")
choice = ""

def coin_flip(choice):
    num = randint(1, 2)
    # if coin is heads or tails
    if num == 1:
    if num == 2:
    # if heads or tails is guessed
    if num == 1 and choice == "Heads":
        print("Heads! You guessed right.")
    elif num == 2 and choice == "Tails":
        print("Tails! You guessed right.")
        print("Sorry, that was the wrong guess.")

#x = input("Enter your guess: " + str(choice))


You’ll have to import randint from the random library if you want to use it. You might consider using random.choice instead. See for more information.

I’ve found that you do random.randint(1,2) instead of randint(1,2). Hope this helps!

I apologise if this is a silly question, but how do you import? When I used random.choice, it said random was not defined

This depends on how you’ve imported the function.

from random import randint -> You can use randint().
import random -> You must use random.randint().

Edit: I believe this answers your query as well, @bit9369036689.

1 Like

Do you just type in import random at the start of the code? I am not sure how import works

Edit: Yes, this has helped me solve the problem, thank you

Yes, import statements usually go at the beginning of your code. import itself imports an entire module while from, import as seen in my previous reply imports a specific function from a module.

You can also find the lesson on modules here and more on importing here.

Side note: it seems like you intended to ask the user for input in the game. You should use the input function for this.

1 Like