I want to convert a number into a letter, if the user enters .8, the program would output a B if the user inputs a .7, the program prints a C, I am not sure how to do it?
a = 0.9
b = 0.8
c = 0.7
d = 0.6
f = 0.5
number = float(raw_input('enter number: '))
i = 0
for i in (a, b ,c ,d, f):
if number == i:
print i
''' Dictionarys, not sure how to use them, would it work best for this purpose? '''
''' I am getting an error '''
'''{ a: '0.9' b: '0.8' c: '0.7' d :'0.6' f: '0.5'}'''
'''
File "<stdin>", line 1
{ a: '0.9' b: '0.8' c: '0.7' d :'0.6' f: '0.5'}
^
SyntaxError: invalid syntax
'''
You want to map from the numbers to the letters, so you want the numbers to be keys in the dictionary:
number = float(raw_input('enter number: '))
my_map = { 0.9: "a", 0.8:"b", 0.7: "c", 0.6:"d", 0.5:"e"}
print my_map[number]
Just because sometime looks like a number/float, doesn't always mean you need to convert it to one. In your case it's easy to use strings. (The handling of invalid input is a little simpler)
>>> D = {'0.9': 'a', '0.8': 'b', '0.7': 'c', '0.6': 'd', '0.5': 'f'}
>>> number = raw_input('enter number: ')
enter number: 0.8
>>> print D[number]
b
Aside. Comparing floats for equality can cause interesting bugs. In your case it would be ok, but you need to be careful if you were calculating a number, say by adding results together
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 0.1 * 9
False
you can use integer as a key ,also I recommend use Get() method of dictionary to get a default value if no such key exsits
The easiest way it is
number = float(raw_input('enter number: '))
d = {0.9:"a",0.8:"b",0.7:"c",0.6:"d",0.5:"f"}
print d.get(number,"other")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.