Reader small image

You're reading from  Scientific Computing with Python 3

Product typeBook
Published inDec 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781786463517
Edition1st Edition
Languages
Right arrow
Authors (3):
Claus Führer
Claus Führer
author image
Claus Führer

Claus Führer is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University's Faculty of Engineering Best Teacher Award in 2016.
Read more about Claus Führer

View More author details
Right arrow

Chapter 2. Variables and Basic Types

In this chapter, we will present the most important and basic types in Python. What is a type? It is a set consisting of data content, its representation, and all possible operations. Later in this book, we will make this definition much more precise, when we introduce the concepts of a class in Chapter 8, Classes.

Variables


Variables are references to Python objects. They are created by assignments, for example:

a = 1 
diameter = 3.
height = 5.
cylinder = [diameter, height] # reference to a list

Variables take names that consist of any combination of capital and small letters, the underscore _ , and digits. A variable name must not start with a digit. Note that variable names are case sensitive. A good naming of variables is an essential part of documenting your work, so we recommend that you use descriptive variable names.

Python has some reserved keywords, which cannot be used as variable names (refer to following table, Table 2.1). An attempt to use such a keyword as variable name would raise a syntax error.

Table 2.1: Reserved Python keywords.

As opposed to other programming languages, variables require no type declaration. You can create several variables with a multiple assignment statement:

a = b = c = 1   # a, b and c get the same value 1

Variables can also be altered after their...

Numeric types


At some point, you will have to work with numbers, so we start by considering different forms of numeric types in Python. In mathematics, we distinguish between natural numbers (ℕ), integers (ℤ), rational numbers (ℚ), real numbers (ℝ) and complex numbers (ℂ). These are infinite sets of numbers. Operations differ between these sets and may even not be defined. For example, the usual division of two numbers in ℤ might not result in an integer — it is not defined on ℤ.

In Python, like many other computer languages, we have numeric types:

  • The numeric type int, which is at least theoretically the entire ℤ
  • The numeric type float, which is a finite subset of ℝ and
  • The numeric type complex, which is a finite subset of ℂ

Finite sets have a smallest and a largest number and there is a minimum spacing between two numbers; refer to the section on Floating Point Representation for further details.

Integers

The simplest numerical type is the integer type.

Plain integers

The statement k = 3 assigns...

Booleans


Boolean is a datatype named after George Boole (1815-1864). A Boolean variable can take only two values, True or False. The main use of this type is in logical expressions. Here are some examples:

a = True 
b = 30 > 45   # b gets the value False

Boolean expressions are often used in conjunction with the if statement:

if x > 0:
   print("positive")
else:
   print("nonpositive)

Boolean operators

Boolean operations are performed using the and, or, and not keywords in Python:

True and False # False
False or True # True
(30 > 45) or (27 < 30) # True
not True # False
not (3 > 4) # True

The operators follow some precedence rules (refer to section Executing scripts in Chapter 1, Getting started) which would make the parentheses in the third line and in the last obsolete (it is a good practice to use them anyway to increase the readability of your code). Note that the and operator is implicitly chained in the following Boolean expressions:

a...

Strings


The type string is a type used for text:

name = 'Johan Carlsson'
child = "Åsa is Johan Carlsson's daughter"
book = """Aunt Julia 
       and the Scriptwriter"""

A string is enclosed either by single or double quotes. If a string contains several lines, it has to be enclosed by three double quotes """ or three single quotes '''.

Strings can be indexed with simple indexes or slices (refer to Chapter 3, Container Types, for a comprehensive explanation on slices):

book[-1] # returns 'r' 
book[-12:] # returns 'Scriptwriter'

Strings are immutable; that is, items cannot be altered. They share this property with tuples. The command book[1] = 'a' returns:

TypeError: 'str' object does not support item assignment

The string '\n' is used to insert a line break  and 't' inserts a horizontal tabulator (TAB) into the string to align several lines:

print('Temperature:\t20\tC\nPressure:\t5\tPa')

These strings are examples of escape sequences. Escape sequences always start with a backslash...

Summary


In this chapter, you met the basic data types in Python and saw the corresponding syntax elements. We will work mostly with numeric types such as integers, floats and complex.

Booleans are needed for setting conditions, and by using strings, we often communicate results and messages.

Exercises


Ex. 1 → Check whether x = 2.3 is a zero of the function:

Ex. 2 → According to de Moivre's formula, the following holds:

Choose numbers n and x and verify that formula in Python.

Ex. 3 → Complex numbers. Verify Euler's formula in the same way:

Ex. 4 → Suppose we are trying to check the convergence of a diverging sequence (here the sequence is defined by the recursive relation un +1= 2un and u0 = 1.0):

u = 1.0 # you have to use a float here!
uold = 10. 
for iteration in range(2000):
    if not abs(u-uold) > 1.e-8:
         print('Convergence')
         break # sequence has converged
    uold = u
    u = 2*u
else:
    print('No convergence')
  1. Since the sequence does not converge, the code should print the No convergence message. Execute it to see what happens.
  2. What happens if you replace the line:

          if not abs(u-uold) > 1.e-8

    with:

          if abs(u-uold) < 1.e-8

    It should give exactly the same result, shouldn't it? Run the code...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Scientific Computing with Python 3
Published in: Dec 2016Publisher: PacktISBN-13: 9781786463517
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (3)

author image
Claus Führer

Claus Führer is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University's Faculty of Engineering Best Teacher Award in 2016.
Read more about Claus Führer