在下面的示例程序中,我希望将用户输入作为映射到完整单词的单个字符:例如'':'小'。我不确定在哪里放。我想要得到的是:
~/Desktop$ python3 test.py
Do you want to hire a bike or a car (b, c): b
Small, medium or large (s, m, l): s
Which colour? Red or yellow (r, y): r
Do you want normal or turbo speed (n, t): t
You chose: bike
You chose: colour: red
You chose: speed: normal
You chose: size: small
以下是代码:
def hire_bike():
choices = {}
choices['type'] = 'bike'
choices['size'] = input('Small, medium or large (s, m, l): ')
choices['colour'] = input('Which colour? Red or yellow (r, y): ')
choices['speed'] = input('Do you want normal or turbo speed (n, t): ')
return choices
def hire_car():
choices = {}
choices['type'] = 'car'
choices['colour'] = input('Which colour? Black or white (b, w): ')
choices['speed'] = input('Do you want normal or turbo speed (n, t): ')
return choices
def menu():
hire = input('Do you want to hire a bike or a car (b, c): ')
if 'b' in hire:
return hire_bike()
elif 'c' in hire:
return hire_car()
x = menu()
for k, v in x.items():
print('You chose: {}'.format(v))
输出结果为:
~/Desktop$ python3 test.py
Do you want to hire a bike or a car (b, c): b
Small, medium or large (s, m, l): s
Which colour? Red or yellow (r, y): r
Do you want normal or turbo speed (n, t): t
You chose: s
You chose: r
You chose: bike
You chose: t
有没有一种标准的方法可以做这种事情?
答案 0 :(得分:2)
choices['colour'] = input('Which colour? Black or white (b, w): ')
您只是存储用户输入的单个字符,而不是相应的“完整”值。 ('l'
- > 'large'
)
# Mappings of user input to its corresponding values
sizes = {
's': 'small',
'm': 'medium',
'l': 'large',
}
colours = {
'r': 'red',
'y': 'yellow'
}
speeds = {
'n': 'normal',
't': 'turbo'
}
def hire_bike():
size = input('Small, medium or large (s, m, l): ').lower()
colour = input('Which colour? Red or yellow (r, y): ').lower()
speed = input('Do you want normal or turbo speed (n, t): ').lower()
return {
'type': 'bike',
'size': sizes.get(size), # or sizes.get(size, 'default size')
'colour': colours.get(colour), # or colours.get(colour, 'default colour')
'speed': speeds.get(speed) # or speeds.get(speed, 'default speed')
}
根据用户的输入,将相应的值设置为choices['size']
,choices['colour']
,choices['speed']
。
(对hire_car()
功能执行相同的操作)