我怎么把它放在main()中?
Posted
技术标签:
【中文标题】我怎么把它放在main()中?【英文标题】:how would i put this in the main()? 【发布时间】:2021-12-22 12:19:12 【问题描述】:我有一个需要以下内容的编码作业:
添加一个 main() 函数以从全局空间中删除所有代码
添加至少 1 个从主函数调用的函数。
至少 1 个函数必须接受并使用参数
至少 1 个函数必须返回您的程序使用的值
这就是我目前所拥有的
color = str(input("What color turtle was drawing the shapes? ")).lower()
numofshapes = int(input("how many shapes did it draw? ")).lower()
def whatturtle(color,numofshapes):
if color != "orange":
answer1 = "you are colorblind"
elif color != "blue":
answer1 = "his name is leonardo"
elif numofshapes != 5:
answer2 = "he did not draw that amount of shapes"
elif numofshapes = 5:
answer2 = "he drew some regular polygons with 3,4,6,9,12 sides!"
return answer1
return answer2
#####
def main():
main()
我在这里要做的是让用户说出绘制形状的海龟的颜色是什么以及它绘制了多少个形状(蓝色和 5)我需要在 def main 中使用该函数( ),我该怎么做?我想要得到的输出也是程序说“answer1 and answer 2”(例如,“你是色盲,他没有画那么多形状”)请帮忙谢谢!
【问题讨论】:
我已经为我所做的添加了一个更好的解释 + 修复了语句以使用字符串,因为这里不需要 int, + 我不知道你为什么用个人问题编辑你的问题,但你可以通过聊天给我发消息 :) chat.***.com/users/12291295/user12291295 【参考方案1】:def whatturtle(color, numofshapes):
answer1, answer2 = '', ''
if color != "orange":
answer1 = "you are colorblind"
elif color != "blue":
answer1 = "his name is leonardo"
if numofshapes != '5':
answer2 = "he did not draw that amount of shapes"
elif numofshapes == '5':
answer2 = "he drew some regular polygons with 3,4,6,9,12 sides!"
return answer1 + answer2
#####
def main():
color = input("What color turtle was drawing the shapes? ").lower()
numofshapes = input("how many shapes did it draw? ")
print(whatturtle(color, numofshapes))
main()
输入:
What color turtle was drawing the shapes? blue
how many shapes did it draw? 6
输出:
you are colorblindhe did not draw that amount of shapes
您有一些语法错误、冗余代码和无法访问的return
语句;
如果color
匹配,由于所有内容都在elif
语句中,它永远不会达到answer2
的条件,所以我添加了if
更适合第三种条件。
第 4 个条件是 numofshapes = 5
,它实际上不是一个条件,而是一个返回 syntax error
的赋值运算符,相等条件写成这样:==
。
第二个返回 return answer2
无法访问,因为您已经返回 answer
,在 Python 中,您可以返回多个语句,我将它们与 +
运算符连接起来,这是字符串的功能之一。
您在输入numofshapes
时尝试使用.lower()
和int
,.lower()
对字符串有效。
【讨论】:
以上是关于我怎么把它放在main()中?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的 C++ 函数只有放在 main() 之后才起作用?
为啥 main 前面有一个 int ,为啥我的教授会排除它? [复制]