为什么我的代码不计算一个数字可以除以2的次数?

时间:2018-07-21 19:03:52

标签: python function count

因此,我试图编写一个代码,计算一个数字在达到1之前可以除以2的次数。我希望能够输入想要的任何数字,然后在函数中使用它,然后,使用在函数外部产生的'count'变量。

print('Pick a number.')
number = input()
count = 0
def powerct(n):
    while n >= 2:
        n = n/2
        count = count + 1
powerct(number)
print(count)

2 个答案:

答案 0 :(得分:0)

Python变量位于“作用域”中-仅在作用域内可见,而不在作用域内。

函数具有自己的作用域-有关此内容的更多信息:Short Description of the Scoping Rules?

函数定义上方的count与函数内部的count不同。您可以通过从函数中返回它来解决此问题(或者将其设为global-如果需要,可以使用google这种方法-我不推荐这样做)。

# python 3.6 -you are probably using 2.x if your input() gives you a number

number = int(input('Pick a number.'))  # you need an int here, not a string
count = 0              # this is not the same count as

def powerct(n):
    count = 0          # this one is a different count
    while n >= 2:
        n = n/2        # this is going to be a float in python 3
        count += 1     
    return count

count = powerct(number)
print(count)

应该解决您的问题。


编辑:

# python 2.7 -realized youre using that by your use of input() giving int not string
number = input("Pick a number.") 
count = 0              # this is not the same count as

def powerct(n):
    count = 0          # this one is a different count
    while n >= 2:
        n = n/2        
        count += 1     
    return count

count = powerct(number)
print count

答案 1 :(得分:0)

尝试将计数传递给函数并返回它。

print('Pick a number.')
number = input()
count = 0
def powerct(n,count):
    while n >= 2:
        n = n/2
        count = count + 1
    return count
count = powerct(number,count)
print(count)

或者,在函数中将count声明为全局变量,这样它就可以在其局部范围内访问它:

print('Pick a number.')
number = input()
count = 0
def powerct(n):
    global count
    while n >= 2:
        n = n/2
        count = count + 1
powerct(number)
print(count)