python-101



python-101

1 0


python-101

Slides for a Python 101 workshop for PyLadies Singapore in December 2015

On Github mbrochh / python-101

Python 101

Your first little steps with the Python programming language

Press SPACE or SHIFT+SPACE to move through the slides...

Who am I?

Thank you, Red Hat & PayPal Singapore ♡ ♡ ♡

Big thanks to Red Hat & PayPal Singapore for kindly hosting this event and for sponsoring pizza and softdrinks.

We have a Slack.com community!

PyLadiesSG has a community on Slack. Myself and others are idling there permanently and we are happy to mentor anyone who needs help.

Visit pyladies-sg-slackin.herokuapp.com if you are based in Singapore and if you would like an invite.

Follow along!

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

What are we going to do today?

  • Learn a bit about Python in general
  • Learn how to execute a Python script
  • Write a little Python program and execute it

A future-birthday calculator

  • Let's write a silly program today!
  • We want to call our program with a birthday and an age:
    python birthday.py 1982-09-08 10
  • It should print the weekday for each birthdays up to the given age
  • The output should look like this:
    I will turn 1 on Thursday, 1983-09-08
    I will turn 2 on Saturday, 1984-09-08
    I will turn 3 on Sunday, 1985-09-08
    I will turn 4 on Monday, 1986-09-08
    I will turn 5 on Tuesday, 1987-09-08
    I will turn 6 on Thursday, 1988-09-08
    I will turn 7 on Friday, 1989-09-08
    I will turn 8 on Saturday, 1990-09-08
    I will turn 9 on Sunday, 1991-09-08
    I will turn 10 on Tuesday, 1992-09-08
    

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Python In A Nutshell

  • Invented by Guido van Rossum in the late 1980s
  • Very easy to read syntax
    • Uses plain English for many functions and operators
    • Uses four spaces of indentation for code blocks
    • Has a comprehensive style guide: PEP8
    • No unnecessary special characters, like semicolons at the end of the line

Python In A Nutshell

  • Python is not a compiled language, but an interpreted language
  • This means, in order to run a Python script, you need to install the Python interpreter
  • Pro: You never need to compile your code.
  • Con: If you want to install your software on other people's computers, they need to install the interpreter as well.

Python In A Nutshell

  • Python is not the fastest language
    • If you want to write a game, better use C
  • Python is not the safest language
    • If you want to fly a rocket to Mars, ask Elon Musk what he is using
  • Python is a very readable, learnable and maintainable language
    • If you want to build a business, use Python

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Using Cloud9 IDE

  • Setting up Python on your local computer can be time consuming
  • We have a Python Introduction workshop to help with this
  • For this workshop we will save some time and just use Cloud9 IDE
  • Create an account at http://c9.io
  • Create a new workspace "pyladies-python101"

How to Execute a Python Script

  • Open your workspace in Cloud9 IDE
  • Rightclick at the workspace name in the left sidebar
  • Chose "New file" and name it "test.py"
  • Doubleclick the new file to open it
  • Enter the following code:
    print("Hello World")
  • Save the file
  • Press the green "Run" button at the top

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Variables

  • Every program needs to store data in memory
  • We use Variables to remember values and use them later
  • The syntax for defining a variable is this:
    variable_name = 1
    message = "Hello World!"
    is_simple = True
    something = None

Exercise

  • Let's create a file called birthday.py
BIRTHDAY = "1982-09-08"
print(BIRTHDAY)
  • Always run your script after each exercise!

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Strings

  • Strings are the most common data type
    • Some programming languages also have Char as a data type
    • A char is a single character
    • Therefore, a whole word, is a long string of characters
  • The syntax for defining a string is this:
    variable_name = "Your string"

Strings

  • Like all things in Python, Strings are also Objects
  • For this workshop we will not worry about Objects.
  • Just remember one thing: Objects usually have useful methods
  • Strings have a ton of useful methods
  • You can call string methods like this:
    my_string = "Hello World!"
    my_string = my_string.upper()
    print(my_string)
    
  • The output should look like this:
    > HELLO WORLD!

Strings

  • One especially useful method of the String object is format()
  • It allows you to add placeholders into your strings
  • Then you can fill in variable values into those placeholders
  • It looks like this:
    my_age = 33
    my_string = "I am {} years old".format(my_age)
    print(my_string)
    
  • The output should look like this:
    > I am 33 years old

Exercise

  • Change birthday.py to look like this:
BIRTHDAY = "1982-09-08"
message = "I am born on {}".format(BIRTHDAY)
print(message)

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Input

  • Command Line Programs often take arguments as input
  • This way you pass in data into the program
  • For example the python command takes a filename as a parameter:
    python birthday.py
  • We can even pass in more than one argument:
    python birthday.py 1982-09-08

Imports

  • Python has an extensive Standard Library
  • We can use things from that library by importing them at the top of our files:
    import datetime
    now = datetime.datetime.now()
    print(now)
    
  • The output should be the current date and time:
    > 2015-12-08 02:19:15.529046

Exercise

  • With this new knowledge we can extend birthday.py a bit...
  • Let's make it so that we pass in the date via the command line
  • Make it look like this:
import sys

BIRTHDAY = sys.argv[1]
message = "I am born on {}".format(BIRTHDAY)
print(message)
  • Try to press the "Run" button

Exercise

  • Whoops! Pressing the "Run" button generates an error:
    • "IndexError: list index out of range"
  • This is because our program now expects one command line argument
  • From now on, we will execute our script from the Terminal
  • Press "ALT+T" to open a new Terminal
  • Enter
    python birthday.py 2015-01-01
  • Leave that tab open, we will run our program from here from now on

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

The If-Statement

  • You need to control the program flow in your programs
  • That means, if some condition is true, then certain code should be executed
  • If it is not true, either nothing should happen or some other code should be executed
  • The If-Statement helps you to do this:
    if 1 > 2:
      print("One is bigger than two")
      # This code is actually never reached
    else:
      print("One is not bigger than two")
    
  • The output should be:
    > One is not bigger than two

Exercise

  • Let's build some error handling into our birthday.py
import sys

if len(sys.argv) < 2:
    print("ERROR: Please provide a date")
else:
    BIRTHDAY = sys.argv[1]
    message = "I am born on {}".format(BIRTHDAY)
    print(message)
  • By the way: "len" is a built-in function to return the length of a list
  • ...and "sys.argv" is just a list of command line arguments
  • The first argument is always the Python script filename
  • The second argument is supposed to be birthdate

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Datetimes

  • The built-in datetime module has three important classes: date, datetime and timedelta
  • We can use these classes to do powerful things with date calulations
  • In order to use the module, you need to import it
  • This is how you create a datetime object:
import datetime
my_date = datetime.datetime(2015, 12, 08)
print(my_date)
  • The output should be:
    2015-12-08 00:00:00

Datetimes

  • The datetime.datetime class has a powerful function called strptime
  • It helps you to turn a string into a datetime object:
  • You can learn more about the formatting options here

import datetime
my_string = "2015-12-08"
my_date = datetime.datetime.strptime(my_string, "%Y-%m-%d")
print(my_date)

  • The output should be:
    2015-12-08 00:00:00

Datetimes

  • There is much more you can do with datetimes
  • For example, you can get the weekday number for any date:

import datetime
my_date = datetime.datetime(2015, 9, 8)
print(my_date.isoweekday())

  • The output should be:
    2
  • Because it's Tuesday, the second day of the week

Exercise

  • Let's convert the birthdate input string into a datetime object
import sys
from datetime import datetime

if len(sys.argv) < 2:
    print("ERROR: Please provide a date")
else:
    BIRTHDAY = datetime.strptime(sys.argv[1], "%Y-%m-%d")
    message = "I am born on {}".format(BIRTHDAY.date())
    print(message)

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Exception Handling

  • Sometimes you can't avoid program crashes
  • Especially when your program accepts user input
  • You can use try-except blocks to handle exceptions:
    value1 = 1
    value2 = 0
    try:
      result = value1 / value2
    except ZeroDivisionError:
      print("ERROR: You can't divide by zero")
    
  • The output should be:
    > ERROR: You can't divide by zero

Exercise

  • Let's make sure that the date is formatted correctly:
import sys
from datetime import datetime

if len(sys.argv) < 2:
    print("ERROR: Please provide a date")
else:
    try:
        BIRTHDAY = datetime.strptime(sys.argv[1], "%Y-%m-%d")
    except ValueError:
        print("ERROR: Please enter a correct date")
        sys.exit()
    message = "I am born on {}".format(BIRTHDAY.date())
    print(message)
  • By the way: "sys.exit()" stops the program

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Functions

  • You can group code into functions
  • You can then call your function many times and therefore re-use your code
  • Functions accept arguments and keyword arguments
  • Functions have return values
  • You can define a function like this:

def function_name(arg1, arg2, kwarg1=None, kwarg2=None):
  result = arg1 + arg2
  return result

  • You can call a function like this:

result = function_name(1, 2, kwarg1="Hello"):
print(result)

Exercise

  • Let's create a function that adds some years to a given date
import sys
from datetime import datetime, date

def get_future_date(base_date, years):
    future_date = date(
        base_date.year + years,
        base_date.month,
        base_date.day
    )
    return future_date

if len(sys.argv) < 3:
    print("ERROR: Please provide a date and an age")
else:
    try:
        birthday = datetime.strptime(sys.argv[1], "%Y-%m-%d")
    except ValueError:
        print("ERROR: Please enter a correct date")
        sys.exit()
    years = int(sys.argv[2])
    future_date = get_future_date(birthday, years)
    message = "I will turn {} on {}".format(years, future_date)
    print(message)

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Lists

  • You can define an empy list like this
    my_variable = []
  • You can store many values into lists
    my_variable = [1, 2, 3]
  • You can add or remove items from lists
    my_variable.append(4)
    my_variable.remove(4)
  • You can access an item in the list by it's index:
    my_variable[1]
    # This should return `2`, because lists are zero-indexed
    
  • Find out more about lists here

Lists

  • Here is a little example of things you can do with lists:
numbers = [1, 2, 3]
more_numbers = [4, 5, 6]
all_numbers = numbers + more_numbers
print(all_numbers)
all_numbers.reverse()
print(all_numbers)
all_numbers.append(7)
print(all_numbers)
all_numbers.sort()
print(all_numbers)
  • The output should look like this:
    [1, 2, 3, 4, 5, 6]
    [6, 5, 4, 3, 2, 1]
    [6, 5, 4, 3, 2, 1, 7]
    [1, 2, 3, 4, 5, 6, 7]
    

Tip: The Range Function

  • "range()" is a built-in function
  • It generates a list of numbers for you:
    my_list = range(100)
    my_other_list = range(1, 100, 1)
    print(my_list)
    print(my_other_list)
    

Loops

  • You often need to repeat the same code in a loop
  • Loops look like this:
var my_list = [1, 2, 3, 4]

for my_number in my_list:
    if my_number == 1:
        continue
    print (my_number)
  • You can use "continue" to skip this iteration of the loop

Exercise

  • Let's extend the output of our program so that it shows all future birthdays up to the provided age
import sys
from datetime import datetime, date

def get_future_date(base_date, years):
    future_date = date(
        base_date.year + years,
        base_date.month,
        base_date.day
    )
    return future_date

if len(sys.argv) < 3:
    print("ERROR: Please provide a date and an age")
else:
    try:
        birthday = datetime.strptime(sys.argv[1], "%Y-%m-%d")
    except ValueError:
        print("ERROR: Please enter a correct date")
        sys.exit()
    years = int(sys.argv[2])
    years_list = range(1, years + 1, 1)
    for year in years_list:
        future_date = get_future_date(birthday, year)
        message = "I will turn {} on {}".format(year, future_date)
        print(message)

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

Dictionaries

  • Dictionaries are so called "key-value-stores"
  • You can define an empty dictionary like this:
    my_dict = {}
  • You can also define it with initial values:
my_dict = {
    "Martin": 33,
    "Eva": 24,
}
  • You can access an item by it's key:
    martins_age = my_dict["Martin"]

Exercise

  • Let's add the final piece to our program
  • We will write a function that returns the weekday name for a given weekday number
import sys
from datetime import datetime, date

def get_weekday_name(weekday_number):
    weekdays = {
        1: "Monday",
        2: "Tuesday",
        3: "Wednesday",
        4: "Thursday",
        5: "Friday",
        6: "Saturday",
        7: "Sunday",
    }
    return weekdays[weekday_number]

def get_future_date(base_date, years):
    future_date = date(
        base_date.year + years,
        base_date.month,
        base_date.day
    )
    return future_date

if len(sys.argv) < 3:
    print("ERROR: Please provide a date and an age")
else:
    try:
        birthday = datetime.strptime(sys.argv[1], "%Y-%m-%d")
    except ValueError:
        print("ERROR: Please enter a correct date")
        sys.exit()
    years = int(sys.argv[2])
    years_list = range(1, years + 1, 1)
    for year in years_list:
        future_date = get_future_date(birthday, year)
        weekday = get_weekday_name(future_date.isoweekday())
        message = "I will turn {} on {}, {}".format(year, weekday, future_date)
        print(message)

Table of Content

  • Introduction
  • Python In A Nutshell
  • Cloud9 IDE
  • Variables
  • Strings
  • Input & Imports
  • The If-Statement & Type-casting
  • Datetimes
  • Exception Handling
  • Functions
  • Lists & Loops
  • Dictionaries
  • What's Next?

What's Next?

Python 101 Your first little steps with the Python programming language Press SPACE or SHIFT+SPACE to move through the slides...