1、使用while循环输入 1 2 3 4 5 6     8 9 10

第一次写成:

n = 1
while n<11:
    if n==7:
        pass
    else:
        print(n)

导致无限循环,所以应该加上n = n+1:

1 n = 1
2 while n<11:
3     if n==7:
4         pass
5     else:
6         print(n)
7     n = n+1

2、求1-100的所有数的和

刚开始写:

1 n = 1
2 s = 0
3 while n<101:
4     s = s+n
5     n = n+1
6     print(s)

结果显示很多行:

1 1
2 3
3 6
4 ....
5 4851
6 4950
7 5050

其实只要最终的结果5050,应该把print放循环外面:

1 n = 1
2 s = 0
3 while n<101:
4     s = s+n
5     n = n+1
6 print(s)

3、输出 1-100 内的所有奇数

刚开始题目都没看,就直接打:

1 n = 1
2 s = 0
3 while n<101:
4     if n%2==0:
5         pass
6     else:
7         s = s + n
8         n = n+1
9 print(s)

没有输出,其实题目意思只要输出所有奇数即可:

1 n = 1
2 while n<101:
3     if n%2==0:
4         pass
5     else:
6         print(n)
7         n = n+2

4、输出 1-100 内的所有偶数

以为很简单,直接打:

1 n = 1
2 while n<101:
3     if n%2!=0:
4         pass
5     else:
6         print(n)
7         n = n+2

没想到没有输出,然后改了一下:

1 n = 1
2 while n < 101:
3     if n % 2 == 0:
4         print(n)
5     else:
6         pass
7     n = n + 1

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

这个真的难倒我了,搞了好久不知道,我干脆先算奇数和,再求偶数和,然后一减,也能得到答案50,窃喜:

 1 n = 1
 2 s = 0
 3 y = 0
 4 while n < 100:
 5     if n % 2 == 0:
 6         s = s + n
 7     else:
 8         y = y + n
 9     n = n + 1
10 print(y-s)

看了视频答案,观摩了好久才明白:

 1 n = 1
 2 s = 0
 3 while n < 100:
 4     temp = n % 2
 5     if temp == 0:
 6         s = s - n
 7     else:
 8         s = s + n
 9     n = n + 1
10 print(s)

视频作者的意思是只要是偶数,都减去,奇数都相加,他的逻辑更好实现

看视频都很简单,自己做却一塌糊涂

12-18 12:48