Python - 输入一个str。并将其转换为数字。 (打印计算)

时间:2018-02-22 06:43:56

标签: python-3.x input

如何输入字母(a,b或c),然后将结果打印为int。(5 * 1)而不是str? (5 * a)。

number = int(input("Input a number: "))
letter = input("Input a latter: ")

a = 1
b = 5
c = 3

print(number * letter)

2 个答案:

答案 0 :(得分:0)

您可以在此处使用字典,如下所示:

代码:

number = int(input('Enter a number: '))
letter = input('Enter a letter: ')
dict = {'a':1,'b':5,'c':3}
print( number * dict[letter.lower()])

答案 1 :(得分:0)

你可以试试这个:

number = int(input('Input a number: '))
letter = input('Input a letter: ')

a = 1
b = 5
c = 3

letter = letter.lower()
if letter in 'abc':
    idx = 'abc'.index(letter)
    letter = [a, b, c][idx]

print(number * letter)

要获得更灵活的方式,您可以这样做:

number = int(input('Input a number: '))
letter = input('Input a letter: ')

a = 1
b = 5
c = 3
d = 4

letter = letter.lower()

# locals() returns a dict of all variables in the current scope.
v = locals().get(letter)
if v is None:
    print('"%s" is not an expected choice!' % letter)
else:
    print(number * v)