所以我刚开始在学校学习python,我一直在家里练习,所以我对python还是个新手。 我遇到的问题是我试图将def two()中的值转移到main()中,但是当我使用{0}将它们放入打印或计算中时,它会显示错误,并且它们没有任何值。在
我的代码是:
def two():
print("Hello world!")
print("Please enter three numbers")
nam=int(input("Enter the first number: "))
num=int(input("Enter the second number: "))
nom=int(input("Enter the third number: "))
print("So the numbers you have entered are {0}, {1},{2}.".format(nam,nom,num))
def main():
main=two()
inpt=input("what math related problem would you like me to do with them? tell me here: ").capitalize()
if inpt== "Divide":
ans=({0}/{1}/{2})/1
print("{0}, there you go!")
elif inpt== "Times":
ans=(nam*num*nom)/1
print("{1}, there you go!")
下面是我运行它得到的结果:
^{pr2}$
在您的代码中:
{0}
、{1}
和{2}
是包含一个元素的集合。你不能划分集合,这正是错误所抱怨的。在您需要将值从
two()
传递到main()
。关于如何做到这一点,请参阅杀戮者的答案。在您不能随意使用
{0}
标记,因为它们是由format()
从字符串中读取来格式化文本的。在字符串之外是一个包含零的集合。在这里的问题是,您试图将字符串格式应用于main函数中的非字符串操作。在
在上面一行中使用的大括号只用于单个
format
函数调用中的值的子项。当您调用ans=({0}/{1}/{2})/1
时,实际上是在创建三个独立的sets;这是一个不同的Python数据类型。你得到了这个错误,因为集合并不是像你的代码那样被分割的。在正如Slayer的答案中提到的,最好的办法是返回“2”函数中的所有三个变量:
^{pr2}$这样,您就可以在主函数中为它们分配其他变量。我强烈建议不要创建与函数同名的变量。这会让你产生一些令人困惑的行为。在
最后,可以修改实际创建异常的代码行。在
您可以从上一个函数返回值,然后将它们设置为变量。在
在
two()
结尾在
^{pr2}$main()
中设置main = two()
另外,您应该重命名
main
您可以使用已经保留的名称空间来覆盖功能。在然后可以用这些值进行除法
现在这些都是单例的,即包含一个元素的集合。在
然后可以使用
format
将这些输入到print
语句中的字符串中相关问题 更多 >
编程相关推荐