Local and global variables in Python

2016.11.15

 0. What will the following program input?

def next():
    print('I am in the next() function...')
    pre()

def pre():
    print('I am here in the pre() function...')

next()

Answer:

I am in the next() function...

I am here in the pre() function...
1. Visually check what the program will print?

var = 'Hi'

def fun1():
    there is a global
    var = 'Baby'
    return fun2(var)

def fun2(var):
    var+='I love you'
    fun3 (var)
    return var

def fun3(var):
    var = 'little turtle'

print(fun1())

 Answer: Baby I love you

2. Write a 1 function to determine whether the incoming string is a 'palindrome' (a palindrome is a couplet written in the form of a palindrome, for example: Shanghai tap water comes from Shanghai)

Law one:

def palindrome(string):
    list1 = list(string)
    list2 = reversed(list1)
    if list1 == list(list2):
        return ' is a palindrome! '
    else:
        return 'Not a palindrome! '
print(palindrome('Shanghai tap water comes from the sea'))

 Law two:

def palindrome(string):
    length = len(string)
    last = length-1
    length //= 2
    flag = 1
    for each in range(length):
        if string[each] != string[last]:
            flag = 0
        last -= 1

    if flag ==1:
        return 1
    else:
        return 0

string = input('Please enter a sentence:')
if palindrome(string) == 1:
    print('It is a palindrome!')
else:
    print('Not a palindrome!')

 3. Write a function to count the number of English letters, spaces, numbers and other characters of the incoming string parameters (possibly more than one).

The program execution result is shown in the figure:

count('I love fishc.com.','I love you,you love me.')

 

def count(*param):
    length = len (param)
    for i in range(length):
        letters = 0
        space = 0
        digit = 0
        others = 0
        for each in param[i]:
            if each.isalpha():
                letters += 1
            elif each.isdigit():
                diet += 1
            elif each == ' ':
                space += 1
            else:
                others += 1
        print('The %dth string has a total of %d letters, %d digits, %d spaces, and %d other characters.'%(i+1, letters, space, digit, others))
count('I love tuocheng','I love you,you love me.')

 The answer is:

The first string consists of 13 English letters, 2 numbers, 0 spaces, and 0 other characters.

The second string consists of 17 English letters, 4 numbers, 0 spaces, and 2 other characters.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326990450&siteId=291194637