python的语句结构——循环结构,if,else结构

if————else

第一种结构:
–if 条件:
结果

if True:
    print("哈哈")

第二种结构:

if 条件:
结果
else:
结果

if True:
    print("哈哈")
else:
    print("不开心")

第三种结构:

choice = ''
if choice == 'A':
    print('我请你吃饭')
elif choice == 'B':
	print('你请我吃饭')
elif choice == 'C':
	print('我们一起去吃饭')

第四种结构:

choice = ''
if choice == 'A':
    print('我请你吃饭')
elif choice == 'B':
	print('你请我吃饭')
elif choice == 'C':
	print('我们一起去吃饭')
else:
    print("都不去吃饭")

第五种结构:
if 条件:
if 条件:
结果
else:
结果
else:
结果

grade = int(input('请猜我的成绩:'))
if grade > 70:
	if grade > 80 :
		print('成绩不错哦')
	else:
		print('成绩这么好哦')
else:
	print("你得努力啦!")

while语句

while 条件:
结果

i = 1
s = 0
while i <= 10:
	s += i
	i+=1
print(s)

break,continue

break : 结束循环。
continue:结束本次循环,继续下一次循环。

while else

count = 1
while True:
    print(count)
    if count == 3: break
    count += 1
else:
    print('循环正常完毕')

循环嵌套

count = 1
flag = True
while flag:
    print(count)
    if count == 3:
        flag = False
    count += 1
else:
    print('循环正常完毕')

例子

求1-100的所有数的和

sum = 0
count = 1
while count < 101:
    sum = sum + count
    count += 1  # count = count + 1
print(sum)

求1-2+3-4+5 … 99的所有数的和

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

输出 1-100 内的所有奇数

count = 1
while count < 101:
    print(count)
    count += 2
count = 1
while count < 101:
    print(count)
    count += 2

用户登陆(三次机会重试)

username = 'OldBoy'
password = '123'
i = 0
while i < 3:
    name = input('请输入用户名:')
    pwd = input('请输入密码:')
    if name == username and pwd == password:
        print('登陆成功')
        break
    else:
        print('用户名或密码错误')
        i += 1

猜你喜欢

转载自blog.csdn.net/qq_38362416/article/details/83098248