Two practical tips for beginners to learn Python
- 2020-04-02 13:59:18
- OfStack
This article has documented two practical tips that are commonly used for beginners to learn Python. The details are as follows:
1. Variable parameters
The sample code is as follows:
>>> def powersum(power, *args):
... '''''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
Since the * prefix precedes the args variable, all redundant function arguments are stored as a tuple in args. If the ** prefix is used, the extra arguments are considered key/value pairs for a dictionary.
2. The exec statement executes the string STR as valid Python code. The execfile(filename [,globals [,locals]]) function can be used to execute a file.
The sample code is as follows:
>>> exec 'print "Hello World"'
Hello World>>> execfile(r'c:test.py')
hello,world!
I hope this article has helped you with your Python programming.