I want to write a function that takes number between 1 and 7 as a parameter and prints out the corresponding day as a string.
For example, if the parameter is 1, your function should print out one
. If the parameter is 2, your function should print out two
, etc.
I wrote this program, but I am not getting anything as an output. I sure that I am using the if
and else
statements correctly
My program:
def string(x):
if x=="1":
word = "one"
else:
if x=="2":
word = "two"
else:
if x=="3":
word = "three"
else:
if x=="4":
word = "four"
else:
if x=="5":
word = "five"
else:
if x=="6":
word = "six"
else:
if x=="7":
word = "seven"
else:
word = "Try again"
return word
def main():
y = int(input("Please enter a number between 1 and 7: "))
z = string(y)
print(z)
main()
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()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments