《Python编程从入门到实践》记录之input()函数

目录

1、input()函数原理

 2、将输入存储在变量作为input函数的参数

 3、使用int()来获取数值输入

4、在Python2.7中获取输入


1、input()函数原理

函数input() 让程序暂停运行, 等待用户输入一些文本,即默认输入为字符串

函数input() 接受一个参数: 即要向用户显示的提示或说明, 让用户知道该如何做。


下边为input()函数简单的例子:

# 将输入存储在变量message中
message = input("Tell me something, and I will repeat it back to you: ")
print(message)  # 输出变量

运行结果:

# 冒号之前是input函数的提示语,冒号之后是作为input函数的输入,存储在变量message中
Tell me something, and I will repeat it back to you: Hi! What about you? 
Hi! What about you?  # print结果

 2、将输入存储在变量作为input函数的参数

有的时候,可能提示语太多,我们可以将提示语放在一个变量中,作为input函数的参数。


简单例子:

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "  # 这里使用换行符,使得提示语可以多行显示

name = input(prompt)                     # prompt一个变量作为input函数的参数
print("\nHello, " + name + "!")

运行结果:

If you tell us who you are, we can personalize the messages you see.
What is your first name? David   # 提示语和输入(David为输入)

Hello, David!   # 输出结果

 3、使用int()来获取数值输入

由于input函数将用户输入解读为字符串。所以,如果在使用中,输入的是数字,后续程序中将作为数值使用,则需要用int()将数字的字符串表示转换为数值表示。


下面的程序, 判断一个人是否满足坐过山车的身高要求:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
height = input("How tall are you, in inches? ")
height = int(height)   # 将字符串表示转换为数值表示
if height >= 36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")

运行结果:

How tall are you, in inches? 18  # 提示语输入

You'll be able to ride when you're a little older.  # 输出结果

4、在Python2.7中获取输入

如果你使用的是Python2.7版本,应使用函数raw_input()来提示用户输入,同样也是讲输入解读为字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值