Reputation: 13
Here is the code that I wrote so far:
def Ordinal(check):
data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}
if check in dict.keys:
return dict.get(check)
else:
return""
def main():
Num=input("Enter a number (1-12) to get its ordinal: ")
print ("The ordinal is", Ordinal(Num))
main()
The program is suppose to get a number between 1 to 12 from the user and then print its ordinal. I am having trouble using the input and checking to see if it is a key and then returning its value as a print statement in the main function. The error is related to the if statement.
Upvotes: 1
Views: 197
Reputation: 1427
Your problem is with if check in data.keys:
because:
data.keys
is a method: <built-in method keys of dict object at 0x10b989280>
You should call the method data.keys()
which returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Or you can do:
def Ordinal(check):
data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}
if check in data:
return data.get(check)
else:
return""
def main():
Num=input("Enter a number (1-12) to get its ordinal: ")
print ("The ordinal is", Ordinal(Num))
main()
Or as @astrosyam pointed out, using data.get(int(check), "")
is a cleaner way.
Upvotes: 1
Reputation: 21619
Maybe something like this? Don't print the output if they input an invalid key.
data = {
1: "First", 2: "Second", 3: "Third", 4: "Fourth", 5: "Fifth",
6: "Sixth", 7: "Seventh", 8: "Eighth", 9: "Ninth", 10: "Tenth",
11: "Eleventh", 12: "Twelfth"}
def Ordinal(check):
return data[check]
def main():
Num = input("Enter a number (1-12) to get its ordinal: ")
try:
print ("The ordinal is {}".format(Ordinal(int(Num))))
except ValueError:
print("didnt enter a valid integer")
except KeyError:
print("Not number between 1-12")
main()
If using python 2.x use raw_input
instead of input
.
Upvotes: 0
Reputation: 1332
To add to Bryan Oakley's answer you can do the following:
def Ordinal(check):
data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}
if check in data:
return data.get(check)
else:
return""
def main():
Num=eval(input("Enter a number (1-12) to get its ordinal: ")) #notice eval here!
print ("The ordinal is", Ordinal(Num))
main()
Notice that I added the eval by the input line.
Upvotes: 0
Reputation: 867
Try this ...
def Ordinal(check):
data={1:"First", 2:"Second", 3:"Third", 4:"Fourth", 5:"Fifth", 6:"Sixth", 7:"Seventh", 8:"Eighth", 9:"Ninth", 10:"Tenth", 11:"Eleventh", 12:"Twelfth"}
return data.get(int(check), "")
def main():
Num=input("Enter a number (1-12) to get its ordinal: ")
print ("The ordinal is", Ordinal(Num))
main()
The if check is not necessary since dict.get can return a default value.
Upvotes: 3