Beginner introduction to Python – Part 2

Al-rite so lets continue where we left off. The example repository is here for reference.

Seven.py

We iterate through lists using for loops in python.

countDown = [9, 8, 7, 6]

for number in countDown:
  print(number)

for item in countDown:
  print(item)

The for in loop in python takes the variable you want to print and the list you are iterating over. You can call the number variable above anything you like. The second example uses item as the variable. countDown is the list of course.

The range function creates a list of numbers that we can iterate over. It usually starts at zero. Using the for in loop and a range function we can create a list of numbers.

# output 0 1 2 3 4 5
for x in range(6):
 print(x) 

You can start the range function at a certain number and tell it when to stop. Below the range starts at three and ends at seven. So the last number we get is 6.

# output 3 4 5 6
for x in range(3, 7):
 print(x)

We can also tell the range function how many steps to take when going to the next number. Below the counter starts at 6 and skips two and outputs 8 and ends because it is supposed to end at 10.

# output 6 8
for x in range(6, 10, 2):
  print(x)

The while loop does what a while loop does :). The format is shown below.

# output 1 2 3 4 5 6 7 8 9
myAge = 0
while myAge >= 0:
    print(myAge)
    myAge += 1
    if myAge == 10:
      break

Notice we can we put an if statement in this while loop. The break out condition occurs if myAge is equal to 10. Calling break ends the while loop.

In a while loop we can use the continue statement to skip a loop.

# output 0 1 2 3 4 6 7 8 9
for x in range(10):
    if x == 5:
        continue
    else:
      print(x)

Above we skip the number five in the range and continue to the next number which is six.

Eight.py

Now lets get into some functions. Create a function in python requires a def statement.

A simple function is show below.

puppyName = "bobby"

# simple function
def show_puppy_name():
  print(puppyName)

# Adding arguments
def add_two_numbers(number1, number2):
 print(number1 + number2)

show_puppy_name() # calling function
add_to_numbers(1,3)  # calling function with arguments

After the def statement you name your function and put in your brackets. After the colons you can begin working in your function. If you want to add arguments to your function place them within the brackets.
Calling your functions is simple just call the name of your function as expected.

Nine.py

Creating a class is pretty straight forward. We created a Dog class for an example. An excerpt of this is show below.

class Dog:
    name = "Dog"
    _bark = "roof roof roof"
    _color = "black and white"
    _waggingTail = "wagging tail"
    _age = 0;

    def __init__(self, bark, color):
        self._bark = bark
        self._color = color

    def set_bark(self, bark):
        self._bark = bark

    def make_noise(self):
        return self._bark

So at the top we have our class variables. Then we have two functions. One is special called __init__. This allows you to set attributes when you create the class object or perform any other initialization actions you like. The second function set_bark is a method of the class it basically sets the dog bark variable. With the above we can now use this class.

dog = Dog("roof", "blue and black")
print(dog.make_noise())

So we can cause the dog to make a noise by calling the make noise function. But first we create the dog object and add two parameters in the object constructor which calls the __init__ function and sets those attributes.

The class functions takes in a argument called self however we don’t need to use that attribute when executing our class functions. When creating class functions we need to add the self argument though.

Ten.py

Here we create dictionaries in python which we would know as keyed arrays, associative arrays or a map in other languages. A simple dictionary is shown below. It basically is comma separated key values pair delimited with curly braces.

numbers = {}
numbers["one"] = 1
numbers["two"] = 2
print(numbers)
#output {'one': 1, 'two': 2}

We can create a dictionary in different ways.

cars = {
    'mazda': "red",
    "toyota": "blue",
    "benz": "black"
}

And add different type of variables in them, however the keys need to be immutable.

phonebook = {
    "barney": 123456,
    "fred": 554533,
    "carry": 532903444,
    "penny": 53434
}

We can loop through a dictionary using the for in loop. We have to specify the key and the value and called items function on the dictionary.


gps = {
    "Home": '14.75 23.43',
    'Car': '24.33 05.43',
    'Dog': '43.52 45.23'
}

for object, location in gps.items():
  print(object + " is located at " + location + "")

The key is named object the value is named location and we call gps.items() to get all the items in the dictionary.

We can also check to see if something is inside a dictionary.


pets = {
    "dog": "bobby",
    "cat": "Bella",
    "horse": "White Thunder",
}

if "dog" in pets:
  print("I have a dog named " + pets["dog"])

The if in statement accomplishes this. If we wanted to check that something is not in pets we do the following

if "horse" not in pets:
  print("i no longer have a horse")

We can delete and push out the objects in a dictionary.

reservations = {
    "Ken": '10pm',
    "Ben": "2pm",
    "Urella": "3pm"
}

del reservations["Ken"] # remove ken from the reservations list

The del statement on the reservations value will remove it from the dictionary. We can also push and item off a dictionary and get that value.

pets = {
    "dog": "bobby",
    "cat": "Bella",
    "horse": "White Thunder",
}

To get the horse from above and remove it from the dictionary we do

horseName = pets.pop("horse")

If we print the pets dictionary the horse index will no longer be there.

Eleven.py

Dealing with imports is what the eleventh py file is all about.

We can import modules like

import math
import statistics
import twelve
import twelve as t
import urllib.request

Above we have imported math, statistics, twelve, twelve as t and urllib.request. Urllib is actually a package and that’s another story. But we take the module from the package.

Modules in python are just other python files.

To use the math import we do the following

print(math.pi)
print(math.log(10))
print(math.pow(2, 4))
print(math.sqrt(100))

We can call the module and access its functions. To call the statistics module we do

print(statistics.mean([2, 5, 6, 9]))
print(statistics.median([1, 2, 3, 8, 9]))

To access twelve which is just another file with functions we do

print(twelve.hello_world())
print(twelve.good_by_world())

We can inspect the twelve.py files to see what it has in it.


def hello_world():
    return "Hello World"


def good_by_world():
    return "Good Bye World"

Not much, just two functions.

We can use t to access these functions as well since we imported the twelve module as t.

import twelve as t

print(t.hello_world())

We can import part of a module. Below we import request from the urllib library.

import urllib.request


html = urllib.request.urlopen('https://wftutorials.blog/about/')
print(html.read())

We can import all the functions from a module like below. We can use functions from the file now.

from twelve import *

print(hello_world())
print(good_by_world())

We can also import a function – singular – from a module. This is shown below.

from twelve import hello_world

print(hello_world())

Above we import the function hello_world from twelve and we call it like a normal function.

Conclusion

We now have a better understanding of the python language. Next I will create some examples of what it can do. More real world examples so that I can get a better hang of the language.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s