In this tutorial you will learn the basics of Python and how to use functions. This will allow you to write a simple python program that you will then run. The program will be a python script run using IDLE
About this Tutorial –
Objectives –
Python is a powerful and popular object-oriented scripting language. This course provides a comprehensive introduction to the core syntax and functions provided by Python, including full coverage of its object-oriented features. The course also explores some of Python’s powerful APIs and techniques, including file handling, XML processing, object serialization, and Web service
Audience
This training course is aimed at new developers and experienced developers
Prerequisites
No previous experience in Python programming is required. But any experience you do have in programming will help. Also no experience in IDLE is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as C++ or C# would be useful but is not required.
Contents
The python course covers these topics and more:
- Strings and Regular Expressions: Overview of strings in Python; Basic string manipulation; Introduction to regular expressions
- XML Processing: XML essentials; Parsing XML documents; Searching for XML content; Generating XML data
- Web Services: Overview of Web services; Implementing Web services using Python; Caching; Compression; Handling redirects
Quick Access
Overview
Estimated Time – 1 Hour
Not what you are looking? Try the next tutorial – Data Structures
Lab 1: Getting started with functions
- Simple Functions
- Python allows you to define global functions, i.e. functions that don’t belong to a particular class.
- This is quite different from some other object-oriented languages, such as Java and C#, where all your functions must be defined as methods in a class.
- A function is a named block of code
- Starts with the def keyword…
- Followed by the name of the function…
- Followed by parentheses, where you can define arguments…
- Followed by a block, where you define the function body
def name_of_function(arg1, arg2, ..., argn) :
statements
statements
...
- Note the following additional points:
- You don’t specify a return type for functions in Python. The function can return a value, it’s just that you don’t have to declare the return type in the function signature.
- The parentheses after the function name are required, even if the function doesn’t take any arguments.
- The function body is a block of indented statements, similar to the way you write if-tests and loops in fact.
- To call a function
- Specify the function name…
- Followed by parentheses, where you can pass arguments
name_of_function(argvalue1, argvalue2, ..., argvaluen)
- Here’s an example of how to define and call simple functions
def say_goodmorning():
print("Start of say_goodmorning")
print(" Good morning!")
print("End of say_goodmorning\n")
def say_goodafternoon():
print("Start of say_goodafternoon")
print(" Good afternoon!")
print("End of say_goodafternoon\n")
def say_goodevening():
pass
# Usage (i.e. client code)
say_goodmorning()
say_goodafternoon()
say_goodevening()
f = say_goodmorning # Alias for say_goodmorning
f() # Calls say_goodmorning() really
print("THE END")
- This example defines three simple functions named say_goodmorning(), say_goodafternoon(), and say_goodevening().
- These functions are trivially simple at the moment – they don’t take any parameters and they don’t return a value explicitly.
- By way of example, the say_goodevening() function has an empty body at the moment. The pass keyword is just a placeholder for real functionality that the developer will presumably add sometime in the future.
- The bottom part of the code snippet shows how to call these functions. Note that if you forget the parentheses, it evaluates the name of the function but doesn’t actually invoke it. This can be a useful technique – it allows you to define an alias for a function. The last bit of code shows this:
f = say_goodmorning # Alias for say_goodmorning
f() # Calls say_goodmorning() really
- Python allows you to define global functions, i.e. functions that don’t belong to a particular class.
- Passing Arguments to a Function
- You can pass arguments to a function
- In the function definition, declare the argument names in the parentheses
- In the client code, pass argument values in the call
- Example:
def display_message(message, count):
for i in range(count):
print(message)
# Usage (i.e. client code)
display_message("Hello", 3)
display_message("Goodbye", 1)
- The example displays the following output:
Hello
Hello
Hello
Goodbye
- You can pass arguments to a function
- Returning a Value From a Function
- All functions in Python return a value. The default return value is None.
- If you want to return a specific value, use the return statement
- This causes the function to exit immediately, and control passes back to the client code
- Example
def display_message(msg):
print(msg)
def generate_hyperlink(href, text):
return "{1}".format(href, text)
def get_number_in_range(msg, lower, upper):
while True:
num = int(input(msg))
if num >= lower and num < upper: return num # Usage (i.e. client code) result1 = display_message("Hello world") print("result1 is %s" % result1) result2 = generate_hyperlink("https://www.bbc.co.uk", "BBC") print("result2 is %s" % result2) result3 = get_number_in_range("Favourite month? ", 1, 13) print("result3 is %s" % result3) - The example displays the following output:
Hello world
result1 is None
result2 is BBC
Favourite month? 100
Favourite month? -2
Favourite month? 8
result3 is 8
- All functions in Python return a value. The default return value is None.
- Understanding Scope
- Python allows you to define variables either inside or outside a function:
- If you declare a variable outside a function, then the variable is global to the module in which it is defined. Furthermore, it will be accessible to any code that imports the module as well. If you want to make the variable private to this module (so it can't be imported into other modules), then prefix the variable name with __. This is a Python idiom.
- If you declare a variable inside a function, then the variable is local to the function in which it is defined. Each function has its own local symbol table.
- If you want to access a global variable inside a function
- you must declare the global variable inside the function by using the global keyword
- This tells the Python interpreter that it's a global name - i.e. it tells Python not to create a local variable with this name
- Example
__DBNAME__ = None
def initDB(name):
global __DBNAME__
if __DBNAME__ is None:
__DBNAME__ = name
else:
raise RuntimeError("Database name has already been set.")
def queryDB():
print("TODO, add code to query %s" % __DBNAME__)
def updateDB():
print("TODO, add code to update %s" % __DBNAME__)
# Usage (i.e. client code)
initDB("Server=.;Database=Northwind")
queryDB()
updateDB()
- Note the following points in this example:
- First, we define a global variable named __DBNAME__ and set it to None. This is a convenient initial value for this variable - it allows us to declare the variable, even though we're not sure what value to assign it just yet. Note that the variable name starts with __, so it's private to this module.
- The initDB() function is intended to be a "database initialization" function. It takes a database name as an argument, and assigns it to the __DBNAME__ variable (as long as __DBNAME__ hasn't already been set). The global statement tells Python __DBNAME__ is a global variable, i.e. it already exists in global scope, so Python won't try to create it as a local variable just for this function.
- The queryDB() and updateDB() functions make use of the global __DBNAME__ variable. The implementations of these function is trivial at the moment.
- In the client code, we call initDB() to initialize the global __DBNAME__ variable. We then call queryDB() and updateDB() to perform some work on the database.
- Python allows you to define variables either inside or outside a function:
- Refactoring Python code to use functions
- In the Student folder, open dateprocessing.py in the editor. This is the solution code for the previous lab, so take a moment to familiarize yourself with the code
- Refactor the code so that it makes use of functions to improve modularity and readability. We suggest you define the following functions (and call them at the appropriate point in your code). This is the main exercise in this lab, so don't feel rushed:
- isLeapYear(year) - Takes a year as a parameter, and returns True or False to indicate it it's a leap year
def isLeapYear(year):
return ((year % 4 == 0) and not(year % 100 == 0)) or (year % 400 == 0)
- getDaysInMonth(month, year) - Takes numeric parameters for the month and year, and returns the number of days in that month
def getDaysInMonth(month, year):
if month == 2:
daysInMonth = 29 if isLeapYear else 28
elif month in (4, 6, 9, 11):
daysInMonth = 30
else:
daysInMonth = 31
return daysInMonth
- isValidDate(day, month, year) - Takes numeric parameters for the day, month, and year, and returns True or False to indicate it it's a valid date
def isValidDate(day, month, year):
return day >= 1 and day <= getDaysInMonth(month, year) and \ month >= 1 and month <= 12 and \ year >= 0 and year <= 2099 - getMonthName(month) - Takes a month number as a parameter, and returns the name of the month
def getMonthName(month):
if month == 1:
monthName = "January"
elif month == 2:
monthName = "February"
...
elif month == 11:
monthName = "November"
elif month == 12:
monthName = "December"
else:
monthName = "Not Known" # Should never happen
return monthName
- getDaySuffix(day) - Takes a day number as a parameter, and returns the suffix for that day number. For example, if the day number is 1, the method returns "st". If the day number is 2, the method returns "nd", and so on
def getDaySuffix(day):
if day in (1, 21, 31):
suffix = "st"
elif day in (2, 22):
suffix = "nd"
elif day in (3, 23):
suffix = "rd"
else:
suffix = "th"
return suffix
- displayAllDatesInMonth(month, year) - Takes numeric parameters for the month and year, and displays all the dates in that month and year. Display the dates in verbose format for now (e.g. 1st February 2014)
def displayAllDatesInMonth(month, year):
print("Dates in %s, %d" % (getMonthName(month), year))
for day in range(1, getDaysInMonth(month, year)+1):
print("%d%s %s %d" % (day , getDaySuffix(day), getMonthName(month), year))
- isLeapYear(year) - Takes a year as a parameter, and returns True or False to indicate it it's a leap year
- Run the program and verify that it all works correctly
Lab 2: Going further with functions
- Defining Default Argument Values
- If a function is particularly complicated or ultra-flexible, it might require a lot of argument values to be passed in from the client code.
- This can be quite onerous on the client - how does the client know what values to pass in for all the arguments?
- To simplify matters for the client code, the function definition can specify default values for some (or all) of its arguments
- The client code can then pass in just the argument values it wants to specify explicitly
- Example:
def book_flight(fromairport, toairport, numadults=1, numchildren=0):
print("\nFlight booked from %s to %s" % (fromairport, toairport))
print("Number of adults: %d" % numadults)
print("Number of children: %d" % numchildren)
# Usage (i.e. client code)
book_flight("BRS", "VER", 2, 2)
book_flight("LHR", "VIE", 4)
book_flight("LHR", "OSL")
- The example displays the following output:
Flight booked from BRS to VER
Number of adults: 2
Number of children: 2
Flight booked from LHR to VIE
Number of adults: 4
Number of children: 0
- If a function is particularly complicated or ultra-flexible, it might require a lot of argument values to be passed in from the client code.
- Variadic Functions
- Python allows you to define a function that can take any number of arguments
- In the function definition, prefix the last argument name with *
- Internally, these arguments will be wrapped up as a tuple
- You can iterate through the tuple items by using a for loop
- Example
def display_favourite_things(name, *things):
print("Favourite things for %s" % name)
for thing in things:
print(" %s" % thing)
# Usage (i.e. client code)
display_favourite_things("Andy", "Jayne", "Emily", "Thomas", 3, "Swans")
- The example displays the following output:
Favourite things for Andy
Jayne
Emily
Thomas
3
Swans
- Python allows you to define a function that can take any number of arguments
- Passing Keyword Arguments
- Client code can pass arguments by name
- Use the syntax argument_name = value
- Useful if the function has a lot of default argument values
- Client code can choose exactly which arguments to pass in
- Example
def book_flight(fromairport, toairport, numadults=1, numchildren=0):
print("\nFlight booked from %s to %s" % (fromairport, toairport))
print("Number of adults: %d" % numadults)
print("Number of children: %d" % numchildren)
# Usage (i.e. client code)
book_flight(fromairport="BRS", toairport="VER", numadults=2, numchildren=2)
book_flight("LHR", "CDG", numchildren=2)
book_flight(numchildren=3, fromairport="LGW", toairport="NCE")
- The example displays the following output:
Flight booked from BRS to VER
Number of adults: 2
Number of children: 2
Flight booked from LHR to CDG
Number of adults: 1
Number of children: 2
Flight booked from LGW to NCE
Number of adults: 1
Number of children: 3
- Client code can pass arguments by name
- Lambda Expressions
- Lambda expressions are handy when you have a short algorithm that you want to define and then invoke at some later time
- A lambda expression is a 1-line inline expression
- Like an anonymous function
- To define a lambda expression:
- Use the lambda keyword...
- Followed by the argument list...
- Followed by a colon...
- Followed by a 1-line inline expression
my_lambda = lambda arg1, arg2, ... argn : inline_expression
- To invoke a lambda expression:
- Same syntax as a regular function call
my_lambda(argvalue1, argvalue2, ..., argvaluen)
- Same syntax as a regular function call
- Example of lambda expressions:
def do_binaryop(msg, n1, n2, op):
res = op(n1, n2)
print("%s %g" % (msg, res))
# Usage (i.e. client code)
addlambda = lambda a, b: a + b
sublambda = lambda a, b: a - b
do_binaryop("Sum", 10, 7, addlambda)
do_binaryop("Diff", 10, 7, sublambda)
do_binaryop("Mult", 10, 7, lambda a, b: a * b)
do_binaryop("Div", 10, 7, lambda a, b: a / b)
- This example shows how to define and invoke lambda expressions. Note the following points about the do_binaryop() function:
- The do_binaryop() function expects to receive a lambda expression as its final parameter. The lambda expression is like a mini-function - it represents an algorithm to be performed when we're ready.
- Inside do_binaryop(), we invoke the lambda expression represented by the op argument. Note that the syntax for invoking a lambda expression is exactly the same as for invoking a normal function
- First we create a couple of lambda expressions indicating how to add and subtract a pair of values. We assign these lambda expressions to a couple of local variables - these local variables are a bit like function pointers in C or C++, or delegates in C#. We then call do_binaryop() twice, passing the lambda expression variables as arguments.
- Next we create a couple of lambda expressions inline, as part of our calls to the do_binaryop() function. This is a convenient short-cut if you have an algorithm that you want to use just once.
- Defining and using default arguments
- Enhance the displayAllDatesInMonth() function so that it takes an optional argument named verbose, and set the default value to False. Refactor the function so that it tests this flag, and outputs dates in verbose format or non-verbose format accordingly:
- Verbose format: 1st February 2014
- Non-verbose format: 01/02/2014
def displayAllDatesInMonth(month, year, verbose=False):
print("Dates in %s, %d" % (getMonthName(month), year))
for day in range(1, getDaysInMonth(month, year)+1):
if verbose:
print("%d%s %s %d" % (day , getDaySuffix(day), getMonthName(month), year))
else:
print("%02d/%02d/%04d" % (day , month, year))
- Invoke displayAllDatesInMonth() function from the client code, with or without a value for the verbose argument. Verify that the program outputs dates in the appropriate format
#Ask the user for a day, month, and year.
day = int(input("Enter a day (1-31): "))
month = int(input("Enter a month (1-12): "))
year = int(input("Enter a year (0 to 2099): "))
print("%02d/%02d/%04d valid? %s" % (day, month, year, isValidDate(day, month, year)))
# Display all dates in month (first verbose, then not verbose)
displayAllDatesInMonth(month, year, True)
displayAllDatesInMonth(month, year)
- Enhance the displayAllDatesInMonth() function so that it takes an optional argument named verbose, and set the default value to False. Refactor the function so that it tests this flag, and outputs dates in verbose format or non-verbose format accordingly:
- Just a little extra if you have the time
- Write a function named displaySpecialDatesInMonth(). This function should be similar to displayAllDatesInMonth(), except that it takes a variadic list of day numbers. The idea is that these days are special days in the month (birthdays, anniversaries, important football games, etc.). The function should also allow the user to display the dates in verbose or non-verbose mode.
- For example, client code should be able to call the function as follows, to display important days in December for the current year (in verbose mode):
displaySpecialDatesInMonth(12, year,
3, 25, 26, 31,
verbose=True)
- For example, client code should be able to call the function as follows, to display important days in December for the current year (not in verbose mode):
displaySpecialDatesInMonth(12, year,
3, 25, 26, 31)
- An Example solution could look like this:
def displaySpecialDatesInMonth(month, year, *specialDays, verbose=False):
print("Special dates in %s, %d" % (getMonthName(month), year))
for day in specialDays:
if verbose:
print("%d%s %s %d" % (day , getDaySuffix(day), getMonthName(month), year))
else:
print("%02d/%02d/%04d" % (day , month, year))
- When you get all this working, if you have a bit of time left over, have a go at writing some lambda expressions and call them in your code
Well done. You have completed the tutorial in the Python course. The next tutorial is
5. Data Structures
Copyright © 2016 TalkIT®
If you would like to see more content like this in the future, please fill-in our quick survey.