Udemy - 100 Days of Code: The Complete Python Pro Bootcamp

Day 4 - Beginner - Randomization & Lists

31. Random Module
import random

# Random Seeds
random.seed(a=None, version=2)
state = random.getstate()
random.setstate(state)

# Random Integers
random_int = random.randrange([start,] stop [,step])    # [start, stop)  
random_int = random.randint(a, b)                       # [a, b]    
random_int = random.getrandbits(k)                      # [0, 2^k)

# Random Floats
random_float = random.random()                          # [0.0, 1.0)  
random_float = random.uniform(a, b)                     # [a, b]

# Random Sequences
random_seq = random.choice(seq)                                                  # 随机选1个
random_seq = random.choices(population, weights=None, *, cum_weights=None, k=1)  # 随机选k个,允许重复
random_seq = random.sample(population, k, *, counts=None)                        # 随机选k个,不重复
random.shuffle(seq)
32. Lists
# List 列表
this_list = ["apple", "banana", "cherry"]  
print(this_list)  
  
# Access Items  
print(this_list[2])
print(this_list[-1])  
print(this_list[0:2])  
print(this_list[-3:-1])

# Change Items
this_list[1] = "blackcurrant"  
this_list[1:3] = ["blackcurrant", "watermelon"]  
this_list[1:3] = ["blackcurrant", "watermelon", "pineapple"]  
this_list[1:3] = ["blackcurrant"]

# Adding Items
this_list.append("orange")
this_list.insert(1, "orange")
this_list.extend(["kiwi", "mango"])

# Remove Items
this_list.remove("apple")
this_list.pop(0)
this_list.pop()
del this_list[0]
del this_list
this_list.clear()
33. Banker Roulette
import random  
friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]  
  
# 1st Option  
print(random.choice(friends))  
  
# 2nd Option  
random_index = random.randint(0, 4)  
print(friends[random_index])
34. IndexError and Nested Lists
# Length of List
fruits = ["Cherry", "Apple", "Pear"]
print(len(fruits))

# IndexError
fruits = ["Cherry", "Apple", "Pear"]
print(fruits[3])

# Nested List / 2D List
fruits = ["Cherry", "Apple", "Pear"]  
veg = ["Cucumber", "Kale", "Spinnach"]

fruits_and_veg = [fruits, veg]
print(fruits_and_veg[1][1])
35. Rock Paper Scissors Project

Demo

import random

game_choices = ["rock", "paper", "scissors"]

user_choice = int(input("What do you choose? "
                        "Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
if 0 <= user_choice <= 2:
    print(f"User chose: {game_choices[user_choice]}")

    computer_choice = random.randint(0, 2)
    print(f"Computer chose: {game_choices[computer_choice]}")

    if ((user_choice == 0 and computer_choice == 2)
        or (user_choice == 1 and computer_choice == 0)
        or (user_choice == 2 and computer_choice == 1)):
        print("You win!")
    elif computer_choice == user_choice:
        print("It's a draw!")
    else:
        print("You lose!")

else:
    print("You typed an invalid number. You lose!")
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐