python学习之input与while:
1.函数input()
函数input()会暂停程序,等待用户输入文本,同时它接受一个参数,起到提示和说明的作用
message = input("Tell me something,and I will repeat it back to you!")
print(message)
2.使用input()获取的值
使用函数input()获取的值为str 类型 , 当你在输入int型需要比较时,则需要先将获取的值转换成int型在进行计算。
def addNum(a,b,c=5):
sum = a + b + c;
print(str(sum))
while True:
a = input("please input first num:")
b = input("please input second num:")
isInputThird = input('Are you input Third Num : y/n')
if isInputThird == 'y':
c = input('please input Third Num:')
else :
c = 0
addNum(int(a),int(b),int(c))
isContinue = input('Are you continue? y/n')
if isContinue == 'y':
continue
else:
break
运行结果:
3.求模运算符
求模运算符(%)将两个数相除并返回余数:
>>>4%3
1
>>>5%3
2
>>>6%3
0
4.while循环简介
for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止
current_num = 1
while current_num <= 5:
print(current_num)
current_num +=1
5.使用break退出循环
要立即退出循环 不在循环while下余下的代码,可使用break
6.使用continue 跳过没写操作
在循环中根据条件决定是否继续执行循环 ,他不会退出整个循环,而只是满足条件的情况下跳过本次循环,执行下次循环。
7.使用input来填充字典
responses = {}
polling_active = True
while polling_active:
name = input("\n what is you name?")
response = input("which mountain would you like to climb someday?")
responses[name] = response
repeat = input("would you like to let another person respond?(yes/no)")
if repeat == "no":
polling_active = False
print("\n----Poll Result ----")
for name,response in responses.items():
print(name+"would like to climb "+response +".")