Chapter 1 ยท Think Python
By the end of this chapter, you will be able to:
1.1 ยท Think Python
Learning programming is largely about connecting the dots.
You need enough concepts, examples, and practice to work with, and then you need to connect them.
An algorithm is a finite, ordered set of unambiguous steps that turns input into output.
A recipe is an algorithm: ingredients in, fixed steps, a finished dish out.
Input [42, 17, 88, 63]: remember 42, keep 42, switch to 88, keep 88.
[42, 17, 88, 63]
Output: 88
88
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
Formal languages are denser, their structure matters, and the details matter.
print("Hello, World!")
mov eax, 1
10110000 00000000
Python, Java, JavaScript, C, and C++ are high-level languages.
An expression combines values, variables, operators, and function calls. Python evaluates it to produce a single value.
x = 5
x
if x > 0:
import math
2 + 3
5
len("data")
4
Computing an expression is evaluation; running a statement is execution.
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
total = 0
len("python") * 2
if total > 10:
0b1100100
0o144
100
0x64
Prefixes: 0b binary, 0o octal, 0x hexadecimal.
0b
0o
0x
Each digit's value = digit ร baseposition
Binary place values: 8, 4, 2, 1. So 1011โ = 8 + 2 + 1 = 11.
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
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
print(0b1011)
1011
11
0b1011
13
A
1000001
ord()
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 ฯ
"C"
c_dec
c_bin
bin()
Decimal code for C: 67 Binary code for C: 0b1000011
hex()
int()
1.2 ยท Think Python
print()
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
total = ( 100 + 200 + 300 ) print(total) total = 100 + 200 + \ 300
600
+
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
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
A colon inside the braces controls how the value looks.
:.2f
4.50
:,
1,234,567
:.1%
8.3%
:>8
apple
Combine them: :,.2f gives 1,234,567.89.
:,.2f
1,234,567.89
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 |
round()
print(round(42.5, 2)) print(f"{42.5:.2f}")
42.5 42.50
print(f"{0.083:.1%}")
0.1%
0.083%
8.30%
sep
end
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
input()
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.
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
total = 10 total = total + 5 print(total) total_minutes = int("135") print(total_minutes // 60, total_minutes % 60)
15 2 15
25
type(input("Age: "))
int
float
str
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.
score = 95 print(type(score)) print(score) print(id(score))
<class 'int'> 95 4311411656
An object has a type, a value, and an identity.
class = "my first class"
SyntaxError: invalid syntax
if
elif
else
for
while
break
def
class
lambda
and
or
not
in
True
None
import
from
as
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]
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
x = print("hi") print(x)
hi
math.sqrt(25)
import math as m
m.pi
from math import sqrt
sqrt(25)
from math import *
import math print(math.sqrt(25), math.pi)
5.0 3.141592653589793
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.5
total_sales = 12750
discount_rate = 0.15
Unit price: $8.50 Total sales: 12,750.00 Discount: 15.0%