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.")
-
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– 200_success2019年04月13日 19:49:53 +00:00Commented Apr 13, 2019 at 19:49
3 Answers 3
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]
It could be modified like this:
import random
result = random.choice(["heads", "tails"])
print(f"Coin flipped! It's {result}.")
Main changes:
Add two lines after
import
. See this post for further details about this convention.Use
random.choice
instead ofstr(random.randint(0, 1))
. This is just a demonstration of another method you could use. I don't thinkrandom.choice
is necessarily better, it depends on what you're about to do in the next part of your code.Rename the variable from
coin
toresult
. A variable name is better if it is more specific. Another option I could think of other thanresult
isside
.Use
f-strings
, which is a handy Python3 syntax.
-
\$\begingroup\$ Welcome to Code Review! Well done on pointing out how your suggestions should be improvements. \$\endgroup\$greybeard– greybeard2019年04月14日 16:44:06 +00:00Commented Apr 14, 2019 at 16:44
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 namecoin
could be confusing if this was part of something bigger. I would usecoin_flip_result
or something similar.
Some ideas for extending/changing the code:
- Use enums (see https://docs.python.org/3/library/enum.html) for the result of the coin flip (named e.g.
CoinSide
), which would allow you to completely skip the if statements and just have something like:
coin_flip_result = CoinSide(randint(0, 1))
print("Coin flipped! It's " + coin_flip_result.name)
- If you haven't already, try doing FizzBuzz (https://en.wikipedia.org/wiki/Fizz_buzz)
Congrats on writing your first bit of code!