python的输入

输入

在python中可使用内置函数input()接收用户的键盘输入。

注意:从input接收的都是字符串类型。

 

先查看帮助

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

 

案例

用法

name= input('请输入名字:\n')
print("你输入的名字为:"+name)
--------执行脚本-------------------
E:\python>python test.py
请输入名字:
tz
你输入的名字为:tz

 

 案例2

将字符转换为ASCII码

#使用ord函数将字符转换成ASCII码
name=input('请输入要转换的字母或数字:')
print(name+'的ASCII码为:',ord(name))
-----------执行脚本-------------------
E:\python>python test.py
请输入要转换的字母或数字:a
a的ASCII码为: 97

 

案例3

%s为占位符,%d为数字占位符

''.format为字符串的格式化函数

#简单的捕鱼达人小游戏
print('''
****************
  捕鱼达人
****************
    ''')
username=input('请输入游戏名字:')
password=input('请输入密码:')
print('%s,请输入你的充值金额:' % username)
coins=int(input())
print('%s充值成功!当前游戏币为:%d' %(username,coins))

#简单的英雄联盟小游戏
print('''
****************
  英雄联盟
****************
    ''')
role = input('请输入角色:')
equipment = input('请输入拥有的装备:')
upgrade_equipment = input('请输入想购买的装备:')
pay = input('请输入付款金额:')
equipment = upgrade_equipment
print('{}拥有{}装备,购买此装备花了{}块钱'.format(role,equipment,pay))

 

案例4

根据输入的年份计算年龄

import datetime
year = input('请输入您的出生年份:')
nowyear = datetime.datetime.now().year
age = nowyear - int(year)
print('你目前的年龄为:'+str(age)+'')
---------------执行脚本------------------
E:\python>python test.py
请输入您的出生年份:1952
你目前的年龄为:68岁

 

学习来自:B站大学 P17-18

《python从入门到项目实践》明日科技 第三章

posted @ 2020-10-25 13:05  努力吧阿团  阅读(818)  评论(0编辑  收藏  举报