温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用户输入和while循环

发布时间:2020-07-26 23:31:38 来源:网络 阅读:156 作者:bigbeatwu 栏目:编程语言

1.函数input()的工作原理

message = input("Tell me something,I will repeat it back to you: ") #input()函数:让程序停止运行,等待用户输入一些文本
print(message)
name = input("Please enter your name: ")
print("Hello," + name + "!")
prompt = "If you tell us who you are,we can personalize the message you see." #创建多行字符串,+=:再附加
prompt += "\nWhat is your first name?"
name_a = input(prompt)
print("Hello "+ name_a + "!")
#求模运算符
number = input("Enter a number,and I will tell you if it's even or odd: ") #使用input()
number = int(number) #用户输入的数值是字符串表示的,转化为数值
if number % 2 == 0:
print("\n The number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
print("\n")

用户输入和while循环
2.使用while循环

num = 1
while num <=5:
print(num)
num+=1
用户输入和while循环

(2)#让用户选择何时退出

prompt = "\nTell me something,I will repeat it back to you."
prompt += "\nEnter 'quit' to end program. "
message = ""
while message != "quit": #message变量来提供判断
message = input(prompt) #input()都需要一个变量存储
if message != "quit": #打印前加个if条件再打印
print(message)
#使用标志
active = True #Ture:程序处于活跃状态
while active:
message = input(prompt)
if message == "quit": #用if语句判断程序状态
active = False
else:
print(message)
#使用break退出循环
while True:
message = input(prompt)
if message == "quit":
break
else:
print(message)
用户输入和while循环

(3)循环中使用continue

num = 0
while num <= 10:
num +=1**
if num % 2 == 0:
continue
#满足条件继续循环,不满足跳出**

print(num)                               **#不写在循环内**

number = 1
while number >3:
print(number)
用户输入和while循环

(4)#删除包含特定值的所有列表元素

pet = ["dog","dog","dog","cat","rabbit"]
print(pet)
while "dog" in pet:
pet.remove("dog")
print(pet)
用户输入和while循环

3.#使用用户输入来填充字典

responses = {} #创建空字典
active = True #循环状态
while active:
name = input("What is your name? " ) #变量做键
response = input("Where are you want to go? ") #变量做值
responses[name] = response #添加键-值
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == "no": #if判断状态
active = False
print("\n---poll Result---")
for name,response in responses.items(): #items():两个变量分别存储键-值
print(name + " would like to go " + response + ".")
用户输入和while循环

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI