【问题标题】:My "IF " and Elif Statements are not Working我的 \"IF \" 和 Elif 语句不起作用
【发布时间】:2022-11-03 07:49:49
【问题描述】:

所以 if 和 elif 语句不起作用

def weight_converter():
  print("Welcome to Weight Converter")
  operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram"))
   if operation == " 1":
     gram_one = int(input("Grams needed to convert to pound: "))
     print("You have", gram_one * 453.57,"pounds")
   elif operation == " 2":
     pound_one = int(inpu())
  
weight_converter()

所以我期待 if 语句运行,但是 gram_one 输入没有出现。请帮我解决这个问题。

【问题讨论】:

  • operation=int(whatever) 表示运算是整数。所以它不可能是字符串" 1"'operation == " 1""operation == " 2" 不可能是真的
  • 尝试if operation == 1 而不是if operation == " 1"。另外,inpu() 是什么?这看起来像一个错字。
  • 以下任何答案是否对您有用或帮助您解决问题?请mark it as acceptedgive it an upvote。它将允许社区中面临相同问题的其他人更轻松地找到他们的答案。

标签: python


【解决方案1】:

我认为你在正确的轨道上,只是需要调整一些事情:

  1. 您似乎遇到了缩进问题,缩进可以正确解决。
  2. elif 块中有一个错字,所以我只是做了一些调整来解决这个问题。
  3. 因为您使用整数作为输入,将其更改为 2 而不是“2”可以解决此问题。
  4. 添加了一个 else 块,以防输入不是 1 或 2。

    希望这有助于您朝着正确的方向前进。

    def weight_converter():
      print("Welcome to Weight Converter")
      operation = int(input(" 1. Gram to Pound 
     2. Pound into Gram"))
      if operation == 1:
        gram_one = int(input("Grams needed to convert to pound: "))
        print("You have", gram_one * 453.57,"pounds")
      elif operation == 2:
        pound_one = int(input())
      else:
          print("An error as occurred..")
    
    weight_converter()
    

【讨论】:

    【解决方案2】:

    您的代码 sn-p 应该类似于以下代码 sn-ps 之一:

    def weight_converter():
      print("Welcome to Weight Converter")
      operation = int(input(" 1. Gram to Pound 
     2. Pound into Gram"))
       if operation == 1:
         gram_one = int(input("Grams needed to convert to pound: "))
         print("You have", gram_one * 453.57,"pounds")
       elif operation == 2:
         pound_one = int(input())
      
    weight_converter()
    

    或者

    def weight_converter():
      print("Welcome to Weight Converter")
      operation = input(" 1. Gram to Pound 
     2. Pound into Gram")
       if operation == "1":
         gram_one = int(input("Grams needed to convert to pound: "))
         print("You have", gram_one * 453.57,"pounds")
       elif operation == "2":
         pound_one = int(inpu())
      
    weight_converter()
    

    在上面的两个代码中,只需输入 sn-ps1或者2通过键盘 if/elif 语句可以正常工作。

    【讨论】:

      猜你喜欢
      • 2017-02-10
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 2017-07-03
      • 1970-01-01
      • 2011-10-24
      相关资源
      最近更新 更多