函数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
可以清晰的看出 ,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")
# Python资料源码自取君羊 708525271
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)
首先将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]
最后
# 兄弟们学习python ,有时候不知道怎么学,从哪里开始学 。掌握了基本的一些语法或者做了两个案例后 ,不知道下一步怎么走 ,不知道如何去学习更加高深的知识 。
# 那么对于这些大兄弟们 ,我准备了大量的免费视频教程 ,PDF电子书籍 ,以及源代码!直接在这个群 708525271 自取就好啦!
# 还会有大佬解答!
好了 ,今天的分享到这里差不多就结束了 ,最后给大家分享一套Python教程:
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集 、发布本站内容到任何网站 、书籍等各类媒体平台 。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理 。