网站文章更新,东莞今天最新消息新闻,黄埔做网站,三九集团如何进行网站建设文章目录 如何在 Python 中从键盘读取用户输入input 函数使用input读取键盘输入使用input读取特定类型的数据处理错误从用户输入中读取多个值 getpass 模块使用 PyInputPlus 自动执行用户输入评估总结 如何在 Python 中从键盘读取用户输入 原文《How to Read User Input From t… 文章目录 如何在 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 strage 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:breakprint(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 getpassdef verify_email(email):allowed_emails [email.strip() for email in os.getenv(ALLOWED_EMAILS).split(,)]return email in allowed_emailsdef 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 infoexample.comlinux用户可以使用export命令。
export ALLOWED_EMAILSinfoexample.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 pyipage pyip.inputInt(prompt你的年龄, min0, max120)
print(f你的年龄是 {age})注这个包最后更新时间是2020年10月11日。 例7:一个简单的交易程序
import pyinputplus as pyipaccount_balance 1000print(欢迎来到 REALBank)
while True:print(f\n你的余额为: {account_balance})transaction_type pyip.inputChoice([存钱, 取钱, 退出])if transaction_type 退出:breakelif transaction_type 存钱:deposit_amount pyip.inputInt(prompt输入金额 (最大 10,000): , min0, max10000)account_balance deposit_amountprint(f存入 {deposit_amount}.)elif transaction_type 取钱:withdrawal_amount pyip.inputInt(prompt输入金额: , min0, maxaccount_balance)account_balance - withdrawal_amountprint(f取出 {withdrawal_amount}.)print(\n感谢选择 REALBank。再见)总结
使用input函数读取用户输入使用getpass模块隐藏用户输入使用PyInputPlus包增强用户输入