8用户输入和while循环——学习笔记

函数input()的工作原理

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其赋值给一个变量,以方便继续使用。
例如我们尝试让用户输入一些东西

a = input("请输入一个数")
print(a)
#运行结果
请输入一个数

这时我们就可以根据要求输入数值
函数input()接受一个参数——要向用户显示的提示或说明,让用户知道该怎么做。

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

使用函数input()时,python将用户输入解读为字符串。
下列将演示用户输入某编号。

a = int(input("请输入编号"))
print(a)
#运行结果
请输入编号

除了int的数据类型,我们还可以根据需要从而输入不同的数据类型。
同时加之运算符的使用,可以满足我们更多的需求。

while循环简介

for循环用于针对集合中的每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不满足为止。
下列我们简单的来用while循环数数。

a = 1
while a<=5:
    print(a)
    a+=1
#运行结果
1
2
3
4
5

可以清晰的看出,while当满足他的循环条件时,会停止运行!
根据上述我们所学习到的知识我们可以尝试着让用户选择何时退出程序!

tellme = "tell me something about you,and i will repeat it back toyou"
tellme == "if you have anything to say,please continue!\nif you have anything to say,please input quit"
message = " "
while message !="quit":
    message = input(tellme)
    print(message)
#运行结果
tell me something about you,and i will repeat it back to youi
i
tell me something about you,and i will repeat it back to youlove
love
tell me something about you,and i will repeat it back to youyou
you
tell me something about you,and i will repeat it back to youquit
quit

进程已结束,退出代码0

使用break退出循环

想立即退出循环,不在运行循环中的余下代码,也不管条件测试的结果如何,直接退出循环,就可以用到break语句。控制程序流程,可以控制那些代码可以执行,哪些代码不可以执行。
请欣赏以下代码:

tellme = "\ntell me something about you,and i will repeat it back to you"
tellme += "\nif you have anything to say,please continue!\nif you have anything to say,please input quit\t"
while True:
    yousay = input(tellme)
    if yousay == "quit":
        break
    else:
        print(f"thank you")
#运行结果
tell me something about you,and i will repeat it back to you
if you have anything to say,please continue!
if you have anything to say,please input quit	i love you
thank you

tell me something about you,and i will repeat it back to you
if you have anything to say,please continue!
if you have anything to say,please input quit	quit

进程已结束,退出代码0

在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环。可以使用continue语句,它不像break语句不在执行余下2代码·并退出整个循环。
例如我们打印从1到10但是只打印其中的奇数的循环。

a = 0
while a < 10:
    a += 1
    if a%2 == 0:
        continue
    print(a)
#运行结果
1
3
5
7
9

首先将a设置为0,python进入循环while后,以步长为1增加,接下来,if语句检查a与2求模运算结果。如可以被整除,就执行continue语句,忽略余下代码,并返回开头。反之,打印

避免无限循环

每一个while语句的必须要有其结束的条件,否则它将永远的循环下去!

删除为特定值的所有元素

在我们之前学习中使用函数remove()函数用来删除列表中的特定值。
这之所以可行,是因为要删除的值只在列表中出现一次。
如果我们要删除列表中的所有数值4那该怎么办呢?

a = [4,596,42,59,44,36,4,12,234,59]
print(a)
while 4 in a:
    a.remove(4)
print(a)
#运行结果
[4, 596, 42, 59, 44, 36, 4, 12, 234, 59]
[596, 42, 59, 44, 36, 12, 234, 59]

删除的是数值4,并不是包含4的所有数值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值