迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中修复 input() 返回 None 的问题

作者:迹忆客 最近更新:2022/10/05 浏览次数:

input() 函数在将调用传递给 print() 函数时最常返回 None。 要解决这个问题,请确保将字符串传递给 input() 函数,而不是调用 print() 函数。

# ⛔️ BAD (passing print() call to input())

user_input = input(print('Enter your preferred language: '))

print(user_input)

# -------------------------------------------

# ✅ Good (passing a string to input())

user_input = input('Enter your preferred language: ')

print(user_input)

运行结果如下

python input返回 none

print() 函数打印一条消息并返回 None

result = print('hello')

print(result)  # 👉️ None

如果我们将对 print() 函数的调用传递给 input() 函数,它将返回 None

相反,请确保将字符串传递给 input() 函数。

user_input = input('Enter your preferred language: ')

print(user_input)

输入函数接受一个可选的提示参数并将其写入标准输出,而没有尾随的换行符。

然后该函数从输入中读取该行,将其转换为字符串并返回结果。

注意 input() 函数总是返回一个字符串,即使用户输入了一个数字。

我们可以使用 print() 函数在使用 input() 函数之前或之后打印一条消息,但不能在对 input() 函数的调用中。

print('This runs before')

user_input = input('Enter your preferred language: ')

print(user_input)

print('This runs after')

如果我们必须在输入消息中使用变量,请使用格式化的字符串文字。

variable = 'language'

user_input = input(f'Enter your preferred {variable}: ')

print(user_input)

格式化字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。

my_str = 'is subscribed:'
my_bool = True

result = f'{my_str} {my_bool}'
print(result)  # 👉️ is subscribed: True

确保将表达式包裹在花括号 - {expression} 中。

None 值的最常见来源是:

  1. 有一个不返回任何东西的函数(隐式返回 None )。
  2. 将变量显式设置为 None
  3. 将变量分配给调用不返回任何内容的内置函数的结果。
  4. 具有仅在满足特定条件时才返回值的函数。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便