什么是return语句的简单基本解释,如何在Python中使用它?
它和print声明有什么区别?
在我之前的问题中,Andrew Jaffe写道:
除了所有其他提示和技巧之外,我认为你错过了一些至关重要的东西:你的功能实际上需要返回一些东西.当你创建
autoparts()或者splittext(),我们的想法是,这将是一个你可以调用的函数,它可以(而且应该)回馈一些东西.一旦你找到了你想要你的函数的输出,你需要把它放在一个return语句中.
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
print(parts_dict)
>>> autoparts()
{'part A': 1, 'part B': 2, ...}
Run Code Online (Sandbox Code Playgroud)
此函数创建一个字典,但它不返回任何内容.但是,因为我添加了print,所以当我运行该函数时会显示该函数的输出.什么return东西和print它之间有什么区别?
def solve(n):
#prepare a board
board = [[0 for x in range(n)] for x in range(n)]
#set initial positions
place_queen(board, 0, 0)
def place_queen(board, row, column):
"""place a queen that satisfies all the conditions"""
#base case
if row > len(board)-1:
print board
#check every column of the current row if its safe to place a queen
while column < len(board):
if is_safe(board, row, column):
#place a queen
board[row][column] = 1
#place the next queen with an updated board
return place_queen(board, …Run Code Online (Sandbox Code Playgroud) 正如标题所示,我做了一个简单的函数,如下所示:
import sys
string = sys.argv[1]
def position():
for index in range(len(string)):
if string[index] == 'A':
print(int(index+1))
position()
Run Code Online (Sandbox Code Playgroud)
当与“AABABC”等测试字符串一起使用时,将以数字形式返回每个“A”的位置。
在这里,我增加索引,1 因为我注意到范围从 0 开始。虽然我可以传递 1 或任何我想要的数字以使其开始,但它会删除/不打印我想要的所有内容。所以我发现这在这种情况下效果最好。
这里一切正常。但当我用return语句替换函数中的 print 时却没有:
import sys
string = sys.argv[1]
def position():
for index in range(len(string)):
if string[index] == 'A':
return int(index+1)
print(position())
Run Code Online (Sandbox Code Playgroud)
在这里,我只显示对代码的编辑,但我确实尝试了几种不同的方法,所有方法都具有相似的结果(因为它不起作用):
+=在这种特定情况下不起作用?与可能被视为与我的重复/相似的其他“问题”相比,我print()在最后一个示例中使用了它之外的函数。所以问题很可能不是来自那里。
我也不认为我的缩进是错误的。
为了提供有关“什么不起作用”的更多详细信息,当我使用return而不是print此处并使用诸如“ABABACD”之类的测试字符串时,它将输出正确的“136”作为结果。但是,当return与我之前列出的其他失败尝试一起使用时,它只会输出“1”......
我有一个功能来检查列表中的"负","正"和"零"值.以下是我的功能:
def posnegzero(nulist):
for x in nulist:
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"
Run Code Online (Sandbox Code Playgroud)
但是当我运行此函数时,它会在检查列表中第一个数字的值后停止.例如:
>>> posnegzero([-20, 1, 2, -3, -5, 0, 100, -123])
"negative"
Run Code Online (Sandbox Code Playgroud)
我希望它继续整个列表.在上面的函数中,如果我改变了returnto的每个实例print,那么它会做它应该做的事情,但是现在我不希望它None在函数完成时说出来.我错在哪里的想法?
源代码需要进行哪些更改?
def Update():
打印('\ n')
打印(“更新”)
cmd = os.system('xterm -e apt-get update')
打印(“完成更新”)
def AptUpdate():
打印('\ n')
打印(“更新系统?{Y / N}”)
打印(“ Y或y”)
打印(“ N或n”)
代码=输入(“命令>”)
如果代码=='y'或代码=='Y':
对于我在Update()中:
返回更新
elif代码=='n'或代码=='N':
返回
其他:
打印(“警告!”)
AptUpdate()
例外:
追溯(最近一次通话):
在第110行的文件“ pybash.py”中
AptUpdate()
AptUpdate中的文件“ pybash.py”,第102行
对于我在更新:
TypeError:“函数”对象不可迭代
这是我第一次尝试创建和使用类。当我要求用户输入时发生错误。我收到以下错误:
n1 = Arithmetic.float_input("Enter your First number: ")
TypeError: float_input() missing 1 required positional argument: 'msg'
Run Code Online (Sandbox Code Playgroud)
这是我的代码。
# Define class
class Arithmetic:
def float_input(self, msg): # Use this function for exception handling during user input
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
def add(self, n1, n2):
sum1 = n1 + n2
print(n1,"+" ,n2,"=", sum1)
def sub(self, n1, n2):
diff = n1 - n2
print(n1,"-",n2,"-", diff)
def mult(self, n1, n2):
product = n1 * …Run Code Online (Sandbox Code Playgroud) python ×7
python-3.x ×2
return ×2
backtracking ×1
class ×1
function ×1
iteration ×1
list ×1
position ×1
printing ×1
python-2.7 ×1
recursion ×1