Home > Blockchain >  Repeating a program using the For loop in python
Repeating a program using the For loop in python

Time:04-30

I wrote a small program to act as a slot machine of sorts. To get full points on this assignment i need to be able to have the program run, the user gets their 3 numbers, and are told if they get any matches. I need the program to be able to run again, ideally after the user inputs the letter 'y'.

import random 
random_num1 = str(random.randint(0,2))
random_num2 = str(random.randint(0,2))
random_num3 = str(random.randint(0,2))
print('Python Slot Machine')

for num in random_num1:
    print(random_num1, random_num2, random_num3)
    if random_num1 == random_num2 == random_num3:
        print('You matched 3!')
    elif random_num1 == random_num2 or random_num1 == random_num3 or 
    random_num2 == random_num3:
        print('You matched 2!')
    else:
        print('You lost')

I had the actual program working, I just need to learn how to repeat it.

CodePudding user response:

Your loop is just looping over the first random number, which is definitely not what you want. You need a "forever" loop, which exits when the user wants to stop. Note that you need to allocate the numbers INSIDE that loop. Also note that you don't need to convert to strings.

import random 
print('Python Slot Machine')

while True:
    random_num1 = random.randint(0,2)
    random_num2 = random.randint(0,2)
    random_num3 = random.randint(0,2)

    print(random_num1, random_num2, random_num3)
    if random_num1 == random_num2 == random_num3:
        print('You matched 3!')
    elif random_num1 == random_num2 or random_num1 == random_num3 or random_num2 == random_num3:
        print('You matched 2!')
    else:
        print('You lost')

    if input("Go again?  y/n: ") == "n":
        break
  • Related