GETTING STARTED WITH  Python

Created by Juan Manuel Torres / @onema

LIsts

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. [1]

Example

#!/usr/local/bin/python3.5
# 08lists.py

my_list = [
    "array",
    "123",
    [1, 2, 3]
];

for value in my_list:
    print(type(value))
    print(value)

#
print('Count: {}'.format(len(my_list)))

my_list.append('Some value')
print('Count: {}'.format(len(my_list)))

my_list.insert(1, 'Inserting value at index 1')
new_index = my_list.index('Inserting value at index 1')
print('The index of the new inserted item is: {}'.format(new_index))

List can be used as queues

#!/usr/local/bin/python3.5
# 09queues.py

from collections import deque

queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.append("Graham")          # Graham arrives
queue.popleft()                 # The first to arrive now leaves
queue.popleft()                 # The second to arrive now leaves
                                # Remaining queue in order of arrival
for name in queue:
    print(name)

But they can be very inefficient because insertions or pops from the beginning of the list require a shift in all the elements of the list.  

Use a "deque" instead

Dictionaries

Also called "Associative Arrays" in other languages,

dictionaries are indexed by keys that can be of any, which can be any immutable type; strings and numbers can always be keys [2]

What are Dictionaries good for?

Think of an dictionaries as a specialized way of organizing and storing data.

#!/usr/local/bin/python3.5
# 10dictionaries.py

from collections import OrderedDict

menu = {
    'shake': [
        'vanilla ice cream',
        'milk'
    ],
    'tiramisu': [
        'instant-espresso powder',
        'sugar',
        '4 large egg',
        'heavy cream'
    ],
    'burger': [
        'beef patty',
        'lettuce',
        'tomatoes',
        'buns'
    ],
}
#a = OrderedDict(sorted(menu.items(), reverse=True))
a = sorted(menu.items(), reverse=True)
for key in a:
    print(key)

Flow Control or Control Structures

So far we have created programs that have no logic, they follow a straight line. 

 

Control Structures are used to build logic into our programs.

Control Structures in Python

Python supports several control structures but we will only look into the following:

  • If statements
  • Else statements
  • Elif (Else If) statements
  • For loops
  • Break
  • Continue
  • Pass

If Statements

If is a condition to check if something is true

#!/usr/local/bin/python3.5
# 12conditionals.py
import random


number = random.randint(0,9)
if number == 1:
    print ('The number variable is equal to one.')
elif number == 2:
    print('The number variable is equal to two.')
else:
    print('OK, I give up, I have no idea what the number is :P')

str_val = 'Foo Bar'
if str_val.find('Foo') != -1:
    print('The string "{0}" contains the word "Foo"'.format(str_val))

if 'Bar' in str_val:
    print('The string "{0}" contains the word "Bar"'.format(str_val))

Loops

A loop allows us to repeat a piece of code many times. 

Each time we loop we can make small changes to our program in order to get a desired output.

Loops

Imagine you want to print all the numbers from 1 to 10

#!/usr/local/bin/python3.5
# 13whileloop.py
i = 0
while i < 10:
    print(i)
    i += 1


print('Done!')

Loops can be used to iterate over arrays

#!/usr/local/bin/python3.5
# 14forloop.py

min = 0
max = 10

# Iterating over a range
for number in range(min, max):
    print(number)

# Iterating over lists
count = [20, 40, 60, 80, 100]
for number in count:
    print(number)

# Iterating over dictionaries
count = {
    'one': 'uno',
    'two': 'dos',
    'three': 'tres'
}
# For dictionaries you must use the items method to iterate over it
for english_key, spanish_value in count.items():
    value = '{} = {}'.format(english_key, spanish_value)
    print(value)

Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Example

#!/usr/local/bin/python3.5
# 15function.py

def main():
    for n in range(1, 20):
        isprime(n)


def isprime(n):
    if n == 1:
        print("1 is special")
        return False
    for x in range(2, n):
        if n % x == 0:
            print("{} equals {} x {}".format(n, x, n // x))
            return False
    else:
        print(n, "is a prime number")
        return True

if __name__ == 'main': main()

Generators

#!/usr/local/bin/python3.5
# 16generators.py

def generator():
    yield 'One'
    yield '2'
    yield 'Three'
    yield '4'

for value in generator():
    print(value)

Generators functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

A generator yields items instead of returning them.

Time to Code

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:


1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...


By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. [5] https://projecteuler.net/problem=2


Solution must be recursive

 

Homework

 

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

 

Find the sum of all the primes below two million.

https://projecteuler.net/problem=10

 

References

questions?

THE END

Juan Manuel Torres | @onema

getting-started-with-python

By Juan Manuel Torres

getting-started-with-python

  • 1,594