Test Automation For Web-Based Applications Portnov Computer School WebDriver Training Test Automation For Web-Based Applications Presenter: Ellie Skobel
Day 3 Python Modules and Functions
Functions 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.
Functions 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) function_name(2, 3) sum is an even number nothing printed
This is the correct way: def function_name(param1, param2): sum = int(param1) + int(param2) if sum % 2 == 0: print sum, ' is an even number' return sum
Function's Parameters 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
Default Argument Values 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("Bob", 55, True) register("Amy", married=True) register("Ken", age=12, married = False)
Keyword Arguments 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)
Arbitrary Argument Lists name argument is required age argument is optional infinite number of optional arguments def register(name, age=18, *args): print "Welcome", name.title() if age < 18: print "You are underage" for num, arg in enumerate(args): print "Argument #{0} is {1}".format(num, arg) If more that 1 argument given, 2nd one will always be assigned to age register("John") register("Jane", 21) register("Jeff", 21, None) register("Amy", 20, 30, 40, 50, 60) register("Steve", None, 42, "Hello")
Python function definitions Modules 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
Packages 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