-4

So I was trying to make a code to count how many times a number could be divided by two before reaching 1. I would like to be able to input any number I want and then use it in the function, and afterwards, to use the 'count' variable that was yielded outside the function.

print('Pick a number.')
number = input()
count = 0
def powerct(n):
    while n >= 2:
        n = n/2
        count = count + 1
powerct(number)
print(count)
  • you have to `return count` after the while block ... and get the returned number from your function call. This might help you solve your problems: [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Patrick Artner Jul 21 '18 at 19:06
  • 2
    Don't use global variables, at least not for something like this. Learn about the `return` statement. – Aran-Fey Jul 21 '18 at 19:11

2 Answers2

0

Python variables live in "scopes" - they are only visible while in scope, not out of it.

Functions got theire own scope - more about this here: Short Description of the Scoping Rules?

Your count from above the function definition is not the same as the count inside your function. You can remedy this by returning it from the function (or making it global - google this method if you like - I would not recommend it).

# 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)

should solve your problem.


Edit:

# 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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Try passing in the count to the function and returning it.

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)

Alternatively, declare count as a global variable in the function, so it can acces it in its local scope:

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)
jshamble
  • 391
  • 2
  • 14