What am I doing wrong in my coin flip code?

469 Views Asked by At

I am trying to write a program that flips a coin, and displays Heads or Tails accordingly. This is what I have:

    from random import random
    while True:

        for i in range (2):
            spin = i.random()
            if spin == 0:
                print ("Heads")
            else:
                print ("Tails")

but I keep getting the error:

Traceback (most recent call last):
  File "C:/Users/Yamnel/Desktop/Python Programs/coin flip.py", line 5, in     <module>
    spin = i.random()
AttributeError: 'int' object has no attribute 'random'
5

There are 5 best solutions below

1
On BEST ANSWER
import random

while True:
    result = random.randrange(2)
    if result == 0:
       print ("Heads")
    else:
       print ("Tails")
0
On

Use this

from random import randrange
while True:
        spin = randrange(0,2)
        if spin == 0:
            print ("Heads")
        else:
            print ("Tails")

Also how many times you want your code to run. This will never end. Ideally you will want your code to run once just to get heads or tails. I suggest to remove while from code. Also keep an eye on indentation if you remove while.

2
On

"int" is a basic type that doesn't have methods like random().

You have to use random.randrange(2)

For more information see:

https://docs.python.org/2/library/random.html (The Official Doc)

0
On

See the following snippet

from random import random
coin = ['Heads', 'Tails']
num_of_tosses = 10
for i in range (num_of_tosses):
    spin = randrange(0,2)
    print coin[spin]

I am using randrange to randomly select elements from 0 to 1. In other words, to select 0 or 1.

Then I am setting a list of choices, called coin, that is used for printing Tails or Heads.

0
On

Most of the solutions presented here focus on random.randrange(). You can also do this using random.choice(), which returns a random element from a non-empty sequence:

>>> from random import choice
>>> coin = 'Heads Tails'.split()
>>> FLIPS = 5
>>> for _ in range(FLIPS):
...   print(choice(coin))
...
Tails
Heads
Tails
Heads
Tails
>>>