Python基础-7-用户输入和while循环

一:函数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
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值