Reputation: 35
I was searching the web about finding factors and saw the one below I was confused about it and wanted some help I don't know what it means
This is for a project that we are making which is to make a game to find factors in which users have to input a number and the program will show the factors I've tried putting
if ValueError:
print("Sorry, I didn't understand that.")
but it doesn't work, I wanted the program to say "Sorry, I didn't understand that." if the user typed a letter or special character
how do I loop it too if the user typed a letter or special character
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("Enter a number: "))
print_factors(num)
the program works but I can't seem to add loops and the value error thing on the top
Upvotes: 1
Views: 31
Reputation: 61
You can use try catch block, and catch the valueError exception. Like below
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
try:
num = int(input("Enter a number: "))
print_factors(num)
except ValueError:
print("Sorry, I didn't understand that.");
Upvotes: 1