Python 33 and python 33
Today, Eiffel saw Chapter 1. The task is to change a while loop to a function.
I changed the while loop to a function smoothly, but I don't know how to write the main function of python. I also encountered problems in parameter calling.
By checking the information, we found that the main function of python can be expressed in the following way:
if __name__ == '__main__'
Then we naturally want to pass the parameters I, numbers, and m declared in the main function into loop.
First thought:
def loop(i,numbers,m): while(i<m): print "at the top is %d" %i numbers.append(i) i = i+1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers:" for num in numbers: print numif __name__ == '__main__': i = 0 numbers = [] m = rawinput("input:") loop(i,numbers,m) print "thank you"
The operation is successful, but the result is a much greater than the input array. The result of the raw_input is 3:
After raw_input is changed to input, the result can be output normally:
Summary:
1. main Function in python (as shown above ).
2. The parameter passing method in python seems to be slightly different from that in c ++.
3. input and raw_input: the difference is that raw_input treats all input items equally (as strings), while input automatically differentiates the input type. For example, when we input 3, raw_input should regard 3 as a string, so the value of the string may be 6907 + 1 = 6908 in the running result.
4. global parameters: during the compilation process, I variables in the main function should be global variables by default, I didn't declare the I variable as global in the loop function. Why does the I value in the loop continue to change without the error "referenced before assignment? Later, I thought that because I passed the I variable using the parameter transfer method, the I values inside and outside the function are always consistent. In other words, if loop () does not reference parameter I, its internal I must be defined as global I.
5. In fact, the main function is not necessary in python.