I was given a task to write a program in a pretty basic python style. The program is supposed to ask the user whether they want to 1. Flip a coin, or 2. Pick a card.
Then uses an IF to check what the user picked. If it was one, it's supposed to randomly generate heads or tails and print what it got.
If the choice was 2, it asks the user to choose a suit, then generates a number between 1 and 13 (ace to king) and prints 'You picked [value] of [suit]'
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a coice :'))
if choice == 1:
Hort = ''
HorT == random.randint(0,1)
if HorT == "0":
print('You got Heads')
elif HorT == "1":
print('You got Tails')
elif choice == 2:
print()
print('1. Hearts')
print('2. Clubs')
print('3. Diamonds')
print('4. Spades')
print()
suitno = ''
suitno ==int(input('Choose a suit'))
if suitno == "1":
suit == "Hearts"
elif suitno == '2':
suit == 'Clubs'
elif suitno == '3':
suit == 'Diamonds'
elif suitno == '4':
suit == 'Spades'
value = ''
value == random.randint(1,13)
print()
print('You picked', value, 'of', suit)
as you can see, it's basic but I was asked to follow the pseudo-code as closely as I could. It stops right at the beginning. I enter then number for the choice, and it just ends.
EDIT: I have amended the code to show what I have changed.
Common mistakes:
==
used for comparison and not for assignment e.g 4 == 4
is True
int
type will never be equal to string e.g 4 == '4'
is False
. This is the reason why your if
statements didn't execute.input()
.else
if you have elif
.Dirty, but complete fix:
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a coice: '))
if choice == 1:
HorT = random.randint(0,1)
if HorT == 0:
print('You got Heads')
else:
print('You got Tails')
elif choice == 2:
print()
print('1. Hearts')
print('2. Clubs')
print('3. Diamonds')
print('4. Spades')
print()
suitno = int(input('Choose a suit: '))
if suitno == 1:
suit = "Hearts"
elif suitno == 2:
suit = 'Clubs'
elif suitno == 3:
suit = 'Diamonds'
else:
suit = 'Spades'
value = random.randint(1, 13)
print()
print('You picked', value, 'of', suit)
It could be written more concisely, but it is pretty basic python style
program :)
@Two-Bit Alchemist - @vaultah version:
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a choice: '))
if choice == 1:
outcomes = ('heads', 'tails')
print('You got {}.'.format(random.choice(outcomes)))
else:
suits = ('Hearts', 'Clubs', 'Diamonds', 'Spades')
print()
for index, element in enumerate(suits, start=1):
print('{}. {}'.format(index, element))
suitno = int(input('Choose a suit: '))
value = random.randint(1, 13)
print('\nYou picked', value, 'of', suits[suitno-1])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments