首页 > 代码库 > Python 基础2

Python 基础2

while  语句的运用:

while 条件:
  代码块
break
  用于跳出循环
continue
  用于跳出本次循环继续下一次循环

简单的几个例子:

1. 10以内的所有整数的输出

n1 = 1
flag = True
while flag:
    print(n1)
    if n1 == 10:
        flag = False
    n1 = n1 + 1

2.break 用法

n1 = 1
while True:
    print(n1)
    if n1 == 10:
        break
    n1 = n1 + 1

# break用于跳出所有循环,并且break下面的代码将不在执行。

3.break与continue的比较

while True:
    print(123)
    break
    print(456)
# print(123)输出结果只是123


while True:
    print(123)
    continue
    print(456)
#输出结果一直是123重复输出

#continue 终止当前循环continue一下的循环不在执行,然后开始下一次循环

4.输出1到10不含7的数字

start = 0
while True:
    #start = start + 1
    start += 1
    if start == 7:
        continue
    print(n1)
    if start == 10:
        break

5.求1到100的和

sum = 0
start = 1
while True:
    sum = sum + start
    if start == 100:
        break
    start += 1
    
print(sum)
#print (sum) sum 千万不能加""

6.输出1-100内的所有奇数

start = 1
while start<101:
    temp = start % 2 
    if temp == 1:
        print(start)
    else:
        pass
    start += 1

7.求1-2+3-4+5...99de 所有数的和

start = 1
sum = 0
while start < 100:
    temp = start %2
    if temp == 1
        sum = sum + start
    else: 
        sum = sum - start
    start += 1
print(sum)

8.用户登录(3次机会重试)

i = 0
while i < 3:
    print(i) 
    use = input("username:")
    pwd = input("passname")
    if user == "acker"and pwd == "111":
        print("yes")
        break
    else:
        print("try again")
    i += 1
    

 

Python 基础2