如何编写增加数字的函数? [英] How does one write a function that increments a number?

查看:84
本文介绍了如何编写增加数字的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果这个问题看起来很愚蠢:如何写一个增加Python值的

函数?当我尝试时,变量

从未改变。

会话如下:

Apologies if this question seems stupid: How does one write a
function that increments a value in Python? When I tried, the variable
never changed.
The session went like this:

def incr(counter):
counter = int(counter)

counter + = 1

counter = 1
incr(柜台)
打印柜台
1
def incr(counter): counter = int(counter)
counter += 1
counter = 1
incr(counter)
print counter 1




提前致谢,

Vaibhav



Thanks in advance,
Vaibhav

推荐答案

您好,请参阅有关使用Python传递的增强内容的部分

教程。 Pythona的传递方案isna ??同样是
C ++的参考参数,但事实证明它与
$ b $非常相似b Ca ??在实践中的论点:

???不可变的论证就像C'的按价值一样。模式。诸如

整数和字符串之类的对象是通过对象引用(赋值)传递的,但是

因为无论如何都无法改变不可变对象,效果是

就像制作副本一样。

???可变参数的行为类似于C'的指针。模式。诸如

列表和字典之类的对象通过对象引用传递,这与C传递数组的方式类似,因为指针可变对象可以更改
函数中有
,就像C数组一样。


Leta ?? s试一试:
Hi, please refer to the sections about the augments passing in Python
tutorial. Pythona??s pass-by-assignment scheme isna??t the sameas
C++a??s reference parameters, but it turns out to be very similar to
Ca??s arguments in practice:
??? Immutable arguments act like C''s "by value" mode. Objects such as
integers and strings are passed by object reference (assignment), but
since you can''t change immutable objects in place anyhow, the effect is
much like making a copy.
??? Mutable arguments act like C''s "by pointer" mode. Objects such as
lists and dictionaries are passed by object reference, which is similar
to the way C passes arrays as pointersa??mutable objects can be changed
in place in the function, much like C arrays.

Leta??s have a try:
def incr(柜台):
counter [0] + = 1


counter = [100]
incr(柜台) )
打印计数器
[101]
def incr(counters): counters[0] += 1

counters =[100]
incr(counters)
print counters [101]






等等......所以这意味着不可能编写一个函数,即
增加一个整数而不将整数转换成一个列表?

Wait... so this means it is impossible to write a function that
increments an integer without turning the integer into a list?


< an***********@gmail.com>写道:
<an***********@gmail.com> wrote:
等等......这意味着不可能编写一个函数来增加一个整数而不将整数转换成一个列表?
Wait... so this means it is impossible to write a function that
increments an integer without turning the integer into a list?




简短的回答是不,你不能,因为整数是不可变的(因为

以及浮点数和字符串等)。更长的答案是你可以创建一个,例如,MutableInt类,其实例表现为可修改的

整数。很可能你并不是真的需要这个,但是如果你认为你会这么做,那么列表中的其他人会勾勒出如何。


George



The short answer is no you can''t, because integers are immutable (as
well as floats and strings among others). The longer answer is you can
create a, say, MutableInt class whose instances behave as modifiable
integers. Most probably you don''t really need this, but if you think
you do, others in the list will sketch out how.

George


这篇关于如何编写增加数字的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆