简体   繁体   English

如何使用现有变量及其值作为函数的参数(Python)?

[英]How can I use existing variables and their values as parameters for a function (Python)?

I believe what I am asking is pretty simple, however none of my searches have turned up useful information. 我相信我要问的很简单,但是我的搜索都没有找到有用的信息。

So, all I want is to be able to access a preexisting variable in a program and use its value as a parameter of one of my own functions. 因此,我所希望的就是能够访问程序中预先存在的变量,并将其值用作我自己的函数之一的参数。

print("Please enter a number")
number = int(input())

def addTwo(number):
    newNumber = number + 2
    print("Your number plus two is ", str(newNumber))

So if you entered the number 4: 因此,如果您输入数字4:

Please enter a number
>>> 4
Your number plus two is 6

That's all I need and hopefully it is simple! 这就是我所需要的,希望它很简单! Thanks! 谢谢!

As @BrenBarn suggested 正如@BrenBarn建议的

print("Please enter a number")
number = int(input())

def addTwo(number):
    newNumber = number + 2
    print("Your number plus two is ", str(newNumber))

addTwo(number)

You simply pass parameters to your function which takes exactly one argument number . 您只需将参数传递给您的函数即可,该函数只需要一个参数number

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

相关问题 函数如何在Python中将其他(函数)生成的变量用作自身的参数? - How can a function use variables generated by other (functions) as parameters for itself in python? 我如何在python中使用serial.readline()函数的值 - How can i use the values of serial.readline() function in python 我如何使用带有变量的随机函数? - How can i use the random function with variables? 如何在Python语句中使用变量? - How can I use variables in statements with Python? 如何使用sql数据库中的列值作为python函数的参数? - How to use column values from sql database as parameters of python function? 如何在 Python 中定义具有默认参数值和可选参数的函数? - How can I define a function with default parameter values and optional parameters in Python? 在Python中,如何在第二个函数中使用函数的return语句而不使用全局变量? - In Python, how can I use a function's return statement within a second function without using global variables? 我不能在我的 function 的参数上使用 Python 模块 - I can not use Python modules on the parameters in my function 当只有一些变量需要多个变量时,如何将多个值传递给函数-Python 3 - How can I pass multiple values to a function when only some variables need more than one - python 3 如何在嵌套函数中使用函数的参数? - How can I use the parameters of a function inside a nested function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM