© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_3

3. Working with Data

Kevin Wilson1  
(1)
London, UK
 

You can store and manipulate all different types of data: a number, a string, list, and so on. With Python, you don't need to declare all your variables before you use them.

Variables

A variable is a labeled location in memory that is used to store values within a computer program. There are two types of variables: local and global.

Local Variables

Variables defined within a function are called local variables , as they are local to that particular function. These variables can only be seen by the function in which they are defined. These variables have local scope. Figure 3-1 shows an example of local variables.

A diagram depicts three rectangular boxes with labels on top that reads first num, second num, and total.

Figure 3-1

An example of local variables

Global Variables

Global variables are defined in the main body of the program outside any particular functions. These variables can be seen by any function and are said to have global scope.

Here in the example below, “a” and “b” are global variables, while “firstnum,” “secondnum,” and “sum” are local variables.

A 5-line code reads a, equals i n t 2, b, equals i n t 3, def add sum, first num, the second num, the sum equals first num plus second num, return the sum.

You would not be able to access the variables “firstnum,” “secondnum,” and “sum” from outside the “addnum” function.

Basic Data Types

A variable can store various types of data, called a data type . Let’s introduce some of the basic types we'll be looking at.

Integers

An integer is a whole number and can be positive or negative. Integers can usually be of unlimited length.
score = 45

Floating Point Numbers

A floating point number , sometimes called a real number, is a number that has a decimal point:
temperature = 44.7

Strings

In Python code , a string must be enclosed in quotes “...” or ‘...’:
name = "John Myers"

Lists

A list is an ordered sequence of data items usually of the same type, each identified by an index (shown in the circles). This is known as a one-dimensional list.

A diagram depicts 4 numbered rectangles marked 0 to 3 and labeled bread, milk, coffee, and cereal.

Lists are known as arrays in other programming languages, and you can create one like this – list elements are enclosed in square brackets [ ]:
shoppingList = ['bread', 'milk', 'coffee', 'cereal']
To reference an item in a list, put the reference in square brackets :
print (shoppingList[1])
You can assign another value to an item in the list (e.g., change cereal):
shoppingList[3] = "chocolate"

You would end up with something like this:

A diagram depicts 4 numbered rectangles marked 0 to 3 and labeled bread, milk, coffee, and chocolate.

Let's look at a program. Open the file list1.py. Here, we've created a list and initialized it with some data.

A window of list 1 dot p y with 17 lines of code that creates a shopping list for Bread, Milk, Coffee, and Cereal. It also adds a fourth item to the list for Pizza.

We can output data from the list using a print statement and a reference to the item in the shopping list:
print (shoppingList[3])
We can also update an item in the list using the reference :
shoppingList[3] = 'pizza'

Two-Dimensional Lists

Two-dimensional lists are visualized as a grid similar to a table with rows and columns. Each column in the grid is numbered starting with 0. Similarly, each row is numbered starting with 0. Each cell in the grid is identified by an index – the row index followed by the column index (shown in the circles).

A 4 by 4 grid with indexes. The grid on the second row, third column, labeled 9 is highlighted.

You could declare the earlier list as
scoreSheet = [
    [ 21, 8, 17, 4 ],
    [ 2, 16, 9, 19 ],
    [ 8, 21, 14, 3 ],
    [ 3, 18, 15, 5 ]
]
To reference an item in a two-dimensional list, put both the references in square brackets (first the row index, then the column index):
print (scoreSheet[1][2]) #circled above
You can change items in the list, put both the references in square brackets (first the row index, then the column index), and then assign the value:
scoreSheet [0][3] = 21

Let’s take a look at a program. Open the file list2d.py. Here, we've declared our shoreSheet list and initialized it with some data .

A window of list 2 d dot p y with 15 lines of code references an item in a two-dimensional list.

We can add an item to a particular location in the list:
scoreSheet [1][2] = 21
We can also output data stored at a particular location :
print (scoreSheet[1][2])

Sets

A set is an unordered collection of unique items enclosed in curly braces { }. Sets can contain different types.

You can create a set like this:
setName = {1, 6, 2, 9}
Two things to note about sets. Firstly, you can’t index individual elements in the set as it is an unordered data type. Secondly, you can’t change individual values in the set like you can with lists. However, you can add or remove items. Use the .add()method, and type the data to add, in the parentheses .
setName.add('item to add')

Let’s take a look at a program. Open the file sets.py. Here, we've created a set with some animal names. We can output the data in the set.

A window of sets dot p y with 7 lines of code lets you add and remove items in a set. The sample provided lists lion, cheetah, and elephant in a set labeled animal and adds mouse.

We can also add an item to the set using the .add() method .

Tuples

A tuple is similar to a list and is a sequence of items each identified by an index. As with lists, the index starts with 0 not 1.

In contrast to lists, items in a tuple can’t be changed once assigned, and tuples can contain different types of data.

To create a tuple, enclose the items inside parentheses ( ):
userDetails = (1, 'John', '123 May Road')

Use a tuple when you want to store a data of a different type, such a sign in details for your website.

Let’s take a look at a program. Open the file tuple.py. Here, we've created a tuple with some colors.

A window of tuple dot p y with 5 lines of codes lists a palette of colors namely, red, orange, yellow, green, and blue and is outputted using the print statement.

We can output the data in the tuple using a print statement :
print (Palette[2])

Dictionaries

A dictionary is an unordered collection of items, each identified by a key.

To create a dictionary, enclose the items inside braces { }. Identify each item with a key using a colon.
dictionary = { 1: 'Dave',
               2: 'Jo'
               3: 'Jane'
}
To read a value, put the key in square brackets:
print (dictionary[1])
To change or add a value, put the key in square brackets. For example, change “jo” to “mike.”
dictionary[2] = 'Mike'

Let’s take a look at a program. Open the file dictionary.py. Here, we've created a dictionary with some user data .

A window of dictionary dot p y with 12 lines of code references data for I D, surname, and name. The value for the surname is changed in line 9.

We can reference the data using the key, for example, “ID”:
print (userData['ID'])

Program Input

One of the main reasons for writing a program is so you can run it multiple times with various different data.

Instead of hard coding the input data into a variable as we’ve done previously, it would be better to prompt the user for the input or retrieve it from a file (see later).

Instead of writing
a = 7
we can use the input() function to prompt the user for a number:
a = input ('Enter a number: ')
It’s a good idea to separate your data from the actual program.

A diagram depicts input data converted into an actual program that reads a equals input, open parenthesis, quote, enter a number, colon, quote, and close parenthesis.

Figure 3-2

Input data into a program

Program Output

Any result calculated by the program needs to be displayed to the user in a meaningful way. We can either output the data to the screen using the print() function, or we can write the data to a file (see later).

A diagram displays a function, print a, as a method to output data.

Figure 3-3

Data output from program

Casting Data Types

Variables can contain various types of data such as text (called a string), a whole number (called an integer), or a floating point number (numbers with decimal points).

With Python, you don’t have to declare all your variables before you use them. However, you might need to convert variables to different types. This is known as type casting .

Python has two types of type conversion: implicit and explicit.

With implicit type conversion, Python automatically converts one data type to another.

With explicit type conversion, the programmer converts the data type to the required data type using a specific function. You can use the following functions to cast your data types:

int( ) converts data to an integer

long( ) converts data to a long integer

float( ) converts data to a floating point number

str( ) converts data to a string

For example, we use the input( ) function to prompt the user for some data :
a = input ('Enter first number: ')

This example would prompt the user for some data and then store the data in the “a” variable as a string.

This might sound ok, but what if we wanted to perform some arithmetic on the data? We can't do that if the data is stored as a string. We’d have to type cast the data in the variable as an integer or a float.
int(a)
or
float(a)

Arithmetic Operators

Within the Python language, there are some arithmetic operators you can use.

A table has 2 columns and 5 rows. The column headers are operator and description with row entries, double asterisk, forward slash, single asterisk, plus sign, and minus sign.

Operator Precedence

BIDMAS (sometimes called BODMAS ) is an acronym commonly used to remember mathematical operator precedence – that is, the order in which you evaluate each operator:
  1. 1.

    Brackets ( )

     
  2. 2.

    Indices (sqrt, power, squared2, cubed3, etc.) **

     
  3. 3.

    Divide /

     
  4. 4.

    Multiply *

     
  5. 5.

    Add +

     
  6. 6.

    Subtract -

     

Performing Arithmetic

If you wanted to add 20% sales tax to a price of £12.95, you could do something like this:
total = 12.95 + 12.95 * 20 / 100
According to the precedence list given earlier, you would first evaluate the “divide” operator:
20 / 100 = 0.2
Next is multiply:
12.95 * 0.2 = 2.59
Finally addition:
12.95 + 2.59 = 15.54

Comparison Operators

These are used to compare values and are commonly used in conditional statements or constructing loops.

A table has 2 columns labeled operator and description. There are 5 operator sign row entries, from double equal sign to left angle bracket, equal sign.

For example, comparing two values in an “if” statement, you could write something like this:
if a > 10:
   print ("You've gone over 10...")

Boolean Operators

Also known as logical operators and are commonly used in conditional statements (if...) or constructing loops (while... for...).

A table has 2 columns and 3 rows. The column headers are operator and description with the row entries and, or, and not, with their descriptions.

For example, you could join two comparisons in an “if” statement using “and,” like this:
if a >= 0 and a <= 10:
   print ("Your number is between 0 and 10")
else
   print ("Out of range - must be between 0 & 10")
Using the 'and' operator would mean both conditions (a >= 0) and
(a <= 10) must be true .

Bitwise Operators

Bitwise operators are used to compare binary numbers:

A table has 3 columns labeled operator, name, and description. There are 6 operator symbol row entries, from the ampersand symbol to the double right angle bracket symbol.

You can apply the bitwise operators:
a >> 2 #shift bits of 'a' left by 2 units
a << 2 #shift bits of 'a' right by 2 units
a & b #perform AND operation on bits

Lab Exercises

Write a program that accepts a length in inches and prints the length in centimeters (1 inch = 2.54cm).

Write a program that accepts your forename, surname, and year of birth and adds them to an array.

Write a program that converts temperatures from Celsius to Fahrenheit:
F = C × 9/5 + 32
Write a program that calculates the volume of a sphere:
V = 4/3 πr3

Write a program to calculate and display an employee’s gross and net pay. In this scenario, tax is deducted from the gross pay at a rate of 20% to give the net pay.

Write a program that stores a shopping list of ten items. Print the whole list to the screen, and then print items 2 and 8.

Extend the previous program, to insert an item into the list.

What is a Boolean operator? Write a program to demonstrate.

What is a comparison operator? Write a program to demonstrate.

What is data type casting? Why do we need it? Write a program to demonstrate.

Summary

  • A variable is a labeled location in memory that is used to store values within a computer program

  • Variables defined within a function are called local variables, as they are local to that particular function.

  • Global variables are defined in the main body of the program outside any particular functions.

  • An integer is a whole number and can be positive or negative. Integers can usually be of unlimited length.

  • A floating point number, sometimes called a real number, is a number that has a decimal point.

  • A string must be enclosed in quotes.

  • A list is an ordered sequence of data items usually of the same type, each identified by an index.

  • A set is an unordered collection of unique items enclosed in curly braces.

  • A tuple is similar to a list and is a sequence of items each identified by an index. Items in a tuple can’t be changed once assigned and tuples can contain different types of data.

  • A dictionary is an unordered collection of items, each identified by a key.

  • We can use the input() function to prompt the user for a number.

  • Converting variables to different types is known as type casting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.105.194