-1

Alright I was trying to code a coin flipper and I was wondering if there was a way to print if the output is heads or tails, 1 being heads and 2 being tails, I'm just not sure how to do it:

import random

min = 1
max = 2
print("Flipping the coin")
print(random.randint(1, 2))
abhigyanj
  • 2,355
  • 2
  • 9
  • 29

4 Answers4

3

The idiomatic way would be to use random.choice(). That can be used on a 1. dict or a sequence like a 2. tuple (a list would also work), depending on how important is to you the number-to-text relationship (e.g. 1 -> Head).

  1. with dict():
import random

coin_outcome = {1: 'Head', 2: 'Tail'}
print("Flipping the coin")

coin_values = list(coin_outcomes.keys())
outcome = random.choice(coin_values)
print(coin_outcome[outcome])
  1. with tuple():
import random

coin_outcome = 'Head', 'Tail'
print("Flipping the coin")
outcome = random.choice(coin_outcome)
print(outcome)

You can rework it in a number of different ways that do avoid random.choice(), but this would mean hardcoding a number of assumptions.

For example, if you were to use random.randint() to get the key of the coin_outcome dictionary (as in 1.) you should make sure that the result of random.randint() is a valid key, and you cannot use say 10 and 20 without adding extra logic to handle this.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • Method 2 is the simple way to do this. – Nick Feb 22 '21 at 07:48
  • They are two different abstractions. It depends on what is valued more. Method 2 abstracts away the number information we do not really care about. Method 1 explicits the key/value relationship, which may be useful in a more rich context. – norok2 Feb 22 '21 at 07:50
  • 1
    Agreed, but for a coin toss it doesn't make any sense to select an integer and then convert that to a string if all you want to do is display it. – Nick Feb 22 '21 at 07:53
1

Use conditional statements if else as:

import random
mini = 1
maxi = 2
print("Flipping the coin")
randOut = random.randint(mini, maxi)
if randOut == 1:
    print("Heads")
else:
    print("Tails")
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
1

You need to use conditions to check the output. Heres a one liner code after importing random:

print("Flipping the coin\n"+("Heads" if random.choice([0, 1]) else "Tails"))

This is ternary expression.

or just select randomly between Heads and Tails:

print("Flipping the coin\n"+random.choice(["Tails", "Heads"]))
Nouman
  • 6,947
  • 7
  • 32
  • 60
1

You are close. However, you haven't set conditions to do print("Head") or print("Tail"). Here is my solution:

from random import randint

def flip_coin():
    coin_result = randint(1, 2)

    if coin_result == 1:
        return "Head"
    elif coin_result == 2:
        return "Tail"

result = flip_coin()
print(result)