python - 有没有办法让这个脚本更短?
问题描述
我是一个全新的程序员,从我读过的内容来看,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,'!')
解决方案
使用packing-unpacking怎么样?
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}!")
推荐阅读
- javascript - 没有父级的 JSON 文件如何获取?
- android - Android Facebook loginResult 拒绝电子邮件权限
- python - 如何计算数据集中每一行的词频
- sql - 删除“case when”中的重复项并计算步骤之间的平均值
- typescript - VSCode 在 TypeScript 中不显示缺少导入
- c++ - 我的循环不计算数组中的最终索引
- javascript - 在浏览器中执行(导入)带有 JavaScript 代码的字符串,该字符串导入 ES6 模块
- javascript - Angular 在同一页面渲染中动态创建图表线始终是最后一个数据值
- mongodb - MongoDB - 自动数据库会话初始化
- matlab - 为 EBAJA 2022 设计和模拟 ATV