# random,隨機。先學四種款基本方法。
# (1)取隨機的整數 .randint()
import random # 先設置導入random模組
print(random.randint(1, 10)) # 使用.randint(1, 10),隨機印出1-10之間的整數
print(random.random()) # 使用.random(),隨機印出0-1之間的浮點數
# (3)在列表中隨機選取一個元素 .choice()
options = ['老虎', '雞', '蟲', '棒'] # 先設一個列表 list []
ran_option = random.choice(options) # 使用.choice(options)
print('電腦出的是:', ran_option)
# (4)把列表打散 .shuffle()
numbers = ['1', '4', '5', '45', '777', '34'] # 先設置一個列表集合
random.shuffle(numbers) # 使用.shuffle(numbers) 打散順序
print(numbers)
-
# random 練習進階
# 剪刀石頭布 rock-paper-scissors/RPS,猜出勝負就停止
import random # 先設置導入random模組
RPS = ['剪刀', '石頭', '布'] # 先設一個列表 list []
while True: # while迴圈使用,重複直到分出勝負
ran_RPS = random.choice(RPS) # 使用.choice()
throwing = input(f' {RPS} ,請出拳:') # 讓使用者出拳
if throwing == ran_RPS:
print(f'我出{ran_RPS},我們平手。請出拳:\n')
elif (throwing == '剪刀' and ran_RPS =='石頭')or \
(throwing == '石頭' and ran_RPS =='布')or \
(throwing == '布' and ran_RPS =='剪刀'):
print(f'我出{ran_RPS},不好意思我贏了。')
break
else:
print(f'我出{ran_RPS},恭喜你贏了!')
break
# random 練習進階
# 剪刀石頭布 rock-paper-scissors/RPS,只猜一次
import random # 先設置導入random模組
RPS = ['剪刀', '石頭', '布'] # 先設一個列表 list []
ran_RPS = random.choice(RPS) # 使用.choice()
throwing = input(f' {RPS} ,請出拳:') # 讓使用者出拳
if throwing == ran_RPS:
print(f'我出{ran_RPS},我們平手。')
elif (throwing == '剪刀' and ran_RPS =='石頭')or \
(throwing == '石頭' and ran_RPS =='布')or \
(throwing == '布' and ran_RPS =='剪刀'):
print(f'我出{ran_RPS},不好意思我贏了。')
else:
print(f'我出{ran_RPS},恭喜你贏了!')
# random 練習進階
# 猜糖果遊戲
# 遊戲規則(1):電腦從5種糖果口味隨機選一個,使用者輸入猜測的答案
# 遊戲規則(2):只猜一次,一次定輸贏
import random # 先設置導入random模組
candies = ['草莓', '葡萄', '檸檬', '可樂', '抹茶']
candy = random.choice(candies) # 設置讓電腦隨機抽口味
ans = input(f'請從 {candies} 猜一個口味:') # 讓使用者猜口味
if ans != candy:
print(f'您猜錯了,答案是{candy}。')
else:
print(f'恭喜您猜對了!答案就是{candy}!')










