Home > Enterprise >  How would you stop a variable from resetting every time a for-loop runs?
How would you stop a variable from resetting every time a for-loop runs?

Time:07-20

I am trying to make a number classifier in python. This classifier is intended to determine whether the inputted integer is odd or even, and whether it is prime or not. In the primesorter(userin) function, I have a for-loop which loops through every number following up to the inputted number, with each loop returning the remainder of the division between the user input and x. If the remainder is == 1, then a variable isnotprime is = added to.

In the program, I tried to make it so that when this variable reaches over 2, it will print f"{userin} is not a prime number". Instead, I see that every instance of the loop it resets this variable. How can I make it save?

# Importing the time module to allow slight delay
from time import sleep

# Have to put sorting function first to avoid referencing error
def sorter(userin):
    if (userin%2) == 0: # Returns remainder: if its 0, the number is even 
        sleep(0.5)
        print(f"{userin} is an even number")
        sleep(0.5)

    elif (userin%2) > 0: # Returns remainder: if its greater than 0, the number is odd
        sleep(0.5)
        print(f"{userin} is an odd number")
        sleep(0.5)

def primesorter(userin):
    for x in range(1,userin):
        isnotprime = 0 # «« This variable will not save every instance of the loop. 

        if (userin%x) == 1:
            isnotprime  = 1
        print(isnotprime)
        
        if isnotprime >= 2:
             print(f"{userin} is not prime")
        else: print(f"{userin} is prime")

# Ask user for input
userin = int(input("Input a number to be categorized: "))


# Enter user input into the pre-defined function
sorter(userin)
primesorter(userin)

CodePudding user response:

The variable definition needs to be outside the for loop, otherwise each time you do an iteration the variable is reset. for example:

input_var = 0 # variable defined outside the for loop
for i in range(12):
    input_var =1 # this line executes every loop
    # input_var = 0 # if it's defined here every loop would initialize the variable to zero
    print(input_var)
  • Related