【问题标题】:Beginner python "None" issue初学者python“无”问题
【发布时间】:2018-06-24 16:38:19
【问题描述】:

我刚开始使用 python,并且因为我开始了一个新的计算器项目,pyCharm 什么都没有。我不确定是什么导致了这个错误,如果我能在这里得到一些帮助,我将不胜感激。 (这只是我展示的主要功能)这是代码:

def main():
    run = True
    while run == True:
        if run == False:
        break
    try:
        operation = input(print("Would you like to *, -, + or /?"))

        if operation != "+" and operation != "-" and operation != "/" and operation != "*":
            print("invalid input.")
            go = input(print("Would you like to continue, yes or no?"))

        if go == "no":
            run = False

        else:
            continue

        else:
            num1 = int(input(print("What's your first number?")))

            num2 = int(input(print("What's your second number?")))

         if operation == "*":
            print(multi(num1, num2))

         if operation == "-":
            print(sub(num1, num2))

         if operation == "+":
               print(add(num1, num2))

         if operation == "/":
               print(div(num1, num2))

         go = input(print("Would you like to make another calculation, yes or no?"))
         if go == "no":
                run = False
                else:
                    continue

        except:
            print("invalid input.")
            go = input(print("Would you like to continue, yes or no?"))
            if go == "no":
                run = False
            else:
               continue

一个例子:

Would you like to *, -, + or /?
None/
What's your first number?
None3
What's your second number?
None4
0.75
Would you like to make another calculation, yes or no?
Noneno

Process finished with exit code 0

【问题讨论】:

  • 请修正第 2-4 行的缩进。这是错误的。另外,如果循环头中的run==True,下一行不能为False。
  • def multi(num1, num2): return num1 * num2 def add(num1, num2): return num1 + num2 def sub(num1, num2): return num1 - num2 def div(num1, num2 ): 返回 num1 / num2
  • print 函数在您的input 语句中返回None,这就是您在用户输入之前看到None 的原因。删除对print() 的调用,input 无论如何都会打印文本。

标签: python


【解决方案1】:

input 调用中删除print 语句:

input(print("What's your first number?")) -> input("What's your first number?\n")input("Your first number: ")

那个Noneprint函数的返回值,由input函数显示。

【讨论】:

  • 非常感谢您的帮助。
【解决方案2】:

输入的函数签名是input([prompt])。括号表示提示是可选的,但基本上input 期望您提供一个字符串以打印出来。相反,你给它一个print() 声明。打印语句的返回值为None,因此输入语句将其作为提示输出。

注意,使用except 语句而不指定错误类型也是不好的做法。如果不指定类型,except 将触发任何错误(例如,当我在添加 multi 之类的函数之前尝试运行您的代码时触发)。我想你想在这里except ValueError

【讨论】:

    【解决方案3】:

    尝试删除输入中的打印语句。
    而不是input(print("Would you like to continue, yes or no?")) , 试试
    input("Would you like to continue, yes or no?")
    我就是这样做的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2021-02-06
      • 1970-01-01
      • 2020-01-04
      • 2020-11-23
      • 2015-03-16
      • 2012-04-15
      相关资源
      最近更新 更多