[英]How do I use the return statement with strings? - Python
我不确定以下为什么不起作用:
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输入的内容吗?
如果要打印第一种颜色,请尝试以下操作:
def main():
firstColour, secondColour, thirdColour, fourthColour = userInputs()
print(firstColour)
当你在函数中的python中返回多个值时,它会将它们打包成什么叫做“元组”,这是一个简单的值列表。 您必须“解压缩”它们才能使用它们。
您的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
在python中,您将返回所谓的元组。 如果你只想返回firstColour
,你只需要调整你的逻辑,用最后找到的颜色分配foundColour
,然后return foundColour
有关元组的更多信息: https : //docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
您没有使用您返回的值:
return firstColour, secondColour, thirdColour, fourthColour
您将返回4个变量,但不使用它们
userInputs()
用以下内容替换上面的内容:
firstColour, secondColour, thirdColour, fourthColour = userInputs()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.