Python学习之路day03——008用户输入input()方法

用户输入

1、input()函数(或方法)的工作原理

input()函数是,让程序暂停运行,等待用户输入数据(文本以及其他信息),然后根据内容进行下一步运行:

print('please type some words input the system:')

message = input()

print(message)

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

代码:

age = input("How old are you? ")
print(age)
if age >20:
print('I am a man !')

输入信息:

How old are you? 23
23

输出结果(报错):

if age >20:
TypeError: '>' not supported between instances of 'str' and 'int'

注意:数据类型错误 str和int不能相互比较大小,此处age是str类型,python会自动将我们输入的文本,转化为str

,所以当我们需要引用age的时候,必须要将age强转为int数据类型。

 正确的书写方式: 

# -*- coding: gb2312 -*-
age = input("How old are you? ")
print(age)
age = int(age)
if age >20:
print('I am a man !')

结果:

How old are you? 56
56
I am a man !

 

 

 

猜你喜欢

转载自www.cnblogs.com/jokerwang/p/9256965.html
今日推荐