【问题标题】:Why is Python code returning 'None' when there is no double print requests? [duplicate]为什么没有双重打印请求时 Python 代码返回“无”? [复制]
【发布时间】:2023-03-24 21:15:01
【问题描述】:

这是我在main() 中的程序的开始。第一个输入请求是在用户应该输入输入的空间中打印“无”。用户仍然可以输入输入,但我无法摆脱“无”。

我尝试修改while 语句末尾的 return 语句的位置,这不会影响任何事情(现在它刚刚被取出,但即使包含它仍然返回 None) .我不是要求它打印两次(据我所知)。

while True:
    start = input(str(print('Would you like to find out your USA weather forecast? Please enter YES or NO.\n')))
    if start.upper() == 'YES':
        choice()
    elif start.upper() == 'NO':
        print('*'*31)
        print('Thank you for joining us today!')
        print('*'*31)
        exit(0)
    else:
        print('Please enter a valid response.')
        break

【问题讨论】:

  • 您的意思是:start = input('Would you like to find out your USA weather ... ')?
  • print 返回None,您将其传递给input,它会将其打印为提示...
  • 另外,我看到'Would you like to find your USA Weather Forecast 结尾处缺少引号? .这是一个错误,因为文本框中的格式用于询问我错过的问题。在代码中,整个语句被封装了。
  • 我需要将输入转换为字符串,这就是我添加 str 的原因。哦,我现在看到了。我不需要打印声明。我不知道为什么我什至在后来要求输入的代码不包含它时添加了它。谢谢。
  • input 的返回值是一个字符串(Python 3),因此无需再次对该值调用str。

标签: python printing return nonetype


【解决方案1】:

你想要:

start = input('Would you like to find out your USA weather forecast? Please enter YES or NO.\n')

发生了什么:

要查看代码中发生了什么,请从最里面的函数调用 (print) 到最外面的 (input) 读取它。 print 函数调用通常会在屏幕上打印一些东西,但它不返回值,所以它的默认返回是 None。然后,您在该返回值上调用 str。 str(None) 是“无”。然后将该值传递给input,即input("None")。这就是您提示时显示的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2014-02-12
    • 2021-02-04
    相关资源
    最近更新 更多