简体   繁体   English

如何定义python函数

[英]How to define a python function

So I am new to Python and have to take a class in it for college credits. 因此,我是Python的新手,必须上一堂课才能获得大学学分。 We were given an assignment to do at home (we are allowed to go online for help etc) and part of this involved defining a function. 我们被分配了一项在家工作的权限(允许我们上线寻求帮助等),其中一部分涉及定义功能。 I'm not very good at coding/computers in general and I'm having a lot of difficulty in trying to do so. 一般而言,我不太擅长编码/计算机,尝试这样做有很多困难。

How would I go about defining a function so cos(a,b,c) = cos(a - c) - ab? 我将如何定义一个函数,使cos(a,b,c)= cos(a-c)-ab? I've tried everything, and I wouldn't be outright asking people for help if I wasn't desperate. 我已经尽了一切努力,如果我不是绝望的话,我不会直截了当地向人们寻求帮助。

I know that function may seem easy to some but I'm just not good at this at all. 我知道某些功能似乎很简单,但是我一点都不擅长。 This is what I tried (don't laugh!) 这就是我尝试过的(不要笑!)

def np.cos(a, b, c):   
"""
Given three variables, rearrange them to create new equation
>>>np.cos(d,e,f)
np.sin(d - f) - e*d
>>>np.cos(1,2,3)
np.cos(1 - 3) - 2*3
"""
if np.cos(a, b, c):
    return np.cos(a - c) - b*a 

As you can clearly see, I'm not sure what I'm doing. 您可以清楚地看到,我不确定自己在做什么。 Any advice/tips would be greatly appreciated. 任何建议/提示将不胜感激。 Thank you :) 谢谢 :)

You can use math.cos() to determine the cosine value of anything in your function. 您可以使用math.cos()确定函数中任何东西的cosine值。

import math 
def cos(a,b,c):
    return math.cos(a-c) - a*b

print cos(1,2,3) 

Two things to look here: 这里有两件事:

  1. Although I have named my function cos to show you the difference between cos and math.cos , you should name your function to something else like cosOfthree to avoid naming conflicts. 尽管我已将函数cos命名为可以显示cosmath.cos之间的区别,但您应将函数命名为cosOfthree类的cosOfthree以避免命名冲突。
  2. Always look at your indentation in python code. 始终在python代码中查看缩进。 Instructions inside function definition should be indented. 函数定义内的指令应缩进。

You can import math and do something like this 您可以导入数学并执行类似的操作

import math
def trig(a,b,c):
    return math.cos(a-c)-a*b
a,b,c= map(eval,raw_input().split())
trig(a,b,c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM