Elif语句被跳过。

huangapple go评论69阅读模式
英文:

Elif statement skipped

问题

while True:
    top_of_range = input("输入一个1-10之间的数字: ")

    if top_of_range.isdigit():
        top_of_range = int(top_of_range)
        break

    elif top_of_range.isdigit() and int(top_of_range) <= 0:
        print("请输入大于0的数字。")
        continue
    
    else:
        print("请输入一个数字。")
        continue

如果我输入一个小于等于0的值,它会直接跳到"请输入一个数字。",期望它显示"请输入大于0的数字。"并回到输入。

英文:
while True:
    top_of_range = input(&quot;Type a number from 1-10: &quot;)

    if top_of_range.isdigit():
        top_of_range = int(top_of_range)
        break

    elif top_of_range.isdigit():
      int(top_of_range) &lt;= 0
      print(&quot;Please type a number larger than 0.&quot;)
      continue
    
    else:
        print(&quot;Please type a number.&quot;)
        continue

if I type a value <= 0 , It just bypasses to "Please type a number."

Expecting it to show "Please type a number larger than 0." and loop back to the input.

答案1

得分: 1

请记住,只有if/elif/else的一个分支实际上会被评估。您可能也希望尝试将输入转换为整数,并在需要时处理异常。

通过在输入不在范围内时引发ValueError,您可以同时处理这两种错误。

英文:

Keep in mind that only one branch of an if/elif/else can actually be evaluated. You may also wish to simply try to convert input to int, and handle the exception if needed.

By raising ValueError on the input not being in range, you can handle both errors at the same time.

def get_number_in_range(bot, top):
  while True:
    try:
      n = int(input(f&quot;Type a number from {bot}-{top}: &quot;))
      if n &lt; bot or n &gt; top: raise ValueError
      return n
    except ValueError:
      print(&quot;Please type a valid number.&quot;)

huangapple
  • 本文由 发表于 2023年7月3日 12:13:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定