Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

Variables


As we know, variables are references to values in memory.

Variables in Python can reference values of different data types such as strings, integers, floating point values, Booleans, and different data types and data structures, as we'll see later on in this book. Python, in contrast to statically typed languages such as Java or C++, doesn't require you to pre-declare a variable's data type. It determines the type during runtime.

You can think of a variable as a box with a named label on it. The box on its own has no value but becomes valuable once you put something inside it. The box represents the things inside it and, similarly, a variable is used to represent the value inside it.

Additionally, a variable's value and type can change during runtime. Any variable can be used to store any data type and can be used as long as it has already been defined. Before we begin taking a look at how to assign variables to values, let's briefly go over the different types of values/data types we've encountered thus far and the ones we'll be dealing with in this chapter.

Values

Python supports several different types of values. These values are what variables can be assigned to. Thus far, we've encountered, strings and numeric values such as integers.

Numeric Values – Integers

Mathematically, integers are whole numbers that are either positive or negative. The same definition is applicable for Python integers.

Here is an example of an integer expression in Python. As we saw earlier, Python echoes whatever you write in the interactive shell:

Python 3.6.0 (default, Dec 24 2016, 08:01:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 7
7
>>>

We also saw the different symbols, such as +, *, and -, that can be used to perform different arithmetic operations on the integer values:

>>> 5 + 4 + 6 + 9
24
>>> 5 * 5
25
>>> 42 - 16
26
>>>

Exercise 5: Checking the Type of a Value

We can also check the type of a value by using the type function that's built into Python:

  1. Open the Python interactive shell.

  2. Enter the following code to view the type of the numeric value 7. Observe the output:

    >>> type(7)
    <class 'int'>
    >>>

    As you can see, it tells us that the type of 7 is int (short for integer).

  3. Now, enter the following code, and observe the output:

    >>> type(4+3)
    <class 'int'>
    >>>
  4. Enter the following code at the prompt, and observe the output:

    >>> type("7") 
    <class 'str'>
    >>>
  5. Enter the following code at the prompt, and observe the output:

    >>> type('7') 
    <class 'str'>
    >>>

    Note

    The part in the output before int says class because everything in Python is an object.

There are a few other numeric types of values, such as floating-point numbers, but we'll be taking a look at those in the next chapter.

String Values

Another type of value that we've seen in the previous section was a string value. This is a sequence of characters that's placed in between two quotation marks, for example, "January", "Chops Maloy", and 'UB40'. You can use both double and single quotes to denote strings. Strings can contain numbers, letters, and symbols, like so:

>>> type("3 Musketeers")
<class 'str'>
>>> type('First Order')
<class 'str'>
>>>

As you can see, it tells us the type of the value "3 Musketeers" is str (short for string).

Type Conversion

Sometimes, you may have a string with an integer inside it or an integer that you want to put in a string. The first scenario often happens with user input where everything is returned inside a string. To be able to use it, we need to convert it to the desired data type.

Python allows you to convert string type values to integer type values and vice versa. Using the built-in str function, you can convert an integer to a string:

>>> str(7)
'7'
>>>

Strings can also be converted to integers, as long as they hold a valid integer value within. This is done by use of the built-in int function:

>>> int("100")
100
>>>

An error occurs if we try converting a string that doesn't contain an integer. Here, the string "Foobar" can't be converted because it's a string of letters. "3.14159" also fails because it is a float, and not an integer:

>>> int("Foobar")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Foobar'
>>> int("3.14159")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.14159'
>>>

These are the basic types of values we'll be dealing with in this chapter.

Exercise 6: Assigning Variables

In this exercise, we will learn how to assign a value to a variable:

  1. Assign a value to a variable in Python using the following syntax:

    >>> number = 7
    >>>
  2. Print the variable to the standard output; this should reveal its value:

    >>> print(number)
    7
    >>>
  3. However, if we try using a variable before assigning it a value, the Python interpreter will raise an error. Check this as follows:

    >>> del number
    >>> print(number)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'number' is not defined
    >>>

    On the first line, we're using a new statement: del. del unbinds a name/variable (Python refers to variables as names) from the current namespace. Calling del number thus deletes the variable number from the current namespace.

    Note

    A namespace is a mapping of names/variables to their values.

This means that the reference number is removed and no longer points to the value 7. When we try printing out the now nonexistent variable, we get an error stating that the name number is not defined.

Exercise 7: Using Variables

We use variables when we have a value in our code that we want to use multiple times. They prevent us from having to repeat that value each time we want to use it, as variables store the values in memory.

When we store values in memory, we can reuse them as many times as we'd like:

  1. Assign the value 7 to the number variable:

    >>> number = 7
  2. We can now use this variable for any operations we'd like. Print out the value of the number variable, multiplied by 5:

    >>> number * 5
    35
  3. Print out number added to 2:

    >>> number + 2
    9
  4. Print out number divided by 3.5:

    >>> number / 3.5
    2.0
  5. Print out number subtracted from itself:

    >>> number - number
    0
  6. Note that, despite having used it, the value of number won't change unless we reassign it. Reassigning 22 to number changes its value and verifies this:

    >>> print(number)
    7
    >>> number = 22
    >>> print(number)
    22
    >>>
  7. You can also assign the resulting value of another operation to a variable. Do this as follows:

    >>> number = 7
    >>> x = number + 1
    >>> x
    8
    >>>
  8. String values can also be assigned and used in a similar fashion. First, set the message variable to the string "I love Python":

    >>> message = "I love Python"
  9. Print out the value of the message variable and add an exclamation point at the end:

    >>> message + "!"
    'I love Python!'
  10. Print out message plus three exclamation points:

    >>> message + "!" * 3
    'I love Python!!!'
    >>>

Here, we can see the application of a new operation to strings: +. We use this whenever we want to concatenate (add together) two strings.

This only applies to strings, and thus trying to concatenate a string with any other data type will raise an error. We shall look at it in greater depth in the next chapter.

An interesting phenomenon with Python variables is that they are not deeply linked:

>>> x = 1
>>> y = x
>>> x = 2
>>> print(x)
2
>>> print(y)
1
>>>

A behavior you'd expect would be that y being assigned to x would change upon changing x, but it doesn't and stays the same. What do you think is happening?

Since Python variables point to values in memory, when y is assigned to x, it does not make an alias for x but instead points the variable y to where the value of x, 1, is. Changing x changes its pointer from 1 to 2, but y remains pointing to its initial value:

Figure 1.7: Variable assignment

Multiple Assignment

In Python, you can also assign multiple variables in one statement, like so:

>>> a, b, c = 1, 2, 3
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
>>>

The assignment works so that the first variable, a, is assigned the first value, 1, after the = sign. The second variable, b, is assigned the second value, 2, and the third variable, c, is assigned the third value, 3.

What happens if we try to assign more variables than we pass values?

Python 3.6.0 (default, Dec 24 2016, 08:01:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a, b, c = 1, 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>

The Python interpreter raises an error and tells us it didn't get enough values to assign to the variables we declared in our statement.

A similar error is raised when we try to assign more values than there are variables:

>>> a, b = 1, 2, 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>>

Activity 3: Using Variables and Assign Statements

Write a script that will use distance in kilometers and time in hours to calculate and print out speed in kilometers per hour, miles per hour, and meters per second.

Here are some hints:

  • The formula for calculating speed is distance/time = speed.

  • To convert kilometers to miles, divide the kilometers by 1.6.

  • To convert kilometers to meters, multiply the kilometers by 1,000.

  • To convert hours to seconds, multiply hours by 3,600.

The steps are as follows:

  1. Open your editor.

  2. Create a file named calculate_speed.py and save it.

  3. On the first two lines, declare two variables for the distance in kilometers and time in hours and assign the values 150 and 2, respectively.

  4. In the next two lines, calculate the distances in miles and distance in meters based on the distance in kilometers.

  5. Then, calculate the time in seconds based off the time in hours.

  6. Next, calculate the speed in kilometers per hour, speed in miles per hour, and speed in meters per second.

  7. Finally, add print statements to print out our results.

  8. Save our script and run it by using the python calculate_speed.py command.

The output should look like this:

Figure 1.8: Output of running the calculate_speed.py script

Note

Solution for this activity can be found at page 276.

So far, we've learned how variables are used in Python and a few of the different values you can assign to them. We've also learned how to use variables in our programs. In the next section, we will be looking at the rules for naming variables.

Naming Identifiers and Reserved Words

Python, like other languages, has a couple of rules on naming identifiers such as variable names, class names, function names, module names, and other objects. Some are strictly enforced by the interpreter, while others are simply by convention, and developers are at liberty to ignore them. The rules and conventions are designed to avoid confusion when the interpreter is parsing through code or to make the code more easily readable by humans.

We'll start off by going through some of the rules for naming variables and other identifiers:

  • An identifier can consist of upper and lowercase letters of the alphabet, underscores, unicode identifiers, and digits 0 to 9.

    Note

    As per the Python documentation, you can find the list of permitted unicode identifiers here: https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html.

  • An identifier cannot begin with a digit; for example, 7x is an invalid variable name.

  • No other characters can be in identifiers. This means spaces or any other symbols. Spaces most notably occur in module names as some operating systems will permit filenames with spaces. This should be avoided.

  • A Python keyword cannot be used in an identifier name, for example, import, if, for, and lambda.

The following are examples of valid variable definitions:

>>> meaning_of_life = 42
>>> COUNTRY = "Wakanda"
>>> Ω = 38.12
>>> myDiv = "<div></div>"
>>> letter6 = "f"
>>>

It should also be noted that Python identifier names are case sensitive. Consider this:

>>> foobar = 5

This is a different variable from the following one:

>>> Foobar = 5

Exercise 8: Python Keywords

Certain names in Python cannot be used as they are parts of the language syntax. Such words are known as reserved words or keywords. An example of a reserved word is import, which is a statement used for when you want to import a module into your code.

Python has several keywords. To get the full list, perform the following steps:

  1. Open the Python interactive shell:

    Python 3.6.0 (default, Dec 24 2016, 08:01:42)
    [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>

    In the output, you will see a line saying Type "help", "copyright", "credits" or "license" for more information.

  2. Run help() to open the help utility.

  3. Type keywords in the prompt:

    help> keywords

    You should see the following output:

    Here is a list of the Python keywords. Enter any keyword to get more help.
    
    False               def                 if                  raise
    None                del                 import              return
    True                elif                in                  try
    and                 else                is                  while
    as                  except              lambda              with
    assert              finally             nonlocal            yield
    break               for                 not
    class               from                or
    continue            global              pass
    
    help>
  4. Quit the help utility by typing quit. This should take you back to the interpreter prompt:

    help> quit

You should not use any word from this list of keywords as an identifier name. Note that you don't have to remember them all as the Python interpreter will restrict you from using them.

In the following example, we are trying to use the keyword for, but we get a syntax error upon doing so. The same applies for all keywords:

>>> for = "Elise"
  File "<stdin>", line 1
    for = "Elise"
        ^
SyntaxError: invalid syntax
>>>

Python Naming Conventions

Python has several guidelines for naming identifiers that aren't enforced by the interpreter. These guidelines are meant for consistent code and making it more readable. Please note that these are simply guidelines and the programmer is at liberty to ignore them.

It should be counterpointed that ignoring naming conventions eventually leads to a road of regret as they provide several advantages, such as the following:

  • Makes the code easier to read and understand for other programmers, since they'd find consistent and instantly recognizable patterns

  • Enhances clarity and reduces ambiguity

  • Makes automated refactoring easier, as the automation tools would have consistent patterns to look for

  • Provides additional information about the identifiers; for example, when you see a variable name in all caps, you immediately know that it is a constant

    Note

    For a more in-depth look at Python naming conventions, visit https://www.python.org/dev/peps/pep-0008/#naming-conventions.

Some of these conventions and guidelines are given here.

Compound variable names should be written in snake_case notation.

Prefer this:

>>> first_letter = "a"

Over this:

>>> firstLetter = "a"  # camelCase
>>> FirstLetter = "a"  # PascalCase

Naming for constants should be written in capital letters to denote that their values are not meant to change. In reality, though, Python has no way of restricting the value of a constant from being changed as they are variables, just like any other:

>>> NUMBER_OF_PLANETS = 8
>>> RADIUS_OF_THE_EARTH_IN_KM = 6371

Note that we can change a constant's value:

>>> NUMBER_OF_PLANETS = 9
>>>

Avoid lower case l or uppercase O as single character variable names, as in some fonts, these letters can be mistaken for 1 and 0, respectively, making the code harder to read.

In the next section, we'll learn about comments, their importance, and how to write them in Python.

Activity 4: Variable Assignment and Variable Naming Conventions

Write a script that will calculate the area and circumference of a circle with a radius of 7. In this activity, we'll get better acquainted with variable assignment as well as variable naming conventions.

Here are some hints:

  • The formula for calculating area is π * r², r being the radius.

  • The formula for calculating circumference is 2 * π * r.

  • π can be approximated to 3.14159.

The steps are as follows:

  1. Open your editor.

  2. Create a file named circle.py and save it.

  3. On the first two lines, declare our constant, π (PI), and the radius of the circle with a value of 7.

  4. Write the lines to run our calculations.

  5. Display the results by using print statements.

  6. Save the script and run it by using the python circle.py command.

The output should look like this:

Figure 1.9: Output of running the circle.py script

Note

Solution for this activity can be found at page 277.