首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >在 Python 中从键盘读取用户输入

在 Python 中从键盘读取用户输入

作者头像
一只大鸽子
发布2024-03-13 14:36:24
发布2024-03-13 14:36:24
5.2K0
举报

如何在 Python 中从键盘读取用户输入

原文《How to Read User Input From the Keyboard in Python》[1]

input 函数

使用input读取键盘输入

input是一个内置函数[2],将从输入中读取一行,并返回一个字符串(除了末尾的换行符)。

例1:使用Input读取用户姓名

代码语言:javascript
复制
name = input("你的名字:")
print(f"你好,{name}")

使用input读取特定类型的数据

input默认返回字符串,如果需要读取其他类型的数据,需要使用类型转换。

例2:读取用户年龄

代码语言:javascript
复制
age = input("你的年龄:")
print(type(age)) # <class 'str'>

age = int(input("你的年龄:"))
print(type(age)) # <class 'int'>

处理错误

如果用户输入的不是数字,int()将会抛出ValueError异常。

代码语言:javascript
复制
>>> age = int(input("你的年龄:"))
你的年龄:三十
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: '三十'

使用try-except处理错误可以使程序更健壮。

例3:用try-except处理用户输入错误

代码语言:javascript
复制
while True:
    try:
        age = int(input("你的年龄:"))
    except ValueError:
        print("请使用数字输入你的年龄,例如24")
    else:
        break

print(f"明年, 你将 {age + 1} 岁。")

从用户输入中读取多个值

有时用户需要输入多个值,可以使用split()方法将输入分割成多个值。 例4:从用户输入中读取多个值

代码语言:javascript
复制
user_colors = input("输入三种颜色,用,隔开: ")
# orange, purple, green
colors = [s.strip() for s in user_colors.split(",")]

print(f"颜色的列表为: {colors}")

getpass 模块

有时,程序需要隐藏用户的输入。例如,密码、API 密钥甚至电子邮件地址等输入。可用标准库模块getpass实现。

下面是一个验证用户邮箱的例子。 例5:使用getpass隐藏用户输入

代码语言:javascript
复制
import os
import getpass

def verify_email(email):
    allowed_emails = [
        email.strip() for email in os.getenv("ALLOWED_EMAILS").split(",")
    ]
    return email in allowed_emails

def main():
    email = getpass.getpass("输入邮箱地址:")
    if verify_email(email):
        print("有效的邮箱,通过。")
    else:
        print("无效的邮箱,拒绝。")

if __name__ == "__main__":
    main()

我们使用os.getenv获取环境变量ALLOWED_EMAILS,并使用getpass.getpass隐藏用户输入。

为了设置环境变量,Windows用户可以在命令行或powershell中使用$env:命令。powershell设置环境变量-知乎[3] 设置当前会话的环境变量:

代码语言:javascript
复制
$env:ALLOWED_EMAILS = 'info@example.com'

linux用户可以使用export命令。

代码语言:javascript
复制
export ALLOWED_EMAILS=info@example.com

然后执行程序,输入邮箱地址,如果邮箱地址在环境变量中,程序将返回Email is valid. You can proceed.否则返回Incorrect email. Access denied.

使用 PyInputPlus 自动执行用户输入评估

PyInputPlus包基于验证和重新提示用户输入而构建并增强 input() 。这是一个第三方包,可用pip安装。 python -m pip install pyinputplus

例6:使用PyInputPlus读取用户输入

代码语言:javascript
复制
import pyinputplus as pyip

age = pyip.inputInt(prompt="你的年龄:", min=0, max=120)
print(f"你的年龄是 {age}")

注:这个包最后更新时间是2020年10月11日。

例7:一个简单的交易程序

代码语言:javascript
复制
import pyinputplus as pyip

account_balance = 1000

print("欢迎来到 REALBank")
while True:
    print(f"\n你的余额为: ¥{account_balance}")
    transaction_type = pyip.inputChoice(["存钱", "取钱", "退出"])

    if transaction_type == "退出":
        break
    elif transaction_type == "存钱":
        deposit_amount = pyip.inputInt(
            prompt="输入金额 (最大 ¥10,000): ¥", min=0, max=10000
        )
        account_balance += deposit_amount
        print(f"存入 ¥{deposit_amount}.")
    elif transaction_type == "取钱":
        withdrawal_amount = pyip.inputInt(
            prompt="输入金额: ¥", min=0, max=account_balance
        )
        account_balance -= withdrawal_amount
        print(f"取出 ¥{withdrawal_amount}.")

print("\n感谢选择 REALBank。再见!")

总结

  • • 使用input函数读取用户输入
  • • 使用getpass模块隐藏用户输入
  • • 使用PyInputPlus包增强用户输入
引用链接

[1] 《How to Read User Input From the Keyboard in Python》: https://realpython.com/python-keyboard-input/#how-to-read-keyboard-input-in-python-with-input [2] 内置函数: https://docs.python.org/zh-cn/3/library/functions.html#input [3] powershell设置环境变量-知乎: https://zhuanlan.zhihu.com/p/677577008

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-03-11,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 如何在 Python 中从键盘读取用户输入
  • input 函数
    • 使用input读取键盘输入
    • 使用input读取特定类型的数据
    • 处理错误
    • 从用户输入中读取多个值
  • getpass 模块
  • 使用 PyInputPlus 自动执行用户输入评估
  • 总结
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档