如何从另一个定义中结转值?

2024-10-17 00:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我刚开始在学校学习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}$

Tags: theyounumberinputmaindefnomnum
3条回答

在您的代码中:

ans=({0}/{1}/{2})/1

{0}{1}{2}是包含一个元素的集合。你不能划分集合,这正是错误所抱怨的。在

您需要将值从two()传递到main()。关于如何做到这一点,请参阅杀戮者的答案。在

您不能随意使用{0}标记,因为它们是由format()从字符串中读取来格式化文本的。在字符串之外是一个包含零的集合。在

这里的问题是,您试图将字符串格式应用于main函数中的非字符串操作。在

print("So the numbers you have entered are {0}, {1},{2}.".format(nam,nom,num))

在上面一行中使用的大括号只用于单个format函数调用中的值的子项。当您调用ans=({0}/{1}/{2})/1时,实际上是在创建三个独立的sets;这是一个不同的Python数据类型。你得到了这个错误,因为集合并不是像你的代码那样被分割的。在

正如Slayer的答案中提到的,最好的办法是返回“2”函数中的所有三个变量:

^{pr2}$

这样,您就可以在主函数中为它们分配其他变量。我强烈建议不要创建与函数同名的变量。这会让你产生一些令人困惑的行为。在

nam, num, nom = two()

最后,可以修改实际创建异常的代码行。在

ans = nam / num / nom

您可以从上一个函数返回值,然后将它们设置为变量。在

two()结尾

return nam, num, nom

main()中设置main = two()

^{pr2}$

另外,您应该重命名main您可以使用已经保留的名称空间来覆盖功能。在

然后可以用这些值进行除法

ans = nam / num / nom

现在这些都是单例的,即包含一个元素的集合。在

然后可以使用format将这些输入到print语句中的字符串中

相关问题 更多 >