【问题标题】:I am costantly getting tuple errors and want to know what they are and how i can fix them我不断收到元组错误,想知道它们是什么以及如何修复它们
【发布时间】:2017-10-17 05:46:33
【问题描述】:

例如,当我在此函数中添加以下多个返回时,我正在为学校编写的代码给了我一个元组错误

def GetHowLongToRun():
  print('Welcome to the Plant Growing Simulation')
  print()
  print('You can step through the simulation a year at a time')
  print('or run the simulation for 0 to 5 years')
  print('How many years do you want the simulation to run?')
  Years = int(input('Enter a number of years to run, or -1 for stepping mode:'))
  skipyear = input("Would you like to pause every year? Y/N")
  skipseason = input("Would you like to pause every season? Y/N")
  return Years, skipyear, skipseason

这给了我以下错误

Traceback (most recent call last):
  File "C:\Users\jonwe\Downloads\Paper1_ASLv1_2017_Python3_Pre (1).py", line 170, in <module>
    Simulation()
  File "C:\Users\jonwe\Downloads\Paper1_ASLv1_2017_Python3_Pre (1).py", line 154, in Simulation
    if YearsToRun >= 1:
TypeError: '>=' not supported between instances of 'tuple' and 'int'

但如果我只返回“Years”字符串,它不会给我任何错误并且可以完美运行

【问题讨论】:

    标签: python-3.x function return tuples


    【解决方案1】:

    我认为问题在于您如何处理/解压缩返回值。我不知道您目前拥有什么,但应该是:

    YearsToRun, skipy, skips = GetHowLongToRun ()
    

    将变量分配给函数的顺序应与返回值的顺序相同。

    >>> YearsToRun, skipy, skips = GetHowLongToRun ()
    Welcome to the Plant Growing Simulation
    
    You can step through the simulation a year at a time
    or run the simulation for 0 to 5 years
    How many years do you want the simulation to run?
    Enter a number of years to run, or -1 for stepping mode:2
    Would you like to pause every year? Y/NN
    Would you like to pause every season? Y/NN
    >>> if YearsToRun >= 1:
    ...    print ('Do something.')
    ...    print ('Skip year: ', skipy)
    ...    print ('Skip season: ', skips)
    ... 
    Do something.
    Skip year:  N
    Skip season:  N
    

    【讨论】:

    • 我最终只是对我试图返回的变量进行了全球化,但我确定这不是一个我应该始终使用的好修复?
    • 这取决于您的喜好。如果它有效,它就有效。我倾向于最小化全局变量,因为我经常在我的函数中隐藏该变量。意思是,我在我的函数中使用了相同的变量名而没有意识到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2021-12-12
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多