一:函数input()的工作原理
1、input()示例
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋给一个变量,以便使用。input()接受一个参数--向用户显示的提醒或说明。
message = input("Input something:")
print(message)
# RESULT
'''
Input something:hello
hello
'''
2、使用int()来获取数值输入
当输入为数字时,实际Python还是会当做字符串即‘10’处理,如果只是打印没有任何问题,但是当做数字来使用时就会引发错误。
#!/bin/python3
num = input("Input num:")
print(num)
if (num > 10):
print("True")
else:
print("False")
# RESULT
'''
Input num:10
10
Traceback (most recent call last):
File "/home/zhaotj/work/python-script/list.py", line 5, in <module>
if (num > 10):
TypeError: '>' not supported between instances of 'str' and 'int'
'''
针对上面问题就引入了函数int()
num = input("Input num:")
print(num)
num = int(num)
if (num > 10):
print("True")
else:
print("False")
# RESULT
'''
Input num:10
10
False
'''
3、求模运算符
num = input("Input num:")
num = int(num)
if num % 2 == 0:
print("The number {num} is even")
else:
print("The number {num} is odd")
# RESULT
'''
Input num:3
The number {num} is odd
Input num:2
The number {num} is even
'''
二:while循环
#!/bin/python3
num = 0
while num <= 5:
print(num)
num += 1
if num == 3:
print("exit.\n")
break
num = 0
while num <= 10:
if num % 2 == 0:
num += 1
continue
print(num)
num += 1
# RESULT
'''
0
1
2
exit.
1
3
5
7
9
'''