python-while循環的練習題


# !/use/bin/env python
# -*-conding:utf-8-*-

#author:shanshan

"""
寫代碼
a. 使用 while 循環實現輸出 1,2,3,4,5, 7,8,9, 11,12
b. 使用while 循環輸出100-50,從大到小,如1009998…,到50時再從0循環輸出到50,然后結束
c. 使用 while 循環實現輸出 1-100 內的所有奇數
d. 使用 while 循環實現輸出 1-100 內的所有偶數
e. 使用while循環實現輸出2-3+4-5+6…+100 的和
"""

#a. 使用 while 循環實現輸出 1,2,3,4,5, 7,8,9, 11,12
i = 0
while i <=13:
if i == 6 and i == 10:
break
else:
print(i)
i = i+1


#b. 使用while 循環輸出100-50,從大到小,如1009998…,到50時再從0循環輸出到50,然后結束
count = 100
list_100_to_small = []
list_50_to_small = []
while count>0:
if count>=50:
list_100_to_small.append(count)
else:
list_50_to_small.append(count)
#list_50_to_small.reverse()
count -=1
list_0_big = list_50_to_small[::-1]
list_100_to_small.extend(list_0_big)
print(list_100_to_small)

#c. 使用 while 循環實現輸出 1-100 內的所有奇數
count = 1
while count <= 100:
if count % 2 == 1:
print(count)
count +=1

#d. 使用 while 循環實現輸出 1-100 內的所有偶數
count = 1
while count <= 100:
if count % 2 == 0:
print(count)
count +=1

#e. 使用while循環實現輸出2-3+4-5+6…+100 的和
count = 2
sum = 0
while count <= 100:
if count % 2 == 1:
sum_count = -count
else:
sum_count = count
sum = sum_count+sum
count +=1
print(sum)


免責聲明!

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



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