Chapter 01
Language basics
The building blocks every program uses: values and types, decisions, loops, functions, strings and missing values. Get these automatic before anything else.
Variables and types
Also called data types, primitives
- What
- A variable is a name that refers to a value. The value has a type, such as integer, decimal number, boolean or string, which decides what you can do with it and how much memory it uses.
- Why
- Types stop you adding a name to a price by accident and tell the reader what a value means. Choosing the right one (a whole number for a count, a decimal type for money) avoids a whole class of bugs.
name = "Ada"
age = 36
height = 1.70
is_admin = False
age += 1
print(f"{name} is {age}")Watch out
Reusing one variable for different meanings in the same function, so a reader cannot tell what it holds at any line.
Static and dynamic typing
Also called type checking, type inference, dynamic typing, statically typed
- What
- Statically typed languages (Java, C++, C#) check types when the code is compiled. Dynamically typed languages (Python, JavaScript) check them while the program runs. Type hints and TypeScript add optional static checks to the dynamic ones.
- Why
- It tells you when a type mistake will surface: before the program runs, or only when that line executes. It also explains why editors can autocomplete so much more in typed code.
Watch out
Treating var or auto as dynamic typing: the type is still fixed at compile time, the compiler just works it out for you.
Conditionals
Also called if else, ternary, switch
- What
- Code that runs only when a condition is true, with
else ifbranches checked in order and an optionalelsefor everything left. The ternary form picks one of two values in a single expression. - Why
- Every decision in a program, from validating input to choosing a price band, is a conditional. Clear ordering of branches is what keeps the logic readable.
if score >= 90:
grade = "A"
elif score >= 50:
grade = "pass"
else:
grade = "fail"
label = "adult" if age >= 18 else "minor"Watch out
Ordering checks from loosest to strictest, so a later branch such as score >= 90 can never be reached.
Loops
Also called for loop, while loop, foreach, iteration
- What
- A loop repeats a block of code: a for-each loop visits every item in a collection, a counting
forloop runs over a range of indexes, and awhileloop repeats as long as a condition holds. - Why
- Processing every order, retrying a request or reading a file line by line are all loops. Prefer for-each when you only need the items, because there is no index to get wrong.
for name in names:
print(name)
for i, name in enumerate(names):
print(i, name)
while attempts < 3:
attempts += 1Watch out
Off-by-one errors: looping with <= over the length reads one element past the end.
Functions
Also called methods, parameters, return value
- What
- A named block of code that takes inputs (parameters), does one job and can return a result. In Java and C# functions live inside classes and are called methods.
- Why
- Functions let you name an idea, reuse it and test it on its own. A program built from small functions is far easier to read and change than one long script.
def area(width: float, height: float = 1.0) -> float:
return width * height
print(area(3, 4))
print(area(width=3))Watch out
Writing a function that both calculates and prints: return the value and let the caller decide what to do with it.
Scope
Also called block scope, global variables, local variables
- What
- Scope is the part of the code where a name is visible. Variables declared inside a function or block exist only there; globals are visible everywhere in a file or program.
- Why
- Keeping variables in the smallest scope means fewer places can change them, so bugs are easier to find and names do not clash.
- Example
- A
totaldeclared inside a loop is reset on every pass and gone after the loop. Declare it before the loop if you need the sum afterwards.
Watch out
Relying on global mutable variables: any function can change them, so the order of calls silently changes results.
Strings and formatting
Also called string interpolation, f-strings, template literals
- What
- A string is a sequence of text characters. Languages give you methods to trim, split, join, search and slice them, plus interpolation to build text from values.
- Why
- Most input and output is text: file lines, form fields, JSON and log messages. Interpolation is clearer and safer than gluing pieces together with
+.
s = " Hello, World "
clean = s.strip().lower()
parts = clean.split(", ")
joined = "-".join(parts)
print(f"{joined} has {len(joined)} chars")
print(clean[:5])Watch out
Building a big string with + inside a loop in Java, C# or Python copies it every time; use StringBuilder or a join.
Null and missing values
Also called None, null, undefined, nullptr, optional
- What
- A special value meaning "nothing here":
Nonein Python,nullandundefinedin JavaScript,nullin Java and C#. C++ usesstd::optionalfor a value that may be absent. - Why
- Lookups, searches and optional input often have no result. Handling that case on purpose is what prevents the most common runtime crash in most languages.
user = users.get("ada")
if user is None:
print("no such user")
name = user.name if user else "guest"Watch out
Calling a method on a value that can be null without checking first, which throws a null reference error far from where the null came from.
Reading and validating input
Also called parsing, user input, stdin
- What
- Reading text typed by a user or passed to the program, then converting it to the type you need, such as an integer, and rejecting anything that does not fit.
- Why
- Input is where programs meet the messy world. Validating it at the edge means the rest of your code can trust its data.
raw = input("Age: ")
try:
age = int(raw)
except ValueError:
print("Please type a whole number")Watch out
Converting input without handling failure: users type spaces, letters and empty lines, and the program crashes.