Introduction

Chapter 1 ยท Think Python

Chapter 1 learning objectives

By the end of this chapter, you will be able to:

  1. Explain what programming is at a high level
  2. Describe how Python fits into the broader computing landscape
  3. Distinguish programming ideas from Python-specific syntax
  4. Find environment and Jupyter setup guidance
  5. Use basic built-in functions in simple Python code

Programming Concepts

1.1 ยท Think Python

Today's goals

  • Define an algorithm and turn one into a program
  • Contrast natural and formal languages
  • Place Python among levels of abstraction
  • Tell interpreted from compiled execution
  • Name the core programming constructs
  • Separate expressions from statements
  • Read binary, hexadecimal, and character codes

How you learn to program

Learning programming is largely about connecting the dots.

  1. Repeat: keep collecting and revisiting the core ideas
  2. Associate: keep linking new ideas to ideas you already have

You need enough concepts, examples, and practice to work with, and then you need to connect them.

An algorithm is a plan

An algorithm is a finite, ordered set of unambiguous steps that turns input into output.

  • Each step is clear enough that anyone, or any machine, gets the same result
  • The steps eventually come to an end
  • It describes the logic, not the syntax of a language

A recipe is an algorithm: ingredients in, fixed steps, a finished dish out.

Example: find the largest number

  1. Look at the first number and remember it as the largest so far
  2. Look at the next number; if it is greater, remember it instead
  3. Repeat step 2 until no numbers are left
  4. Report the number you remembered

Input [42, 17, 88, 63]: remember 42, keep 42, switch to 88, keep 88.

Output: 88

From algorithm to program

numbers = [42, 17, 88, 63]

largest = numbers[0]          # step 1
for num in numbers[1:]:       # step 3
    if num > largest:         # step 2
        largest = num
print(largest)                # step 4
print(max(numbers))           # built-in version
88
88

Natural vs formal languages

Feature Natural (English) Formal (Python)
Ambiguity Full of it; context resolves it Exactly one meaning
Redundancy Verbose, to avoid misunderstanding Concise
Literalness Idiom and metaphor Means exactly what it says

Formal languages are denser, their structure matters, and the details matter.

Which statement describes a formal language?

  1. Context decides what a sentence means
  2. It uses redundancy to prevent misunderstanding
  3. Every valid program has exactly one meaning
  4. Idioms and metaphors are common

Levels of abstraction

Level Closer to Example
High-level language People print("Hello, World!")
Low-level (assembly) Hardware mov eax, 1
Machine code The CPU 10110000 00000000

Python, Java, JavaScript, C, and C++ are high-level languages.

Interpreted, compiled, and hybrid

Interpreted and compiled execution pipelines

Programming constructs

Control structures

  • Sequence: one step after another
  • Selection: choose a path
  • Iteration: repeat steps

Supporting elements

  • Subroutine (function)
  • Nesting
  • Variable and data type
  • Operator
  • Array (collection)

Expressions produce values

Expression with operands and operators

An expression combines values, variables, operators, and function calls. Python evaluates it to produce a single value.

Statements perform actions

Kind Example What happens
Statement x = 5 Assigns 5 to x; no value
Statement if x > 0: Starts a conditional block
Statement import math Loads a module
Expression 2 + 3 Produces 5
Expression len("data") Produces 4

Computing an expression is evaluation; running a statement is execution.

Expressions and statements in code

x = 5            # statement: no value is shown
print(x + 5)     # x + 5 is an expression: 10
if x > 0:        # statement: controls the flow
    print("x is positive")
10
x is positive

Which line is an expression?

  1. total = 0
  2. import math
  3. len("python") * 2
  4. if total > 10:

Number systems

System Base Digits Python literal for 100
Binary 2 0 and 1 0b1100100
Octal 8 0 to 7 0o144
Decimal 10 0 to 9 100
Hexadecimal 16 0 to 9, A to F 0x64

Prefixes: 0b binary, 0o octal, 0x hexadecimal.

Positional notation

Each digit's value = digit ร— baseposition

Number Expansion Value
345 (base 10) 3ร—10ยฒ + 4ร—10ยน + 5ร—10โฐ 345
1011 (base 2) 1ร—2ยณ + 0ร—2ยฒ + 1ร—2ยน + 1ร—2โฐ 11

Binary place values: 8, 4, 2, 1. So 1011โ‚‚ = 8 + 2 + 1 = 11.

Reading 100 in binary

0b1100100
  โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚โ”” 0 ร— 2^0 = 0
  โ”‚โ”‚โ”‚โ”‚โ”‚โ””โ”€ 0 ร— 2^1 = 0
  โ”‚โ”‚โ”‚โ”‚โ””โ”€โ”€ 1 ร— 2^2 = 4
  โ”‚โ”‚โ”‚โ””โ”€โ”€โ”€ 0 ร— 2^3 = 0
  โ”‚โ”‚โ””โ”€โ”€โ”€โ”€ 0 ร— 2^4 = 0
  โ”‚โ””โ”€โ”€โ”€โ”€โ”€ 1 ร— 2^5 = 32
  โ””โ”€โ”€โ”€โ”€โ”€โ”€ 1 ร— 2^6 = 64
                   โ”€โ”€โ”€
                   100

Converting in Python

print(bin(100), oct(100), hex(100))
print(hex(0b1100100))
print(int("0x64", 16), int("0b1100100", 2))
print(0b1011, 0x64)
0b1100100 0o144 0x64
0x64
100 100
11 100

What does print(0b1011) display?

  1. 1011
  2. 11
  3. 0b1011
  4. 13

Character encoding

  • A bit is 0 or 1; a byte is 8 bits
  • Text is stored as numbers: an encoding
  • In ASCII, A is 65, or 1000001
  • UTF-8 extends ASCII to every writing system

ASCII code chart, 1972

Character codes with ord() and chr()

code = ord('A')
print(code, bin(code), hex(code))
print(chr(code))
print(ord('B') - ord('A'), 'B' > 'A')
print(ord('รฉ'), chr(960))
65 0b1000001 0x41
A
1 True
233 ฯ€

Character Codes

  1. Store the decimal code for "C" in c_dec with ord()
  2. Store its binary code in c_bin with bin()
  3. Print these two lines, with a comma between label and value:
Decimal code for C: 67
Binary code for C: 0b1000011

Recap

  • An algorithm is the plan; a program writes it in a language
  • Formal languages are unambiguous, dense, and literal
  • Python is high-level; its automatic bytecode step makes it feel interpreted
  • Sequence, selection, and iteration construct every program
  • Expressions produce values; statements perform actions
  • bin(), hex(), int(), ord(), chr() move between number systems and characters

Basic Syntax

1.2 ยท Think Python

Today's goals

  • Use indentation to mark blocks
  • Split long statements with parentheses
  • Display output with print() and f-strings
  • Read input and convert it to numbers
  • Write comments and docstrings
  • Inspect objects and recognize keywords
  • Call built-in functions and import modules

Indentation defines blocks

for i in range(5):
print(i)
IndentationError: expected an indented block after 'for' statement on line 1
for i in range(3):
    print(i)
0
1
2

One statement per line

total = (
    100
    + 200
    + 300
)
print(total)
total = 100 + 200 + \
        300
600
  • Preferred: one statement per line, parentheses for long expressions
  • Works but fragile: a backslash (a trailing space breaks it)
print("Name:", "Alice", "Age:", 25)
print("Name:" + " Alice" + " Age:", 25)
print("I am " + 25 + " years old")
Name: Alice Age: 25
Name: Alice Age: 25
TypeError: can only concatenate str (not "int") to str

F-strings

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")
My name is Alice and I am 25 years old.
The sum of 10 and 20 is 30

Format specifications

A colon inside the braces controls how the value looks.

Spec Meaning Example output
:.2f 2 decimal places 4.50
:, thousands separators 1,234,567
:.1% percent, 1 decimal place 8.3%
:>8 right-align in 8 characters apple

Combine them: :,.2f gives 1,234,567.89.

Format specifications in code

price = 4.5
revenue = 1234567.891
growth = 0.083
item = "apple"

print(f"Price: ${price:.2f}")
print(f"Revenue: {revenue:,.2f}")
print(f"Growth: {growth:.1%}")
print(f"|{item:>8}|{item:<8}|")
Price: $4.50
Revenue: 1,234,567.89
Growth: 8.3%
|   apple|apple   |

Format spec vs round()

print(round(42.5, 2))
print(f"{42.5:.2f}")
42.5
42.50
  • round() returns a number; Python drops trailing zeros
  • A format spec returns text with exactly the places you ask for

What does print(f"{0.083:.1%}") display?

  1. 0.1%
  2. 0.083%
  3. 8.3%
  4. 8.30%
print("A", "B", "C")
print("A", "B", "C", sep="-")
for num in range(5):
    print(num, end=" ")
A B C
A-B-C
0 1 2 3 4
  • sep: placed between values (default a space)
  • end: added at the end (default a newline)

input() returns a string

age = input("Enter your age: ")
print(type(age))
age = int(age)
print(type(age))
print(f"You are {age} years old.")
Enter your age: 25
<class 'str'>
<class 'int'>
You are 25 years old.

Type conversion: int(), float(), str()

price_text = "19.99"
price = float(price_text)
print(price * 2)

age = 25
message = "I am " + str(age) + " years old"
print(message)
39.98
I am 25 years old

Update a variable from its old value

total = 10
total = total + 5
print(total)

total_minutes = int("135")
print(total_minutes // 60, total_minutes % 60)
15
2 15

The user types 25. What is type(input("Age: "))?

  1. int
  2. float
  3. str
  4. It depends on what the user types

Comments and docstrings

def area_circle(radius):
    """Return the area of a circle given its radius."""
    import math
    return math.pi * radius**2   # pi times r squared

print(area_circle(3))
print(area_circle.__doc__)
28.274333882308138
Return the area of a circle given its radius.

Every value is an object

score = 95
print(type(score))
print(score)
print(id(score))
<class 'int'>
95
4311411656

An object has a type, a value, and an identity.

Keywords are reserved

class = "my first class"
SyntaxError: invalid syntax
Job Keywords
Flow control if, elif, else, for, while, break
Definitions def, class, lambda
Logic and values and, or, not, in, True, None
Imports import, from, as

Built-in functions

scores = [88, 92, 75, 100, 83]
print(len(scores))
print(min(scores), max(scores))
print(sum(scores) / len(scores))
print(sorted(scores))
5
75 100
87.6
[75, 83, 88, 92, 100]

Arguments and return values

print(int("101"), int("101", 2), round(1.2345, 2))

return_value = print("display only")
print(return_value)
101 5 1.23
display only
None
  • Arguments go inside the parentheses
  • Most functions return a value; print() returns None

What does this code display?

x = print("hi")
print(x)
  1. hi then hi
  2. hi then None
  3. None only
  4. An error

Modules and imports

Pattern Code Use
Standard import math math.sqrt(25)
Alias import math as m m.pi
Selective from math import sqrt sqrt(25)
All (avoid) from math import * name conflicts
import math
print(math.sqrt(25), math.pi)
5.0 3.141592653589793

Format a Price Report

Given unit_price = 8.5, total_sales = 12750, and discount_rate = 0.15, print exactly these lines with f-strings and format specifications:

Unit price: $8.50
Total sales: 12,750.00
Discount: 15.0%

Recap

  • Indentation marks blocks; parentheses split long lines
  • print() and f-strings display output; format specs shape it
  • input() returns text; convert with int(), float(), str()
  • Comments are ignored; docstrings are kept
  • Every value is an object; keywords are reserved
  • Built-in functions need no import; modules do