Python教程:如何在Python中实现键盘输入操作

文章目录

  • 如何在 Python 中从键盘读取用户输入
  • input 函数
  • 使用input读取键盘输入
  • 使用input读取特定类型的数据
  • 处理错误
  • 从用户输入中读取多个值
  • getpass 模块
  • 使用 PyInputPlus 自动执行用户输入评估
  • 总结
  • 如何在 Python 中从键盘读取用户输入

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

    input 函数

    使用input读取键盘输入

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

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

    name = input("你的名字:")
    print(f"你好,{name}")
    

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

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

    例2:读取用户年龄

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

    处理错误

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

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

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

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

    while True:
        try:
            age = int(input("你的年龄:"))
        except ValueError:
            print("请使用数字输入你的年龄,例如24")
        else:
            break
    
    print(f"明年, 你将 {age + 1} 岁。")
    

    从用户输入中读取多个值

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

    user_colors = input("输入三种颜色,用,隔开: ")
    # orange, purple, green
    colors = [s.strip() for s in user_colors.split(",")]
    
    print(f"颜色的列表为: {colors}")
    

    getpass 模块

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

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

    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设置环境变量-知乎
    设置当前会话的环境变量:

    $env:ALLOWED_EMAILS = 'info@example.com'
    

    linux用户可以使用export命令。

    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读取用户输入

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

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

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

    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包增强用户输入
  • 作者:一只大鸽子

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python教程:如何在Python中实现键盘输入操作

    发表回复