使用返回值对数字进行平方运算

2024-06-17 14:51:02 发布

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

好吧,我相信这是一个相当简单的作业,但我有很多麻烦,因为在线课程很糟糕,我刚刚开始编码。无论如何,我正在处理一个python赋值,其中我必须使用返回值对一个数字进行平方运算。以下是说明:

Write a function to square a number using return values. Squaring a number means multiplying it by itself (duh). Then make several calls to that function in your start function to test it out. Your square function should only return a value, not print anything. For example a function call like x = square(5) should put the value 25 in x. Print out x to be sure your function returns the correct value."

这是我最后的代码。我肯定这不太好,但这是一个简单的赋值,只需要我返回一个函数——不多也不少。但根据我得到的信息,我无法理解:

def square(x): 
    squared = x * x
    return squared
    print(squared)

print(square(5))
print(square(9))
print(square(8))
#above is just me 'testing' the code. If I don't include it, the checker tells me its wrong. 

当涉及到平方我给它的任何数字时,代码工作得很好,并且代码本身包括前面所述的返回函数。但是,它说这是错误的,“存储返回值以便验证它是否正确。”我查看了所有的课程和视频,但我找不到任何关于存储返回值以验证它的内容。有什么帮助吗

另外,如果格式错误,很抱歉。我10分钟前刚刚开了一个账户,因为我有点渴望有一个比我更聪明的人告诉我我做错了什么


1条回答
网友
1楼 · 发布于 2024-06-17 14:51:02

说明会告诉您如何执行此操作:

For example a function call like x = square(5) should put the value 25 in x.

所以你应该写:

x = square(5)
print(x)

函数中也不应该有print(squared)。它没有做任何事情,因为它在return语句之后,该语句结束了函数

相关问题 更多 >