简体   繁体   中英

Why am I getting an error code when I run this code?

Why am I getting the following error code when I run this code:

builtins.NameError: name 'string' is not defined

def explore_string():
    get_input()
    explore_chars(string)
    sum_digits(string)

def explore_chars(string):
    print("Original: ",string)
    print("Length:   ",len(string),"chars")
    print("2nd char: ",string[1])
    print("2nd last: ",string[2])
    print("Switched: ",string[-3:]+string[3:-3]+string[0:3])

def sum_digits(string):
    dig_sum=0
    l=['1','2','3','4','5','6','7','8','9']
    for i in string:
        if i in l:
            dig_sum+=int(i)
    print("Digit sum: ",dig_sum)
    
def get_input():
    string=input("Enter 10 or more chars ending with a period: \n-> ")
    while(len(string)<10 or string[len(string)-1]!='.'):
        string=input("-> Error! Try again: ")
    return string 

explore_string()

You need to change your explore_string like this:

def explore_string(): 
    string = get_input()
    explore_chars(string)
    sum_digits(string)

The result value of get_input() should be stored in a variable string

Imentu's answer seems like the right solution. However, I want to add some minor tips that could help you to solve such problems by yourself. Because you might encounter them many more times in the future (at least I did).

The error code oftentimes contains a lot of information about the problem that you're facing. In your case the xxx is not defined means that you are referencing an object xxx which Python doesn't know about yet (it is not defined). Whenever you encounter this, then there are 2 main things you should check

  • Did I forget to assign it? (which is the case here)
  • Did I make a typo? (eg if you typed strng = get_input() )

If you combine this with the fact that the issue is centered around the word "string" and the approximate line number given by the error, then you should be able to find the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM