Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Repeating a program using the For loop in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading