Basics

Overview

Teaching: 20 min
Exercises: 25 min
Questions
  • How do I run Python programs?

  • What are Python’s basic data types?

Objectives
  • Launch the IPython, doing some operations, and exit the IPython.

  • Create and run Python commands in IPython.

  • Write simple scripts (.py files) that use atomic data types, variables, and lists.

Python programs are plain text files.

IPtyhon

%load_ext autoreload
from module1 import function1
## edit module1
%autoreload 2

For more information about autoreload, you can refer to the documentation here.

Use the IPython for running Python.

Code vs. Text

We often use the term “code” to mean “the source code of software written in a language such as Python”. A “code command” in a command is a IPython that contains software; a “text comment started bt #” is one that contains ordinary prose written for human beings.

Use variables to store values.

age = 42
first_name = 'Ahmed'

Use print to display values.

print(first_name, 'is', age, 'years old')
Ahmed is 42 years old

Variables must be created before they are used.

print(last_name)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 print(last_name)

NameError: name 'last_name' is not defined

Python provides the usual atomic types and operators.

Index and slice to get information out of a string.

element = 'helium'
print('first character:', element[0])
print('last character:', element[-1])
print('middle:', element[2:5])
first character: h
last character: m
middle: liu

Use the built-in function len to find the length of a string.

print(len('helium'))
6

Python containers

Python includes several built-in containers types: list, dictionaries, sets, and tupple.

A list stores many values in a one-dimensional structure.

pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
print('pressures:', pressures)
print('length:', len(pressures))
print('second value:', pressures[1])
print('middle:', pressures[1:-1])
pressures: [0.273, 0.275, 0.277, 0.275, 0.276]
length: 5
second value: 0.275
middle: [0.275, 0.277, 0.275]

Lists’ values can be replaced by assigning to them.

pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]

Appending items to a list lengthens it.

primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
primes.append(9)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7, 9]

Use del to remove items from a list entirely.

print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
primes before removing last item: [2, 3, 5, 7, 9]
primes after removing last item: [2, 3, 5, 7]

The empty list contains no values.

Lists may be heterogeneous.

goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']

Character strings are immutable.

element[0] = 'C'
TypeError: 'str' object does not support item assignment

Indexing beyond the end of a collection is an error.

print('99th element of element is:', element[99])
IndexError: string index out of range

We will study about dictionaries, sets, and tupple later.

More Math

What is displayed when a Python cell in a notebook that contains several calculations is executed? For example, what happens when this cell is executed?

7 * 3
2 + 1

Swapping Values

Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do?

lowest = 1.0
highest = 3.0
temp = lowest
lowest = highest
highest = temp

Predicting Values

What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.)

initial = "left"
position = initial
initial = "right"

Challenge

If you assign a = 123, what happens if you try to get the second digit of a?

Solution

Numbers are not stored in the written representation, so they can’t be treated like strings.

a = 123
print(a[1])
TypeError: 'int' object is not subscriptable

Choosing a Name

Which is a better variable name, m, min, or minutes? Why? Hint: think about which code you would rather inherit from someone who is leaving the lab:

  1. ts = m * 60 + s
  2. tot_sec = min * 60 + sec
  3. total_seconds = minutes * 60 + seconds

Solution

minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).

Slicing

What does the following program print?

element = 'carbon'
print('element[1:3] is:', element[1:3])
element[1:3] is: ar
  1. What does thing[low:high] do?
  2. What does thing[low:] (without a value after the colon) do?
  3. What does thing[:high] (without a value before the colon) do?
  4. What does thing[:] (just a colon) do?

Fill in the Blanks

Fill in the blanks so that the program below produces the output shown.

values = ____
values.____(1)
values.____(3)
values.____(5)
print('first time:', values)
values = values[____]
print('second time:', values)
first time: [1, 3, 5]
second time: [3, 5]

How Large is a Slice?

If ‘low’ and ‘high’ are both non-negative integers, how long is the list values[low:high]?

From Strings to Lists and Back

Given this:

print('string to list:', list('tin'))
print('list to string:', ''.join(['g', 'o', 'l', 'd']))
['t', 'i', 'n']
'gold'
  1. Explain in simple terms what list('some string') does.
  2. What does '-'.join(['x', 'y']) generate?

Working With the End

What does the following program print?

element = 'helium'
print(element[-1])
  1. How does Python interpret a negative index?
  2. If a list or string has N elements, what is the most negative index that can safely be used with it, and what location does that index represent?
  3. If values is a list, what does del values[-1] do?
  4. How can you display all elements but the last one without changing values? (Hint: you will need to combine slicing and negative indexing.)

Stepping Through a List

What does the following program print?

element = 'fluorine'
print(element[::2])
print(element[::-1])
  1. If we write a slice as low:high:stride, what does stride do?
  2. What expression would select all of the even-numbered items from a collection?

Slice Bounds

What does the following program print?

element = 'lithium'
print(element[0:20])
print(element[-1:3])

Sort and Sorted

What do these two programs print? In simple terms, explain the difference between sorted(letters) and letters.sort().

# Program A
letters = list('gold')
result = sorted(letters)
print('letters is', letters, 'and result is', result)
# Program B
letters = list('gold')
result = letters.sort()
print('letters is', letters, 'and result is', result)

Copying (or Not)

What do these two programs print? In simple terms, explain the difference between new = old and new = old[:].

# Program A
old = list('gold')
new = old      # simple assignment
new[0] = 'D'
print('new is', new, 'and old is', old)
# Program B
old = list('gold')
new = old[:]   # assigning a slice
new[0] = 'D'
print('new is', new, 'and old is', old)

Key Points

  • Python programs are plain text files.

  • We can write Python in the IPython as well as plain text).

  • Most common atomic data types are int, float, str, and bool.

  • Most common type of collection is list.

  • Use variables to store values.

  • Use print to display values.

  • Variables persist between cells.

  • Variables must be created before they are used.

  • Use an index to get a single character from a string or list.

  • Use a slice to get a substring or sub-list.

  • Use the built-in function len to find the length of a string.

  • Python is case-sensitive.