Search code examples
pythonpython-3.xvariablesinputindentation

how to bring out a variable outside of indention?


I created a program that has indention in it (you know , like for and while loops , if , elif , else , def and any another thing that has indention after it.) and this indention has some new created variables in it. like this :

          .
          .
          .
little_input = input()
big_input = input()
num = 10
def calculate() :
    global num
    num += 1
    num2 = num * big_input
    num3 = num2 / little_input
    print(num3)
    rmin = num2 % little_input
    if rmin == 0 :
        print(num3)
           .
           .
           .

and then I saw I need to do something with the num3 variable but it needs to be outside of the def indention. and when it's outside , it says the variable is not defined. can you help me with this? thanks.

edit for @Nesi :

print("chain wheel calculator")
print("enter the little diameter in mm :")
little_input = input()
print("enter the big diameter in mm :")
big_input = input()

little_input = int(little_input)
big_input = int(big_input)

num = 9

def calculate() :
    global num
    num += 1
    num2 = num * big_input
    num3 = num2 / little_input
    print(num3)
    rmin = num2 % little_input
    if rmin == 0 :
        print(num3)

while num <= 100 :
    calculate()

Solution

  • Try this.

    def calculate(num) :
        num2 = num * big_input
        num3 = num2 / little_input
        print(num3)
        rmin = num2 % little_input
        if rmin == 0 :
            print(num3)
        # after you do what you need with this function
        # you will endup with value for num3, right?
        # we will give it to the loop.
        return num3
    
    print("chain wheel calculator")
    print("enter the little diameter in mm :")
    little_input = input()
    print("enter the big diameter in mm :")
    big_input = input()
    
    little_input = int(little_input)
    big_input = int(big_input)
    
    
    num = 9
    while num <= 100 :
        num3 = calculate(num)  # pass the num to function
        print(num3)
        num += 1