简体   繁体   中英

I can't understand the fundemantals of functions in python

word = input('enter a word:')
letter = input('enter the letter you want to count:')
number = 0

def count(word ,letter)  :
    for i in word :
        if i == letter :
            number = number + 1
    print(number)

count(word ,letter)

this script doesn't work but this one works:

word = input('enter a word:')
letter = input('enter the letter you want to count:')

def count(word ,letter)  :
    number = 0
    for i in word :
        if i == letter :
            number = number + 1
    print(number)

count(word ,letter)

When number = 0 is replaced, why is the code affected? What is the thing that is I don't know about fuctions? What is the difference between number = 0 in function and out of function? Thanks for answering.

You can't assign (ie re-assign) values to variables defined outside of the function (you can however manipulate them, so if it's an object such as a list or a dict, you can modify that object - but again, that's not recommended as it makes code hard to read).

Keep all necessary references inside the function (and send any required information in as arguments to that function).

What you're actually asking about isn't only about functions, but it's what's called scope . Scope defines what symbols (which variables, etc.) are visible to code in particular locations.

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