knowledge-kitchen

Python - A Blast Through the Programming Language

Database Design

  1. Overview
  2. Values, variables & literals
  3. Conditionals
  4. Functions
  5. Loops
  6. Strings
  7. Lists
  8. Tuples
  9. Dictionaries
  10. Conclusions

Overview

Concept

A fast and furious blast through programming in Python.

Values, variables & literals

Values

What is a value?

The representation of some element that can be manipulated by a program.

-Wikipedia

Data types

Python supports values in a variety of types:

Data structures

Python also includes some built-in data structures that can group a bunch of values.

Obtaining a value

Values can be obtained by any of the following:

Variable

A variable is a labeled reference to a value.

foo = 4
bar = 3.14
baz = False
bum = "My name is Inigo Montoya!"

The signifiers on the left of the = sign are assigned the value on the right.

Conditionals

Designing truth

With conditional logic, a given block of code can be designed to run only if certain conditions are met.

import datetime
today = datetime.datetime.today().weekday() # the day of the week as an int
if today == 1:
    print("Oh, Monday!")
if input("What's your name?") == "My name is Inigo Montoya!":
    print("Oh, no!")
elif 3.14 == 4:
    print("You're never going to get this!")
else:
    print("You might get this!")

Indentation is important.

Functions

Reusable blocks of code

Functions allow blocks of code to be reused throughout a program without rewriting the block of code more than once.

import random

def random_fortune():
    possible_fortunes = [
        "See the light at the end of the tunnel.",
        "There is time to be practical now.",
        "Nothing is as good or bad as it appears.",
        "Be calm when confronting an emergency crisis."
    ]
    random_index = random.randint( len(possible_fortunes) - 1 )
    print( possible_fortunes[ random_index ] )

In order for the block of code within the function definition to be executed, the function must be explicitly called from somewhere else in the code.

random_fortune()

Return values

All functions return a value. Sometimes that value is useful, sometimes not, depending upon the intended use of the function.

By default, Python functions return None - a special value of the otherwise-useless data type NoneType.

useless = random_fortune()
print(useless) # outputs None, since that's what random_fortune() returned
useless = print("Wow, I love programming!") # prints out, "Wow, I love programming!"
print(useless) # prints out None, since that's what the print function returned
print( "Your random fortune is: " + random_fortune() )
# first prints out a random fortune message, e.g. "There is time to be practical now."
# then prints out "Your random fortune is: None", since random_fortune() returned None

Useful return values

Explicitly declare a function’s return value to override the default None.

def random_fortune():
    possible_fortunes = [
        "See the light at the end of the tunnel.",
        "There is time to be practical now.",
        "Nothing is as good or bad as it appears.",
        "Be calm when confronting an emergency crisis."
    ]
    random_index = random.randint( len(possible_fortunes) - 1 )
    return possible_fortunes[ random_index ]

The return value can now be used elsewhere in the code.

print( "Your random fortune is: " + random_fortune() )
# prints out "Your random fortune is: There is time to be practical now.", or another random fortune

Paramaters and arguments

Functions can be designed with parameters - unassigned variables (i.e. variables with no value).

def add( x, y ):
    sum = x + y
    return sum # how can you return the sum of two unassigned variables?!

x and y do have values assigned to them when the function is called with arguments.

result = sum( 10, 20 )
print( result ) # prints 30

Loops

Iterating

Loops allow a block of code to be executed several times in sequence, if desired. There are two types: for and while.

strange_animals = ['platypus', 'meerkat', 'echidna']
for strange_animal in strange_animals:
    print( strange_animal )
i = 0
while i < len(strange_animals):
    strange_animal = strange_animals[i]
    print( strange_animal )
    i = i + 1

Infinite loops

A while loop will iterate infinitely, unless the boolean condition upon which it rests evaluates to a logical False.

some_condition = True
while some_condition:
    response = input('Hey')
some_condition = True
while some_condition:
    response = input('Hey')
    some_condition = response != 'Hey'

Strings

Manipulating text

There are lots of built-in Python functions related to text.

animal = "platypus"

Indexing characters

Individual characters within a string can be accessed by index numbers.

animal = "platypus"

Negative index numbers start from the end of the string and go backwards.

Slicing

A new string can be generated from a slice of an existing string.

animal = "platypus"

Lists

Concept

A list is a group of values, all bundled up together.

animals = [ 'platypus', 'meerkat', 'echidna' ]
random_assortment = [
    'gorgonzola',
    12,
    False,
    2.99,
    { 'this': 'that' },
    [1,2,3],
    None
]

Modifier functions

There are lots of built-in Python functions related to modifying what is stored in lists.

animals = [ 'platypus', 'meerkat', 'echidna' ]

Indexing list values

Individual values within a list can be accessed by index numbers.

animals = [ 'platypus', 'meerkat', 'echidna' ]

Negative index numbers start from the end of the string and go backwards.

Any existing list index can have its value reassigned.

Slicing

A new list can be generated from a slice of an existing list.

fibonacci_sequence = [ 0, 1, 1, 2, 3, 5, 8, 13, 21 ]

Tuples

Tuples

Tuples are a list-like data structure that is immutable.

fibonacci_sequence = ( 0, 1, 1, 2, 3, 5, 8, 13, 21 )

Dictionaries

Key-value pairs

Dictionaries establish a relationship between a key and a value.

person = {
    'first_name': 'Foo',
    'last_name': 'Barstein',
    'age': 15
}

A value can then be looked up by its corresponding key.

print( "Hello " + person['first_name'] + "!")

And any key can have its value reassigned.

person['last_name'] = 'Bazberger'

Even new keys, e.g. person['is_over_21'] = True

Lists of keys, lists of values

It is possible to extract a list of the keys in a dictionary using a dictionary’s .keys() function.

person = {
    'first_name': 'Foo',
    'last_name': 'Barstein',
    'age': 15
}
list_of_keys = list( person.keys() )

Similarly, it is possible to generate a list of the values in the dictionary.

list_of_values = list( person.values() )

Looping through keys or values

There are several ways to loop through the keys or values of a dictionary.

person = {
    'first_name': 'Foo',
    'last_name': 'Barstein',
    'age': 15
}

Loop through just the keys.

for key in person.keys():
    print(key)

Loop through just the values.

for value in person.values():
    print(value)

Looping through keys and values

One can also loop through the keys and the values at once using a dictionary’s .items() function.

person = {
    'first_name': 'Foo',
    'last_name': 'Barstein',
    'age': 15
}
for key, value in person.items():
    print(key, '-', value)

Conclusions

Thank you. Bye.