iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
1
自我挑戰組

30天學python系列 第 3

[Day03] 分支結構 & 循環結構

分支結構

if 語句

if 和 else 就是專門用於建構分支結構,elif 和 else 中也可以再建構新的分支
文中有三個簡單的範例,因為有五個練習,所以我直接前往練習,選了當中的 3 題。

練習

練習1 - 英制單位與公制單位互換。

value = float(input('請輸入長度: '))
unit = input('請輸入單位: ')
if unit == 'in' or unit == '英寸':      # 如果輸入 in 或 英吋
    print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':    # 如果輸入 cm 或 厘米
    print('%f厘米 = %f英寸' % (value, value / 2.54))
else:                                   # 如果都不是以上的輸入
    print('請輸入有效的單位')

https://ithelp.ithome.com.tw/upload/images/20190918/20121116cHt3GJQb1t.png https://ithelp.ithome.com.tw/upload/images/20190918/20121116L90ZClYWTA.jpg

練習2 - 擲骰子決定做什麼。

from random import randint # 隨機整數值

face = randint(1 , 6) # 隨機1 ~ 6
if face == 1:
    result = '唱首歌'
elif face == 2:
    result = '跳個舞'
elif face == 3:
    result = '學狗叫'
elif face == 4:
    result = '做俯臥撑'
elif face == 5:
    result = '念繞口令'
else:
    result = '講冷笑話'
print(result)

https://ithelp.ithome.com.tw/upload/images/20190918/20121116pLCbjtxXBV.jpg

練習4 - 輸入三條邊長如果能構成三角形就計算周長和面積。

import math

a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
    print('周長: %f ' % (a + b + c))
    p = (a + b + c) / 2 
    area = math.sqrt(p * (p - a) * (p - b) * (p - c))
    print('面積: %f ' % (area))
else:
    print('不能構成三角形')

https://ithelp.ithome.com.tw/upload/images/20190918/20121116oo0010ljC7.jpg https://ithelp.ithome.com.tw/upload/images/20190918/201211166VXgE86KtM.jpg

循環結構

循環結構有兩種做法,一種是 for-in 循環,一種是 while 循環。

for-in 循環

用 for 循環求 1~100 和

sum = 0 
for x in range (101):
    sum += x
print(sum)

https://ithelp.ithome.com.tw/upload/images/20190918/20121116jyWJAUfsaR.jpg

  • range(101)可以產生一個 0 到 100 的整數序列。
  • range(1,100)可以產生一個 1 到 99 的整數序列。
  • range(1,100,2)可以產生一個 1 到 99 的奇數序列,其中的 2 是數值的增量。

用 for 循環求 1~100 的偶數和

sum = 0 
for x in range (2,101,2):
    sum += x
print(sum)

https://ithelp.ithome.com.tw/upload/images/20190918/20121116ns2dAszRmT.jpg

while 循環

如果不知道具體循環次數的循環結構。while 循環通過一個能夠產生或轉換出 bool 值的表達式來控制循環,表達式的值為 True 循環繼續,表達式的值為 False 循環結束。

猜數字遊戲

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('你的智商餘額明顯不足')

https://ithelp.ithome.com.tw/upload/images/20190918/20121116mkChUTGaMQ.jpg

練習

練習1 - 輸入一個數判斷是不是質數。

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)

https://ithelp.ithome.com.tw/upload/images/20190918/2012111689KuJqFX3o.jpg

練習2 - 輸入兩個正整數,計算最大公約數和最小公倍數。

x = int(input('x = '))
y = int(input('y = '))
if x > y:          # 計算兩個數的公因數的範圍為較小的數到1以內的數
    x, y = y, x    # 將較小的數設為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

https://ithelp.ithome.com.tw/upload/images/20190918/201211161iu2fp4tsF.jpg

練習3 - 印出三角形圖案。

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()

https://ithelp.ithome.com.tw/upload/images/20190918/20121116HGgmpBVweg.jpg

今天算是基礎程式的一個小段落了,明天會是 5 題的自行練習,將會用前幾天所學來寫。


上一篇
[Day02] 語言元素
下一篇
[Day04] 自我練習
系列文
30天學python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言