ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

用户输入和while循环

2022-03-25 19:02:03  阅读:169  来源: 互联网

标签:prompt 用户 while 循环 print input message 输入


函数input()

函数input() 让程序暂停运行,等待用户输入的一些文本。

input函数可以接受一个参数,会显示在输出中,一般用来提示用户输入什么,当然也可以不提供,不过最好还是要的

message = input("Tell me something, and I will repeat it back to you:\n")
print(message)

 

用int() 获得数据输入

input得到的数据是字符串类型,如果直接把这个变量与数值进行比较就会报错,不信可以尝试一下

可以采用int()  来强制转换这个数值,从字符串类型转换为数值类型

age = int(input("How old are you?\n"))
if age >= 18:
    print("You are old enough to vote.")
else:
    print("You are too young to vote.")

 

 

while循环

while循环格式

while 条件表达式:

     语句块(注意要有跳出循环的操作或者表达式)

 

让用户选择何时退出

prompt = "Tell me somthing, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
print(prompt)
message = ''
while message != 'quit':
    message = input()
    if message != 'quit':
        print(message)

 

 

使用标志

很多时候需要使用很多的判断条件来决定是否继续循环 ,这时候就要用到标志(flag),

一般来说这个标志可以是很多类型,比如数值,当出现标志大于某一数值时跳出循环,

比如布尔型,当True时继续执行,否则跳出循环

prompt = "Tell me somthing, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
print(prompt)
flag = True
while flag:
    message = input()
    if message == 'quit':
        flag = False
    else:
        print(message)

 

使用break退出循环

这里的break与c语言作用类似,可以提前结束循环,

比如遍历中找到需要的值我们可以用break来跳出循环,无需继续执行循环体

prompt = "Tell me somthing, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
print(prompt)
while True:
    message = input()
    if message == 'quit':
        break
    else:
        print(message)

 

在循环中使用continue

遇到continue时当前循环的余下语句不再执行,跳到循环头进行判断是否要再执行当前循环

# 输出奇数
i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

 

使用循环时必须要有跳出循环的语句或使循环条件不满足的时候

这样才能使循环有限,不会死循环

 

使用while循环处理列表和字典

在列表之间移动元素

for循环是一个遍历列表的有效方式,但是在for循环中修改列表会使for循环不好跟踪列表的元素

unconfirmed_users = ['alice', 'brain', 'candace']  # 未验证用户
confirmed_users = []   #已经验证的用户
while unconfirmed_users:    #有元素就执行
     confirmed_users.append(unconfirmed_users.pop())
print(unconfirmed_users)
print(confirmed_users)

 

删除列表中的所有特定值元素

pets = ['cat', 'dog', 'cat', 'goldfish', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)

 

使用用户输出来填充字典

count = 0
list = {}
while True:
    if count == 3:
        break
    name = input("What's your name?\n")
    age = input("How old are you?\n")
    list[name] = age
    count += 1
print(list)

 

标签:prompt,用户,while,循环,print,input,message,输入
来源: https://www.cnblogs.com/wojiuyishui/p/16056203.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有