我在Python上还很陌生,并且具有用于将数字加倍的定义函数。我想使用for语句将数字翻三倍。这来自Dan Bader的Python基础知识6.3节。由于某种原因,这个让我感到难过。
下面,我尝试添加: 我的for语句后的数字=数字* 2,但我的结果是 20 40 80
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 3):
print(doubles(number))
实际结果是: 10 10 10
预期结果是: 10 20 40
答案 0 :(得分:1)
您想让number
(全局声音)保留调用doubles
的结果的声音;因此,请明确地这样做:
for x in range(0,3):
number = doubles(number)
print(number)
答案 1 :(得分:1)
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 5):
print(doubles(number))
number=doubles(number)
答案 2 :(得分:0)
您需要像这样将数字彼此相加。 “数字=数字+数字”的简称“数字+ =数字” 最好, 我希望这样写时更容易看到它。
number = 5
for x in range(0, 3):
double = number * 2
print(double)
number += number
答案 3 :(得分:0)
您将x递增,但沿途未更改“ number”的值
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 3):
print(doubles(number))
number*=2
答案 4 :(得分:0)
这是最少编码的解决方案。
def double(a):
print(a)
for b in range(1,5):
b = a * 2
a = b
print(a)
double(10)