3  Basics Good to Know

What To Expect In This Chapter

In the previous chapter, you learned some essential basics of Python. In this chapter, I will build on those earlier concepts to add more details to the same ideas. I will also introduce different data types and how to combine variables with English.

3.1 More Python Basics

3.1.1 Computers read = from Right to Left!

The way computers use = is quirky. Let me explain why. Consider the code below:

x = 40
y = x + 2

How Python executes these instructions as follows:

Action
x = 40 Make x have the value 40
y = x + 2 [STEP 1] Add 2 to x (to get 42)
[STEP 2] Then make y equal to the answer (i.e. 42).

This means the following will work in programming (but not math!).

y = 40
y = y + 2
print(y)

You will frequently see variables modified using this syntax. So, best get used to it.

Note: Python also allows the following syntax.

x = y = 10

3.1.2 Shorter and cleaner

Let me introduce you to some shorthand syntax that will make your code slightly neater. This is related to the previous point and involves updating the value of a variable.

y = 40
y = y + 2

In the above snippet of code we can replace y = y + 2 with y += 2 so that

y = 40
y += 2    # Same as y = y + 2
y
42

You will see this shorthand often in books and on the web. So, even if you do not use it, it will be helpful to be able to read and understand it. Similar shorthand notations exist for subtraction, division and multiplication, as shown below.

Subtraction

y = 40
y -= 2     # Same as y = y - 2
y
38

Division

y = 40
y /= 2    # Same as y = y/2
y
20.0

Multiplication

y = 40
y *= 2    # Same as y = y * 2
y
80

3.1.3 Asking questions

Previously we saw how we could use if to make decisions based on a question (condition). Let’s now look at a few more examples of how we can ask questions.

Let’s ask some questions about the following two lists.

fruits = ["apple", "banana", "pineapple", "jackfruit"]
vegetables = ["celery", "potato", "broccoli", "kale"]
  1. "apple" in fruits
  2. "peach" in fruits
  3. "peach" not in fruits
  4. ("apple" in fruits) and ("celery" in vegetables)
  5. ("apple" in fruits) or ("celery" in vegetables)

You will find the following useful when asking questions:

Question/Condition Math Symbol Python Symbols
Equals? = ==
Not equal? !=
Less than? < <
Greater than? > >
Less than or equal? <=
Greater than or equal? >=

Note:

  1. Basic Python only knows how to compare similar things (types) (e.g. numbers or English). So, 3 > 10.5 will work, but 3 > 'apple' will not. However, Python can compare 'apples' and 'oranges':

    'apples' > 'oranges'

This comparison works because English letters are internally represented as numbers. For example, a is 97 and o is 111.

This will become even clearer after you have worked on the section below on data types.

  1. Python allows you to write

    (x > 5) and (x < 15)

    as

    5 < x < 15

3.1.4 There is more to if

There are situations when we need more branches in an if statement. Python has the elif (else if) statement for such cases. Here is how it works

name = 'Batman'

if name == 'Batman':
    print('Hello Hero | Batman!')
elif name == 'Robin':
    print('Hello Sidekick | Robin!')
else:
    print('Hello World!')

Python stores information in different formats or types.

For efficiency (i.e. speed and memory), computers store information in different ways. For example, here are four ways we can store the number 1.234. We are also using the function type() to check how the information is stored.

  1. As an integer (int). This will end up dropping the decimal portion.

    x = int(1.234)
    print(x, type(x))
    1 <class 'int'>
  2. As an English word (str).

    x = str(1.234)
    print(x, type(x))
    1.234 <class 'str'>
  3. As a decimal number (float).

    x = float(1.234)
    print(x, type(x))
    1.234 <class 'float'>
  4. As a complex number (complex). This will include an imaginary part of the number.

    x = complex(1.234)
    print(x, type(x))
    (1.234+0j) <class 'complex'>

Note:

  1. There are many other types of data. See here for more details.
  2. We can force Python to change the type of a variable:
x = '1.234'
print(x, type(x))
1.234 <class 'str'>
x = float(x)
print(x, type(x))
1.234 <class 'float'>

This is referred to as typecasting. I.e. we cast x into the type float.

3.1.5 Combining English and variables

  1. name = "Batman"
    print(f"Hello {name}!")
    Hello Batman!
  2. name = "Batman"
    print(f"Hello {name.upper()}!")
    Hello BATMAN!
  3. x = 10
    print(f"The value of {x} squared is {x**2}!")
    The value of 10 squared is 100!

Note the f and the { } in the above command. This is called f-string or string interpolation.

You can do more with f-strings, like formatting a string or number. Let me show you three examples.

  1. text = 'Bruce Wayne is Batman.'
    print(f'{text}')
    Bruce Wayne is Batman.
    print(f'{text:>30}')      # A block of 30 characters; aligned right
            Bruce Wayne is Batman.
    print(f'{text:^30}')      # A block of 30 characters; aligned centre
        Bruce Wayne is Batman.    
    print(f'{text:<30}')      # A block of 30 characters; aligned left
    Bruce Wayne is Batman.        
  2. print(f'The cube of pi to 6 decimal places is {np.pi**3:.6f}')
    The cube of pi to 6 decimal places is 31.006277

    The f in .6f is used to tell the f-string to output the number in decimal notation.

  3. print(f'The cube of pi to 6 decimal places is {np.pi**3:.6e}')
    The cube of pi to 6 decimal places is 3.100628e+01

    The e in .6e is used to tell the f-string to output the number in scientific notation.

Structure of f-strings

The f-string formatting has the structure {X:>0Y.ZW}. So here is what you can use for each of the letters (X,Y,>,0,Z,W) .

W Specifies the type of variable:
f - float
d- integer
s- string
g - Ask python figure out
X Variable to format (Can be a number or a string)
> Alignment Use <, >, ^ for Left, Right and Centre
Y Total number of characters
Z Number of decimal places
0 Use 0’s to pad the spaces

You can refer to this website for more information.

3.1.6 Python can be a prima-donna.

When we do something Python doesn’t like or understand, it will often act like a prima-donna and throw a complaint with a looong error message. As with most complaints, scroll to the end to see the real problem.

If you had used Print() in the previous chapter, you would have already seen an error message. Fixing errors with code is called debugging. The more debugging you do, the more comfortable you will be with programming. So, we will practice this often in the following weeks.

3.2 Best Practices for Scientific Computing

3.2.1 Some tips

Now is an apt time to highlight some best practices you should always bear in mind. The following is an excerpt from ().

I have only given those points that apply to you now. I will bring up more as we progress on our journey.

  1. Write programs for people, not computers.
  2. Optimise software only after it works correctly.
  3. Document design and purpose, not mechanics.
  4. Collaborate.

If you don’t take care, your code can quickly become unfathomable to others and (even) your future self. So, consciously produce easily understandable code (for example, using appropriate variable names). In addition, discussing your code with your friends (collaboration) is helpful because you will get immediate feedback if your code is indecipherable or if you have misunderstood a concept.

Another common pitfall novices succumb to is pursuing a perfect solution right from the get-go. Instead, it is better to get something (anything) working before slowly adding complexity and optimising the code.

Remember

Start simple, get something working first before making it perfect.

3.2.2 Getting help.

The internet (e.g. stack overflow) is the fastest way to get a question about programming answered. However, you can also get information from within Python by:

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

The above is some documentation corresponding to the function. Unfortunately, unless you already have some experience, this documentation is not the friendliest, so you are better off with Google.


  1. despite the English phrase↩︎