python

python(8):用户输入

2022-03-30  本文已影响0人  Z_bioinfo

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python再将其存贮在一个变量中。

message = input('please input the password:')
print(message)

会出现以下界面


image.png

当我在方框中输入123456,敲击回车时


image.png

1.编写清晰的程序

name = input('please enter your name: ')
print('hello,' + name + '!')
please enter your name: xiaoming
hello,xiaoming!
#当提示超过一行时
name = 'please enter your name: '
name += '\nwhat is your first name?'
name = input(name)
print('hello,' + name + '!')
please enter your name: 
what is your first name?zhang
hello,zhang!

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

使用函数input()时,python将用户输入解读为字符串。

age = input('how old are you ')
how old are you 21
age
'21'#可见21是作为字符串表示的
#解决问题,函数int()将数字的字符串转为数值表示
age = int(age)
age
21
或者用eval函数
age = eval(input('how old are you '))
age
21

3.求模运算符:%,两数相除并返回余数

4%3
1
5%1
0
6%3
0
#可以利用这一点判断一个数是否是偶数
number = input('请输入一个数: ')
number = int(number)
if number % 2 == 0:
    print('这是偶数')
else:
    print('这是奇数')
请输入一个数: 5
这是奇数
上一篇 下一篇

猜你喜欢

热点阅读