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

Using If Else statements in addition to sets using Python

I have to create a fortune teller for school. I want the user to input a number between 1-9. But i also want to give an error message if they put in a different number. I’m using a set containing my numbers, but I can’t call it in my if statements.

fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! Choose a number from 1 to 9 and hit enter: ')
print()
if user_num == fortune_num:
    print(user_num)
else:
    print('Error')

>Solution :

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

Use the keyword in to check set membership, also cast input into int:

fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! 
\nChoose a number from 1 to 9 and hit enter: ')
print()
if int(user_num) in fortune_num: #this would throw an error if input is not int
    print(user_num)
else:
    print('Error')
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