Python基礎題 - 1


1、使用while循環輸入 1 2 3 4 5 6     8 9 10

1 count = 0
2 while count <= 9:
3     count += 1
4     if count == 7:continue
5     print(count)
View Code

 或:

 1 # 把7換成空格
 2 count = 0
 3 while count < 10:
 4     count += 1
 5     if count == 7:
 6         print(' ')
 7     else:
 8         print(count)
 9 # 不輸入空格
10 count = 0
11 while count < 10:
12     count += 1
13     if count == 7:continue
14     print(count)
15 # 用pass
16 count = 0
17 while count <= 9:
18     count += 1
19     if count == 7:
20         pass              #直接跳過
21     else:
22         print(count)
View Code

 

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

1 count = 0
2 sum = 0
3 while count < 100:
4     count += 1
5     sum = sum + count
6 print(sum)
View Code

 

3、輸出 1-100 內的所有奇數

1 count = 0
2 while count < 100:
3     count += 1
4     if count % 2 == 0:continue
5     print(count)
View Code

 或:

# 第一種方法
count = 1
while count < 101:
    print(count)
    count += 2
# 第二種方法
count = 1
while count < 101:
    if count % 2 == 1:
        print(count)
    count += 1
View Code

 

4、輸出 1-100 內的所有偶數

1 count = 0
2 while count < 100:
3     count += 1
4     if count % 2 == 1:continue
5     print(count)
View Code

 

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

1 power = 1
2 count = 0
3 sum = 0
4 while count < 99:
5     count += 1
6     power += 1
7     sum = sum + count*((-1)**power)
8 print(sum)
View Code

 或:

1 count = 1
2 sum = 0
3 while count < 100:
4     if count % 2 == 0:
5         sum -= count
6     else:
7         sum += count
8     count += 1
9 print(sum)
View Code

 

6、用戶登陸(三次機會重試)

 1 user_name = 'admin'
 2 password = 'admin'
 3 count = 0
 4 while count < 3:
 5     count += 1
 6     name = input ('請輸入用戶名:')
 7     if name == user_name:
 8         pw = input('請輸入密碼:')
 9         if pw == password:
10             print('登陸成功')
11             break
12         else :print('密碼錯誤!')
13         if count == 3:print('登陸超過三次!請明天重試。')
14     else :
15         print('用戶名不存在!')
16         if count == 3 :print('登陸超過三次!請明天重試。')
View Code

 或:

1 i = 0
2 while i <3:
3     username = input('請輸入賬號:')
4     password = input('請輸入密碼:')
5     if username == 'admin' and password == 'admin':
6         print('登陸成功')
7     else:
8         print('登錄失敗,請重新登錄')
9     i += 1
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM