简体   繁体   English

我如何在 python 中编写一个 function 作为输入 2 个数字和 1 个字符串

[英]How do I write a function in python that takes as input 2 numbers, and 1 string

I tried to do it but my code doesn't work.我尝试这样做,但我的代码不起作用。 When I call operate(4,5,add) I have a traceback that says "name 'add' is not defined" .当我调用operate(4,5,add)时,我有一个回溯,上面写着"name 'add' is not defined" Could you please help me?请你帮助我好吗?

def operate(x,y,z):
    if (z == "add"):
        op = x+y
        print("%d + %d = %d" %(x, y, op))
    elif (z == "multiply"):
        op = x*y
        print("%d * %d = %d" %(x, y, op))

add is not a string. add不是字符串。 'add' and "add" are strings. 'add'"add"是字符串。 You need to call your function with operate(4, 5, 'add') or operate(4, 5, "add") .您需要使用operate(4, 5, 'add')operate(4, 5, "add")调用您的 function。

暂无
暂无

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

相关问题 python 基础知识 - 我正在尝试编写一个 function,它将一个字符串(一个月)作为输入并返回该月的天数 - python basics - I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month 您如何在Python中编写一个函数,该函数需要一个字符串并返回一个新字符串,该字符串是原始字符串,并且重复了所有字符? - How do you write a function in Python that takes a string and returns a new string that is the original string with all of the characters repeated? 如何编写一个接受字符串并返回该字符串中的第一个单词的函数 - How do I Write a function that takes in a string and returns the first word in that string 如何将 3 个数字与在 Python 中仅采用 2 个变量的函数与我编写的代码进行比较 - How do I compare 3 numbers with a function that takes only 2 variables in Python with a code that I have written 如何编写一个函数 function(n) 接受一个整数,并使用 while 循环返回前 n 个偶数的总和? - How do I write a function function(n) that takes in an integer, and returns the sum of the first n even numbers using a while loop? 如何为 Python 的可变数量输入数据编写 function? - How do I write a function for Varied amount input data for Python? 如何优雅/高效地为需要大量实例变量的 Python 类编写 __init__ 函数? - How do I elegantly/efficiently write the __init__ function for a Python class that takes lots of instance variables? 如何在 Python 中创建一个接受数字和整数列表的函数? - How can I create a function in Python that takes a list of numbers and an integer? 如何将此输入的字符串转换为数字? - How do i transform the string of this input into numbers? 如何使用循环来编写 python 程序,该程序接受用户输入“第 1 个人的经验年数?”、第 2 个人、第 3 个人等等? - How do I write a python program using loops that takes the user input "Years of experience of person 1?", person 2, person 3, and so on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM