Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Portnov Computer School Test Automation For Web-Based Applications Presenter: Ellie Skobel Day 7 Python Modules and Functions 2 Keyword def introduces a function definition Function name must start with a letter or _ and it's followed by the parenthesized list of formal parameters. Body of the function start at the next line, and must be indented. 3 def function_name(param1, param2): sum = int(param1) + int(param2) if sum % 2: print sum, ' is an even number' return sum To use the function in your code: function_name(3, 5) sum is an even number function_name(2, 3) nothing printed 4 Possible to define functions with a variable number of parameters (a.k.a arguments) Default Argument Values ◦ function can be called with fewer arguments than it is defined to accept Keyword Arguments ◦ functions can be called using form kwarg=value Arbitrary Argument Lists ◦ function can be called with an any (infinite) number of arguments 5 name argument is required age argument is optional False is a default value def register(name, age=None, married=False): print "Welcome", name.title() if age and int(age) > 20: print "You don't look a day over", int(age)–2 if married: print "Your spouse is very lucky!" register("John") register("Jane", 21) register("Amy", married=True) register("Bob", 55, True) register("Ken", age=12, married = False) 6 name argument is required argument form: key = value infinite number of optional arguments def register(name, **kwargs): print "Welcome", name.title() for key in kwargs.keys(): print key, ":", kwargs[key] register("John") register("Jane", age=21) register("Amy", married=True, gender="female") register("Jeff", height="6'1", weight=175, children=None) 7 name argument is required age argument is optional infinite number of optional arguments def register(name, age=18, *args): If more that 1 print "Welcome", name.title() argument given, 2nd if age < 18: one will always be print "You are underage" assigned to age for num, arg in enumerate(args): print "Argument #{0} is {1}".format(num, arg) register("John") register("Jane", 21) register("Jeff", 21, None) register("Amy", 20, 30, 40, 50, 60) register("Steve", None, 42, "Hello") 8 A module is a file containing Python definitions and statements The file name is the module name with the suffix .py appended Module name is: common Python statement Python function definitions 9 Packages are directories which contain python files (modules) Packages are a way of structuring modules The __init__.py files are required to make Python treat the directories as packages python package named: functions contains file: __init__.py regular directory, NOT a package 10