Day 4 - Beginner - Randomisation and Python Lists

Day 4 - Beginner - Randomisation and Python Lists

38. Day 4 Goals: what we will make by the end of the day
39. Random Module
40. [Interactive Coding Exercise] Random Exercise
41. Understanding the Offset and Appending Items to Lists
42. [Interactive Coding Exercise] Banker Roulette - Who will pay the bill?
43. IndexErrors and Working with Nested Lists
測驗 5: List and IndexError Quiz
44. [Interactive Coding Exercise] Treasure Map
45. Day 4 Project: Rock Paper Scissors
46. Programming is like going to the Gym
2個讚
  1. Day 4 Project: Rock Paper Scissors

使用 true table,list 的解法,感覺比較簡單易懂 !

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''
import random

image = [rock,scissors,paper]

select = int(input("Please select 0 for Rock, 1 for scissors, 2 for paper. > "))
if select < 0 or select > 2:
  print("You select a wrong number. You Lose !")
else:
  print(image[select])
  print("\n\nComputer select :")
  computer = random.randint(0,2)
  print(image[computer])

# ------ 以下主程式 -------
  rule1 = ["Draw","Win","Lose"]
  rule2 = ["Lose","Draw","Win"]
  rule3 = ["Win","Lose","Draw"]
  result = [rule1,rule2,rule3]
  print(f"You {result[select][computer]} !")

39. Random Module

import module

就是將我們所要引入的 module 裡面的所有程式碼 import 進來,因此可以在 import 以後使用該模組裡的所有變數(variable)、函式(function)、類別(Class)等等

  • 若 module 本身即是一個可執行的 python file,則會直接執行,執行結果可影響後續程式。
  • 不可在 import module 之前叫用 module 內之元件,必須要在使用它們之前先進行 import。通常都會把需要 import 的 module 們列在整個檔案的最一開始,但不是必須。
  • 一個模組不會重複載入。多個不同的模組都可以用 import 引入同一個模組到自己的 Local 名字空間,其實背後的 PyModuleObject 物件只有一個。多次 import 的效果是只有第一次 import 有用。

語法1:import [module]

語法2:from [module] import [name1, name2, …]

語法3:import [module] as [new_name]

語法4:from [module] import *
(不推薦,相對以後維護程式會困難,搞不清楚該元件來自何處;也可能會造成名稱衝突。)

2個讚