2.3.8. Basic Types#

import sys
from pathlib import Path

# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

# Add project root to path
sys.path.insert(0, str(project_root))

# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download

2.3.8.1. Numbers#

Python has three basic number types: integers (e.g., 1), floating-point numbers (e.g., 1.0), and complex numbers. The standard mathematical order of operations is followed for basic arithmetic operations. Note that dividing two integers results in a floating-point number, and dividing by zero will generate an error.

integer = 42             # integer (natural number)
floating = 3.14          # floating-point number (real number)
complex_num = 3 + 4j     # complex number

print(f"Integer: {integer}")
print(f"Floating-point number: {floating}")
print(f"Complex number: {complex_num}") 
Integer: 42
Floating-point number: 3.14
Complex number: (3+4j)
num1 = 1 + 1
num2 = 1 * 3         
num3 = 1 / 2
num4 = 2 / 2             ### output 1.0, not 1

print(num1, type(num1))
print(num2, type(num2))
print(num3, type(num3))
print(num4, type(num4))
2 <class 'int'>
3 <class 'int'>
0.5 <class 'float'>
1.0 <class 'float'>

The modulus operation (also known as the mod function) is represented by the percent sign. It returns what remains after the division:

print(4 % 2)
print(5 % 2)
print(9 // 2)
0
1
4
### Exercise: How many hours and minutes are there in 12500 seconds?
### Use numeric operators
### Your code starts here



### Your code ends here

Hide code cell source

### solution
total_seconds = 12500

remaining_seconds = total_seconds % 60
minutes = total_seconds // 60
remaining_minutes = minutes % 60
# hours = total_seconds // 3600  # 3600 seconds in an hour
hours = minutes // 60  # 60 minutes in an hour

print(f"{hours} hours, {remaining_minutes} minutes, and {remaining_seconds} seconds")
3 hours, 28 minutes, and 20 seconds

2.3.8.2. Strings#

Python represents sequences of letters, which are called strings because the letters are strung together like beads on a necklace. Strings are one of the most commonly used built-in types.

Strings represent text (character sequences) and are created using quotes. Strings can be created using single or double quotes. You can also wrap a single quote in double quotes if you need to include a quote within the string.

Some features about strings in Python:

  • A string is a sequence of characters enclosed in quotes.

  • You can use single, double, or triple quotation marks to create a string; they are all legal.

  • Double quotes make it easy to write a string that contains an apostrophe, which is treated the same as single quotes in programming.

2.3.8.2.1. Creating String Variables#

name1 = "Alice"
name2 = 'Alice'
name3 = """Alice"""
print(name1, name2, name3)
Alice Alice Alice

2.3.8.2.2. Quotation Marks & Escaping#

An escape sequence is a combination of a backslash \ with a special character/symbol to treat the special characters as regular strings.

Observe the following two strings. You see that we are trying to honor the single quote in a pair of double quotes. For that, you can either:

  • enclose the single quotation mark inside the double quotation marks as in the first example, or enclose the double quote with single quotes like the 2nd.

  • use an escape sequence. Note that in s3, we have three single quotation marks, and we are able to produce the same results as the first example.

  • Starting from s4, we have a syntax error because the quotation marks are not properly closed.

s1 = "It's a sunny day."   ### double quote enclose single
s2 = 'It"s a sunny day.'   ### ... but legal
s3 = 'It\'s a sunny day.'  ### escape single quote
print(s1, s2, s3, sep="\n")
It's a sunny day.
It"s a sunny day.
It's a sunny day.

The enclosing quotations have to be symmetrical, otherwise you would have a syntax error.

%%expect SyntaxError
s4 = 'It's a sunny day.'   ### illegal: not closed
s5 = "It"s a sunny day."   ### illegal: not closed
print(s4, s5, sep="\n")
  Cell In[9], line 1
    s4 = 'It's a sunny day.'   ### illegal: not closed
                           ^
SyntaxError: unterminated string literal (detected at line 1)

Commonly used escape sequences are as follows.

Sequence

Meaning

\'

Single quote inside single-quoted string

\"

Double quote inside double-quoted string

\\

Backslash literal

\n

Newline

\t

Tab

Some examples of escape sequences are:

print("First line \n Second line")      ### \n: gives new line (break)
print("Name:\tDoris")                   ### \t: tab
print("He said \"Python is great!\"")   ### print " inside ""
print('I\'m learning Python')           ### show ' as a character, not quotation mark
First line 
 Second line
Name:	Doris
He said "Python is great!"
I'm learning Python

Observe and see if the print output makes sense to you.

print("PS C:\\Users\\tychen>")          ### \\ to show \
PS C:\Users\tychen>

2.3.8.2.3. Common string operations#

  1. Concatenation: "Hello" + " " + "World""Hello World"

  2. Repetition: "Ha" * 3"HaHaHa". The multiplication (*) operator also works with strings; it makes multiple copies of a string and concatenates them.

  3. Length: len("Python")6. Python provides a useful function called len that computes the length of a string. Notice that len counts the letters between the quotes, but not the quotes. In collection types, len counts the number of elements in the collection.

  4. Indexing: "Python"[0]"P"

  5. Slicing: "Python"[0:3]"Pyt"

Here we have one example for each of the string operations:

name = "Alice"
greeting = "Hello, " + name + "!"              ### 1. concatenation

print("1.", greeting)                           
print("2.", greeting * 3)                      ### 2. repetition
print(f"3. Length: {len(name)}")               ### 3. length + f-string
print(f"4. First letter: {name[0]}")           ### 4. indexing + f-string
print(f"5. First three letters: {name[0:3]}")  ### 5. slicing + f-string
1. Hello, Alice!
2. Hello, Alice!Hello, Alice!Hello, Alice!
3. Length: 5
4. First letter: A
5. First three letters: Ali

Exercise: String Manipulation

  • What will be the output of this code?

  • Guess first and then activate Live Coding and run the code in the cell below to find out.

s = "hello"
t = s
s = s.upper()
print(t)

A) HELLO
B) hello
C) Error
D) None

### Use this code cell to test.



###

Hide code cell source

### solution: comment out the print statement 
#   to see the output of t

s = "hello"
t = s
s = s.upper()
# print(t)

2.3.8.2.4. Indexing and Slicing#

Strings are sequences of characters. You can access specific elements using square bracket notation. Python indexing starts at zero. Negative indexing in slicing starts with -1 from the end element.

s = 'hello'
print(s[0])
print(s[4])
print(s[-1])
h
o
o

Slice notation allows you to grab parts of a string. Use a colon to specify the start and stop indices. The stop index is not included.

s = 'applebananacherry'
print(s[0:])     ### applebananacherry
print(s[:5])     ### apple
print(s[5:11])   ### banana
print(s[-6:])    ### cherry
print(s[-6:0])   ### 
print(s[-6:-1])  ### cherr (stop exclusive)
applebananacherry
apple
banana
cherry

cherr

2.3.8.3. Boolean Type#

The type of a Boolean value is bool. The only two Boolean values are True and False. They are built-in keywords and must be capitalized.

Booleans represent truth values and are used extensively in conditional comparisons and logical expressions, which involve comparison/relational operators and logical operators.

3 > 5
False
num1, num2, num3, num4 = 1, 2, 3, 4

if (num1 > num2):                  ### comparison operator ">"
    print("num1 is greater than num2.")
else:
    print("num1 is not greator than num2.")
num1 is not greator than num2.
is_student = True
is_graduated = False

print(f"Is student: {is_student}")      
print(f"Is graduated: {is_graduated}")   
Is student: True
Is graduated: False
if is_student:                          ### in this case, True
    print("The person is a student.")
else:
    print("The person is not a student.")
The person is a student.

2.3.8.3.1. Boolean Expressions#

A boolean expression is an expression that is either True or False. For example, the following expressions use the equals operator, ==, which compares two values and produces True if they are equal and False otherwise. Remember that there are six relational/comparison operators: == != > < >= <=.

t_f_1 = 5 == 5
t_f_2 = 5 == 7
print(t_f_1, t_f_2)
True False

A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = assigns a value to a variable and == compares two values.

x = 5       ### assignment
y = 7       ### assignment
x == y      ### comparison/relational
False

True and False are special values that belong to the type bool; they are not strings:

print(type(True))
print(type(False))
<class 'bool'>
<class 'bool'>

The == operator is one of the 6 relational operators; the others are:

x != y               # x is not equal to y
x > y                # x is greater than y
x < y                # x is less than y
x >= y               # x is greater than or equal to y
x <= y               # x is less than or equal to y
True

2.3.8.3.2. Truthy and Falsy#

In Python, every object has a truth value in Boolean contexts like if and while. “Truthy” values behave like True, while “falsy” values behave like False - empty containers and zero are falsy; most non-empty values are truthy.

  • Falsy: False, None, 0, 0.0, '', [], {}, set()

  • Truthy: most other values (e.g., '0', [0]).

  • Quick check: bool(value);

  • idiom: if not items: checks emptiness.

# Minimal truthy/falsy examples
print(bool(0)), print(bool(''))        # False
print(bool('0')), print(bool([0]))     # True
False
False
True
True
(None, None)