Python Forum

Full Version: name ' ' is not defined error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: AOhTfvC]


it won't print my str please help it has worked before but just now it won't work
Copy and paste your code using python tags, and put the full text of the error message in output tags.
import math

while True:  
    try:
        tal = int(input("tal?: "))
    except ValueError:
        print("kun tal")
    n = tal
    for p in range(2,n):
        moudu = n%p
        prime = "det er et primtal"
        if moudu == 0:
            prime = "det er ikke et primtal"
            break
    ianden = tal*tal
    print (prime)
    print ("² = ", ianden)
    print ("kvadratrod =", math.sqrt(tal))
    
    input('Press enter to continue: ')
Output:
Exception has occurred: NameError name 'prime' is not defined File "C:\Users\nonoe\OneDrive\Skrivebord\info om tal 0.1.py", line 20, in <module> print (prime)
The variable prime only gets defined if a value greater than 2 is entered. If you enter 1 on the first try, the loop on line 9 never executes, and prime never gets defined. Note that if you enter 1 on the second try, it uses the value of prime from the previous try. You need to set a value to prime before that loop.
thank you very much.
this really helped my day :)