All you have to do in this case is remove the int()
call from the main()
. Your string()
function is expecting a string – if you send it an int
, it’ll never work. Additionally, you can use the elif
keyword:
def string(x):
if x=="1":
word = "one"
elif x=="2":
word = "two"
elif x=="3":
word = "three"
elif x=="4":
word = "four"
elif x=="5":
word = "five"
elif x=="6":
word = "six"
elif x=="7":
word = "seven"
else:
word = "Try again"
return word
def main():
y = input("Please enter a number between 1 and 7: ")
z = string(y)
print(z)
main()
Or you can use a data structure called a dictionary
:
def string(x):
if x not in ('1', '2', '3', '4', '5', '6', '7'):
return "Try again"
d = {'1':'one', '2':'two', '3':'three', '4':'four',
'5':'five', '6':'six', '7':'seven'}
return d.get(x)
def main():
print(string(input("Please enter a number between 1 and 7: ")))
main()
solved How to use IF or ELSE statements in Python? BTW, How is my username and profile picture?