簡體   English   中英

有沒有辦法使這個腳本更短?

[英]Is there a way to make this script shorter?

我是一個嶄新的程序員,根據我的閱讀,Python很容易學習,所以我嘗試學習它。 這只是我幾分鍾內制作的一個有趣的腳本,我想知道是否可以縮短它。 如果您無法分辨,這實際上是用戶輸入三個變量,然后選擇其中一個,重復三次,然后合並答案。

import random
import time

print("name three diffrent animals")
animal1 = input("1")
animal2 = input("2")
animal3 = input("3")
x = (random.randint(1,3))
if x == 1:
    x = animal1
if x == 2:
    x = animal2
if x == 3:
    x = animal3

print("name three diffrent colors")
color1 = input("1")
color2 = input("2")
color3 = input("3")
y = (random.randint(1,3))
if y == 1:
    y = color1
if y == 2:
    y = color2
if y == 3:
    y = color3

print("name three diffrent sports")
sport1 = input("1")
sport2 = input("2")
sport3 = input("3")
z = (random.randint(1,3))
if z == 1:
    z = sport1
if z == 2:
    z = sport2
if z == 3:
    z = sport3

print("your dream animal is a.....")
time.sleep(3)
print(y, ',' , z, 'playing', x,'!')

如何使用開箱包裝?

print("Name three different animals: ")
animals = input("1: "), input("2: "), input("3: ")

並使用choice()代替randint()嗎?

x = random.choice(animals)

並且(也許)使用f字符串進行打印?

print(f"{y} {z} playing {x}!")

這是一個建議

# read a list of N animal names
animals = list(map(lambda i: input(str(i)), range(1, N)))

# read a small (fixed) number of animal names
animals = input("1"), input("2"), input("3")

# select a random animal from the list
x = animals[random.randint(0, len(animals) - 1)]

# or

x = random.choice(animals)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM