Python 100天-從新手到大師學習筆記Day04:循環結構

For迴圈

知道要重複程式幾次時使用
sum = 0
for x in range(101):
sum += x
print(sum)
#range(101)產生0到100的的數列#range(1, 100)產生0到99的的數列#range(1, 100, 2)產生1到99的奇數數列,2是每次增加2
使用每次+2的方法sum = 0
for x in range(2, 101, 2):
sum += x
print(sum)
使用分支結構sum = 0
for x in range(1, 101):
if x % 2 == 0:
sum += x
print(sum)
from math import sqrt

num = int(input('請輸入一個正整數: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print('%d是質數' % num)
else:
print('%d不是質數' % num)

While迴圈

不知道要重複程式幾次時使用
import random

answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = int(input('请输入: '))
if number < answer:
print('大一点')
elif number > answer:
print('小一点')
else:
print('恭喜你猜对了!')
break #終止程式於該行
print('你总共猜了%d次' % counter)
if counter > 7:
print('你的智商余额明显不足')
for i in range(1, 10):
for j in range(1, i + 1):
print('%d*%d=%d' % (i, j, i * j), end='\t')
print()
x = int(input('x = '))
y = int(input('y = '))
if x > y:
x, y = y, x
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print('%d和%d的最大公約數是%d' % (x, y, factor))
print('%d和%d的最小公倍數是%d' % (x, y, x * y // factor))
break
row = int(input('請輸入行數: '))
for i in range(row):
for _ in range(i + 1):
print('*', end='')
print()


for i in range(row):
for j in range(row):
if j < row - i - 1:
print(' ', end='')
else:
print('*', end='')
print()

for i in range(row):
for _ in range(row - i - 1):
print(' ', end='')
for _ in range(2 * i + 1):
print('*', end='')
print()

Written by

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store