5
\$\begingroup\$

I know this is the simplest code that you have probably ever seen but its the first thing I've ever made. Any ideas on how to improve it or add new functions to it?

from random import randint
coin = str(randint(0, 1))

if coin == "0":
    print("Coin flipped! It's tails.")
elif coin == "1":
    print("Coin flipped! It's heads.")
\$\endgroup\$
  • 8
    \$\begingroup\$ Please fix your indentation. One easy way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block. \$\endgroup\$ – 200_success Apr 13 at 19:49
6
\$\begingroup\$

Types

This was too long for a comment to prince:

Enums are bad in python except for very specific cases, while this may be one of them, I would generally recommend against Enums. Enums are not useful code, they don't make the code clearer. Python doesn't have a switch statement.

First learn the built-in types, a flip can be described with a Boolean (bool) [note: booleans are a subtype of ints]. If you have more options (like a dice roll), then use whole numbers (int). If you randomly choose a winner from a pool of players, use a set of strings (str).

If you need to map an input to an output, rather than a long if chain, use Dictionaries (dict):

result = {
    False: "It's tails.",
    True: "It's head."
}

choice = bool(random.randint(0, 1)) 
#     or bool(random.getrandbits(1))
#     or random.choice({True,False})

print(result[choice])

While it might seem ridiculous to use a dictionary in this case, it will make sense if you take a deck of card for example.

result = {
    1: "as",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten",
    11: "jack",
    12: "queen",
    13: "king"
}

# or 
"""
result = {
    1: "as",
    **{i: str(i) for i in range(2,11)}
    11: "jack",
    12: "queen",
    13: "king"
}
"""
colors = {"clubs", "diamonds", "spades", "hearts"}
your_card = bool(random.randint(0, 13))
ai_card = bool(random.randint(0, 13))

print(f"Your card is the {result[your_card]} of {random.choice(colors)}")
print(f"Your card is the {result[ai_card]} of {random.choice(colors)}")
print(f"The winner is {'you' if your_card > ai_card else 'ai'}")

Of course, in those cases, it isn't obvious to find the string if you have the number, if it is trivial to make a function that can do the conversion, make a function.

My top advice is Don't make long if chains and avoid enums until you know all built in types

°[note: code not tested]

\$\endgroup\$
9
\$\begingroup\$

It could be modified like this:

import random


result = random.choice(["heads", "tails"])
print(f"Coin flipped! It's {result}.")

Main changes:

  1. Add two lines after import. See this post for further details about this convention.

  2. Use random.choice instead of str(random.randint(0, 1)). This is just a demonstration of another method you could use. I don't think random.choice is necessarily better, it depends on what you're about to do in the next part of your code.

  3. Rename the variable from coin to result. A variable name is better if it is more specific. Another option I could think of other than result is side.

  4. Use f-strings, which is a handy Python3 syntax.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! Well done on pointing out how your suggestions should be improvements. \$\endgroup\$ – greybeard Apr 14 at 16:44
5
\$\begingroup\$

Assuming you've sorted out the indentation I would do a few things to the code as is:

  • Separate the import from the rest of the code, grouping stuff that belongs together is super useful for readability when it comes to more complicated code.
  • Think about whether you need to use str, does it add anything to the code? I'd avoid that and instead just use the int instead.
  • Think about the variable name coin. I'd say that the result of the coin flip is not the coin itself so the name coin could be confusing if this was part of something bigger. I would use coin_flip_result or something similar.

Some ideas for extending/changing the code:

coin_flip_result = CoinSide(randint(0, 1))
print("Coin flipped! It's " + coin_flip_result.name)

Congrats on writing your first bit of code!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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