如何为命令设置多个输入:
while True:
option = input('What Units Are You Using? (Q to Quit) ').lower()
if option == ['millimeters' , 'mm']:
a = int(input('Enter Your number: '))
while True:
b = a / 10 # centimeters
c = a / 1000 # meters
print('Okay- Heres what we got:', b,'centimeters(cm) and', c,' meters (m)')
break
因此:如果选项== ['毫米','mm']:如何让它运行毫米和毫米? (Python 3.33) 感谢
答案 0 :(得分:2)
您可以使用in
运算符(检查成员是否存在),如此
if option in ['millimeters' , 'mm']:
现在,如果if
是option
或millimeters
,则会满足mm
条件。
<强>建议:强>
format
方法撰写字符串。所以,你改进的程序看起来像这样
while True:
option = input('What Units Are You Using? (Q to Quit) ').lower()
if option in ['millimeters' , 'mm']:
a = int(input('Enter Your number: '))
b, c = a / 10, a / 1000
print('Okay- Heres what we got: {} centimeters(cm) and {} meters (m)'.format(b, c))
答案 1 :(得分:0)
while True:
option = input('What Units Are You Using? (Q to Quit) ').lower()
if option == 'millimeters' or option == 'mm':
a = int(input('Enter Your number: '))
while True:
b = a / 10 # centimeters
c = a / 1000 # meters
print('Okay- Heres what we got:', b,'centimeters(cm) and', c,' meters (m)')
break
答案 2 :(得分:0)
这是一个扩展版本:
import sys
if sys.hexversion < 0x3000000:
inp = raw_input # Python 2.x
else:
inp = input # Python 3.x
class Unit:
def __init__(self, short_singular, short_plural, long_singular, long_plural, per_meter):
self.ss = short_singular
self.sp = short_plural
self.ls = long_singular
self.lp = long_plural
self.per_meter = per_meter
self.names = {short_singular, short_plural, long_singular, long_plural}
def match(self, name):
return name in self.names
def to_meters(self, amt):
return amt / self.per_meter
def from_meters(self, amt):
return amt * self.per_meter
def to_str(self, amt, sig=3, short=False):
if amt == 1.0:
s = self.ss if short else self.ls
else:
s = self.sp if short else self.lp
return "{{:0.{}f}} {{}}".format(sig).format(amt, s)
units = [
Unit('in', 'ins', 'inch', 'inches', 39.3701),
Unit('ft', 'ft', 'foot', 'feet', 3.28084),
Unit('yd', 'yds', 'yard', 'yards', 1.09361),
Unit('mi', 'mi', 'mile', 'miles', 0.000621371),
Unit('mm', 'mm', 'millimeter', 'millimeters', 1000.),
Unit('cm', 'cm', 'centimeter', 'centimeters', 100.),
Unit('m', 'm', 'meter', 'meters', 1.),
Unit('km', 'km', 'kilometer', 'kilometers', 0.001)
]
def get_unit(prompt):
while True:
name = inp(prompt).strip().lower()
for unit in units:
if unit.match(name):
return unit
print("I don't know that one.")
def get_float(prompt):
while True:
try:
return float(inp(prompt))
except ValueError:
pass
def main():
a = get_unit("Convert from what unit? ")
b = get_unit("To what unit? ")
amt = get_float("How many {}? ".format(a.lp))
res = b.from_meters(a.to_meters(amt))
print("The result is {}.".format(b.to_str(res)))
if __name__=="__main__":
main()
像
一样运行Convert from what unit? km
To what unit? in
How many kilometers? 4.3
The result is 169291.430 inches.