【问题标题】:My unit checking variable isn't reading the input properly, when I put cm in as input the program sends the boolean to the else我的单位检查变量没有正确读取输入,当我将 cm 作为输入时,程序将布尔值发送到 else
【发布时间】:2013-10-07 02:09:45
【问题描述】:

当我在 uCheck 变量中输入 cm 时,程序会在 else 条件下打印字符串

uCheck=input(print('Unit?')) #<--I enter 'cm' here
if uCheck=='nm':
    Wave=Wave
if uCheck=='cm': #<--it seems to skip this boolean
    Wave=Wave*(10**7)
if uCheck=='mm':
    Wave=Wave*(10**6)
if uCheck=='m':
    Wave=Wave*(10**9)
else:
    print('Invalid Unit! Valid units are: nm, mm, cm, m.') #<-- and prints this
    Frequency()

【问题讨论】:

  • 你可以摆脱print -- input('Unit?') 应该可以正常工作... reference
  • 微米怎么了?我知道 mu 不在大多数键盘上,但 um 经常被接受。

标签: python boolean python-3.3 boolean-logic


【解决方案1】:

您的 if 语句是单独的。即使第一个是真的,你仍然会检查第二个、第三个和第四个,因为只有第一个是真的,else 块将被执行。

将它们更改为elif,您的代码应该可以工作:

uCheck = input('Unit? ')

if uCheck == 'nm':
    Wave = Wave
elif uCheck == 'cm':
    ...

另外,更好的方法是使用字典:

units = {
    'nm': 1,
    'mm': 10**6,
    'cm': 10**7,
    'm': 10**9
}

unit = input('Unit? ')

if unit in units:
    wave *= units[unit]
else:
    print('Invalid Unit! Valid units are: ' + ', '.join(units))
    frequency()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多