我不确定以下为什么不起作用:
def main():
userInputs()
print(firstColour)
def userInputs():
validColours = ['red', 'green', 'blue', 'yellow', 'magenta','cyan']
while True:
firstColour = input('Enter the 1st colour: ')
secondColour = input('Enter the 2nd colour: ')
thirdColour = input('Enter the 3rd colour: ')
fourthColour = input('Enter the 4th colour: ')
if firstColour in validColours:
if secondColour in validColours:
if thirdColour in validColours:
if fourthColour in validColours:
break
else:
print('Invalid colours.Enter the colours again between red, green, blue, yellow, magenta, cyan')
return firstColour, secondColour, thirdColour, fourthColour
我认为如果我调用主函数,它会打印我作为firstColour输入的内容吗?
答案 0 :(得分:3)
如果要打印第一种颜色,请尝试以下操作:
def main():
firstColour, secondColour, thirdColour, fourthColour = userInputs()
print(firstColour)
当你在函数中的python中返回多个值时,它会将它们打包成一个名为" tuple"这是一个简单的值列表。你必须"解包"他们是为了使用它们。
您的userInputs函数中似乎还存在逻辑错误。你的返回函数缩进太多,这使得它总是在第一次尝试后返回,而不是重试。
def userInputs():
validColours = ['red', 'green', 'blue', 'yellow', 'magenta','cyan']
while True:
firstColour = input('Enter the 1st colour: ')
secondColour = input('Enter the 2nd colour: ')
thirdColour = input('Enter the 3rd colour: ')
fourthColour = input('Enter the 4th colour: ')
if firstColour in validColours:
if secondColour in validColours:
if thirdColour in validColours:
if fourthColour in validColours:
break
else:
print('Invalid colours.Enter the colours again between red, green, blue, yellow, magenta, cyan')
return firstColour, secondColour, thirdColour, fourthColour
答案 1 :(得分:0)
在python中,您将返回所谓的元组。如果您只想返回firstColour
,则只需调整逻辑即可为foundColour
分配最后找到的颜色,然后return foundColour
有关元组的更多信息:https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
答案 2 :(得分:0)
您没有使用您返回的值:
return firstColour, secondColour, thirdColour, fourthColour
您将返回4个变量,但不使用它们
userInputs()
用以下内容替换上述内容:
firstColour, secondColour, thirdColour, fourthColour = userInputs()