๐ freeCodeCamp ยท subject
freeCodeCamp Scientific Computing with Python Syllabus
The Scientific Computing with Python syllabus for freeCodeCamp in full: 6 chapters and 19 topics, every one listed below, plus 50 Scientific Computing with Python flashcards with answers.
Scientific Computing with Python syllabus: all 6 chapters
Expand any chapter to see its topics and sub-topics.
-
Python Fundamentals
4 topics- Variables and Data Types
- Conditionals and Loops
- Functions
- Strings and Formatting
-
Data Structures
3 topics- Lists and Tuples
- Dictionaries and Sets
- Comprehensions
-
Object Oriented Python
2 topics- Classes and Objects
- Inheritance and Polymorphism
-
Working with Files and Modules
3 topics- Reading and Writing Files
- Importing Modules
- Regular Expressions
-
Networking and Databases
2 topics- Working with APIs
- SQLite Databases
-
Certification Projects
5 topics- Arithmetic Formatter
- Time Calculator
- Budget App
- Polygon Area Calculator
- Probability Calculator
freeCodeCamp Scientific Computing with Python flashcards โ 50 questions with answers
In Python, what are the four primary primitive data types, and how do you check the type of a variable?
int (integers), float (decimal numbers), str (text strings), and bool (True/False). Use the built-in function type(x) to check a variable's type, e.g. type(3.14) returns <class 'float'>.
What is the difference between dynamic typing and static typing, and which does Python use?
Python is dynamically typed: a variable's type is determined at runtime from the value assigned, and the same name can be rebound to values of different types. Statically typed languages (like C or Java) fix a variable's type at declaration and check it at compile time.
In Python, what do the operators /, //, %, and ** compute? Give the result of each for 7 and 2.
/ is true division: $7 / 2 = 3.5$; // is floor division: $7 \; // \; 2 = 3$; % is modulo (remainder): $7 \bmod 2 = 1$; ** is exponentiation: $7^{2} = 49$.
Which values are considered 'falsy' in Python conditionals?
False, None, zero of any numeric type ($0$, $0.0$), and empty collections: '' (empty string), [] (empty list), () (empty tuple), {} (empty dict), and set(). Everything else evaluates as truthy.
What is the difference between the break and continue statements inside a Python loop?
break exits the loop entirely, skipping any remaining iterations. continue skips the rest of the current iteration and jumps to the next iteration of the loop.
What does the else clause on a Python for or while loop do?
The else block runs only if the loop completes normally, i.e. it was never terminated by a break statement. It is commonly used in search loops to handle the 'not found' case.
In a Python function definition, what is the difference between *args and **kwargs?
*args collects any extra positional arguments into a tuple; **kwargs collects any extra keyword arguments into a dictionary. They let a function accept a variable number of arguments.
What does a Python function return if it has no return statement (or a bare return)?
It returns None. Every Python function returns a value; if none is specified explicitly, the implicit return value is None.
What is a lambda function in Python and what is its syntax?
An anonymous, single-expression function written as lambda parameters: expression. Example: square = lambda x: x**2 defines a function computing $x^{2}$. Lambdas are often passed to functions like sorted(), map(), and filter() as the key or transform.
Name the three main ways to format strings in Python and show the modern preferred one.
1) f-strings: f"Hello {name}" (preferred, Python 3.6+); 2) the str.format() method: "Hello {}".format(name); 3) %-formatting: "Hello %s" % name. F-strings evaluate expressions directly inside the braces.
In an f-string, what does the format spec {value:.2f} do, and what does {n:>8} do?
{value:.2f} formats the number as a float with exactly 2 digits after the decimal point (e.g. 3.14159 becomes 3.14). {n:>8} right-aligns the value in a field 8 characters wide, padding with spaces on the left.
Why are Python strings called immutable, and what happens when you 'modify' one?
Immutable means the character sequence cannot be changed in place; s[0] = 'x' raises a TypeError. Any operation that appears to modify a string (concatenation, replace(), upper()) actually creates and returns a brand-new string object.
What are the key differences between a Python list and a tuple?
Lists are mutable (elements can be added, removed, changed) and written with brackets [1, 2, 3]; tuples are immutable and written with parentheses (1, 2, 3). Tuples can be used as dictionary keys and set elements because they are hashable; lists cannot. Tuples are slightly faster and signal fixed structure.
What does the slice syntax list[start:stop:step] return, and what does lst[::-1] do?
It returns a new list containing elements from index start up to but not including stop, taking every step-th element. lst[::-1] returns a reversed copy of the list. Omitted values default to start=0, stop=len(lst), step=1.
Compare the list methods append(), extend(), and insert().
append(x) adds the single item x to the end of the list; extend(iterable) adds each element of the iterable to the end individually; insert(i, x) inserts x at index i, shifting later elements right. append([1,2]) adds one nested list, while extend([1,2]) adds two elements.
What are the requirements for Python dictionary keys, and what happens when you assign to an existing key?
Keys must be hashable (immutable types such as str, int, float, tuple of immutables); lists and dicts cannot be keys. Assigning to an existing key overwrites its value โ dictionaries hold at most one value per key.
What is the difference between dict[key] and dict.get(key) when the key is missing?
dict[key] raises a KeyError if the key does not exist. dict.get(key) returns None instead (or a chosen fallback via dict.get(key, default)), so it never raises for a missing key.
What are the four main set operations in Python, with their operators?
Union: $A \cup B$ via a | b (elements in either); intersection: $A \cap B$ via a & b (elements in both); difference: $A \setminus B$ via a - b (in a but not b); symmetric difference: $A \triangle B$ via a ^ b (in exactly one). Sets also enforce uniqueness โ duplicates are automatically removed.
Write a list comprehension that produces the squares of the even numbers from 0 to 9, and state the general syntax.
[x**2 for x in range(10) if x % 2 == 0] gives [0, 4, 16, 36, 64], i.e. $x^{2}$ for even $x$. General syntax: [expression for item in iterable if condition] โ the if filter is optional.
How do dictionary comprehensions and set comprehensions differ syntactically from list comprehensions?
Both use braces instead of brackets. A dict comprehension has a key:value pair: {k: v for k, v in pairs}, e.g. {x: x**2 for x in range(5)}. A set comprehension has a single expression: {x % 3 for x in nums}. Brackets [] would instead produce a list.
Show the other 30 Scientific Computing with Python flashcards
What is the difference between a list comprehension and a generator expression in Python?
A list comprehension [x*2 for x in data] builds the whole list in memory immediately. A generator expression (x*2 for x in data) uses parentheses and produces values lazily, one at a time, using constant memory โ but it can only be iterated once.
In a Python class, what is the purpose of the __init__ method and the self parameter?
__init__ is the initializer (constructor) that runs automatically when an object is created; it sets up the instance's attributes. self is the first parameter of instance methods and refers to the specific object being operated on โ Python passes it automatically when you call obj.method().
What is the difference between class attributes and instance attributes in Python?
Class attributes are defined directly in the class body and shared by all instances; instance attributes are assigned on self (usually in __init__) and belong to one specific object. An instance attribute with the same name shadows the class attribute for that instance.
What do the dunder methods __str__ and __repr__ control?
__str__ returns the human-readable string used by print() and str(); __repr__ returns an unambiguous, developer-oriented representation used in the interactive shell and by repr(). If __str__ is missing, Python falls back to __repr__.
In Python inheritance, what does super().__init__() do inside a subclass?
It calls the parent class's __init__ method so the parent's initialization (setting up inherited attributes) runs before or alongside the child's own setup. This avoids duplicating the parent's constructor logic in every subclass.
What is method overriding, and how does it enable polymorphism in Python?
Overriding is defining a method in a subclass with the same name as one in the parent, replacing the inherited behavior. Polymorphism means the same call, e.g. shape.area(), executes different code depending on the object's actual class โ Python dispatches to the most derived implementation at runtime.
What is 'duck typing' in Python?
A style of polymorphism where an object's suitability is determined by the methods and attributes it actually has, not its declared type: 'if it walks like a duck and quacks like a duck, it's a duck.' Code calls obj.quack() without checking isinstance; any object providing quack() works.
Why is the with statement the preferred way to open files in Python?
with open('file.txt') as f: creates a context manager that automatically closes the file when the block exits โ even if an exception occurs โ preventing resource leaks. Without it you must remember to call f.close() manually in a finally block.
What do the file modes 'r', 'w', 'a', and 'r+' mean in Python's open()?
'r' = read only (error if the file doesn't exist); 'w' = write, truncating/overwriting any existing content (creates the file if absent); 'a' = append, writing at the end while preserving existing content; 'r+' = read and write without truncating. Add 'b' for binary mode, e.g. 'rb'.
Compare the file-reading methods read(), readline(), and readlines().
read() returns the entire file as one string; readline() returns the next single line (including its trailing newline); readlines() returns a list of all lines. For large files, iterating directly with 'for line in f:' is most memory-efficient because it streams line by line.
What is the difference between 'import math' and 'from math import sqrt'?
import math binds the whole module; you access members with the prefix, e.g. math.sqrt(16) computes $\sqrt{16} = 4$. from math import sqrt imports only that name into the current namespace so you call sqrt(16) directly. 'import module as alias' (e.g. import numpy as np) gives a shorthand name.
What does the idiom if __name__ == '__main__': accomplish in a Python file?
Code under it runs only when the file is executed directly as a script, not when the file is imported as a module. When imported, __name__ equals the module's name; when run directly, __name__ equals the string '__main__'. It lets a file serve as both a reusable module and a runnable program.
In what order does Python search for a module when you write an import statement?
Python searches sys.path in order: 1) the directory containing the running script (or current directory), 2) directories in the PYTHONPATH environment variable, 3) the standard library, and 4) installed third-party packages in site-packages. The first match wins.
In Python regular expressions, what do the metacharacters \d, \w, \s, ., ^, and $ match?
\d matches a digit 0โ9; \w matches a 'word' character (letter, digit, or underscore); \s matches whitespace; . matches any character except newline; ^ anchors the match to the start of the string; $ anchors it to the end. Capitalized versions (\D, \W, \S) match the complement.
In regex, what do the quantifiers *, +, ?, and {m,n} mean?
* = zero or more repetitions; + = one or more; ? = zero or one (optional); {m,n} = between m and n repetitions inclusive. By default quantifiers are greedy (match as much as possible); appending ? (e.g. *?) makes them lazy/non-greedy.
Compare the re module functions re.search(), re.match(), and re.findall().
re.search(pattern, s) scans the whole string and returns a Match object for the first occurrence (or None); re.match() only matches at the beginning of the string; re.findall() returns a list of all non-overlapping matches (or of captured groups if the pattern has groups).
What is a REST API, and which HTTP methods correspond to the four CRUD operations?
A REST API is a web interface where clients access resources at URLs using standard HTTP methods. CRUD mapping: Create โ POST, Read โ GET, Update โ PUT (or PATCH for partial updates), Delete โ DELETE. Responses typically carry data as JSON.
Using Python's requests library, how do you fetch JSON from an API and check for success?
response = requests.get(url); check response.status_code == 200 (or call response.raise_for_status() to raise on errors); then data = response.json() parses the JSON body into Python dicts/lists. Query parameters are passed with the params= keyword argument.
What do the HTTP status code ranges 2xx, 4xx, and 5xx indicate? Give one key example of each.
2xx = success (200 OK, 201 Created); 4xx = client error โ the request was wrong (400 Bad Request, 401 Unauthorized, 404 Not Found, 429 Too Many Requests); 5xx = server error โ the server failed (500 Internal Server Error, 503 Service Unavailable).
What sequence of steps does a Python program follow to run a query against an SQLite database with the sqlite3 module?
1) conn = sqlite3.connect('file.db') opens/creates the database; 2) cur = conn.cursor() gets a cursor; 3) cur.execute(sql, params) runs the SQL; 4) fetch results with cur.fetchone()/fetchall(); 5) conn.commit() saves any changes (INSERT/UPDATE/DELETE); 6) conn.close() closes the connection.
Why should you use parameterized queries like cur.execute('SELECT * FROM users WHERE name = ?', (name,)) instead of string formatting in SQL?
Placeholders (?) let the database driver safely escape user input, preventing SQL injection attacks where malicious input alters the query's structure. Building SQL with f-strings or concatenation embeds raw user text directly into the command and is a critical security flaw.
What makes SQLite different from client-server databases like MySQL or PostgreSQL?
SQLite is serverless and embedded: the entire database lives in a single file on disk and the library runs inside your application process โ no separate server, no network, no user accounts. It ships in Python's standard library (sqlite3), making it ideal for local apps and prototyping, but it handles concurrent writers poorly compared to server databases.
In the freeCodeCamp Arithmetic Formatter project, what five error conditions must arithmetic_arranger reject, and with which messages?
1) More than 5 problems โ 'Error: Too many problems.'; 2) an operator other than + or - (e.g. * or /) โ "Error: Operator must be '+' or '-'."; 3) non-digit characters in an operand โ 'Error: Numbers must only contain digits.'; 4) an operand longer than 4 digits โ 'Error: Numbers cannot be more than four digits.' Only + and - are supported; multiplication/division are invalid.
How is each problem laid out in the Arithmetic Formatter's vertical output?
Right-align both operands; the width of each problem is the length of the longer operand plus 2 (one for the operator, one for the space after it). The operator sits on the left of the second line, dashes span the full problem width, problems are separated by exactly 4 spaces, and answers appear on a bottom line only if show_answers is True.
In the freeCodeCamp Time Calculator, what are the inputs and required output forms of add_time()?
Inputs: a 12-hour start time like '3:00 PM', a duration like '3:10' (hours:minutes), and an optional starting day of the week. Output stays in 12-hour format with AM/PM and appends nothing if the result is the same day, '(next day)' if it lands 1 day later, or '(n days later)' for $n \geq 2$. If a day was given, the result includes the new capitalized day name, e.g. '6:10 PM, Monday (20 days later)'.
What arithmetic converts a 12-hour time plus a duration into the final time and days elapsed (Time Calculator logic)?
Convert start to minutes past midnight (add $12 \times 60$ for PM, treat 12 AM as 0); add the duration in minutes. Days elapsed $= \left\lfloor \frac{\text{total minutes}}{1440} \right\rfloor$; remaining time $= \text{total} \bmod 1440$. Then hour $= \left\lfloor \frac{\text{remaining}}{60} \right\rfloor$, minute $= \text{remaining} \bmod 60$, and convert back to 12-hour AM/PM. New weekday index $= (\text{start index} + \text{days}) \bmod 7$.
In the freeCodeCamp Budget App, what do the Category methods deposit(), withdraw(), transfer(), and check_funds() do?
deposit(amount, description) appends {'amount': amount, 'description': description} to the ledger. withdraw() appends a negative amount only if check_funds passes, returning True/False. transfer(amount, other) withdraws with description 'Transfer to [Dest]' and deposits into the other category as 'Transfer from [Source]', returning True/False. check_funds(amount) returns True only if amount does not exceed the current balance (sum of ledger amounts).
How is a Category's string output formatted in the Budget App?
A title line of exactly 30 characters with the category name centered in asterisks; then one line per ledger item: the first 23 characters of the description, then the amount right-aligned with 2 decimal places in 7 characters (line total 30); finally a line 'Total: x.xx'. Example: '*************Food*************'.
In the freeCodeCamp Polygon Area Calculator, what formulas does the Rectangle class use for area, perimeter, and diagonal?
For width $w$ and height $h$: area $= w \times h$, perimeter $= 2w + 2h$, and diagonal $= \sqrt{w^{2} + h^{2}}$. get_amount_inside(other) returns how many times another shape fits without rotation: $\left\lfloor \frac{w}{w'} \right\rfloor \times \left\lfloor \frac{h}{h'} \right\rfloor$.
How does the Square class relate to Rectangle in the Polygon Area Calculator project, and what constraint must set_side enforce?
Square is a subclass of Rectangle whose constructor calls the parent with width = height = side, so it inherits get_area, get_perimeter, get_diagonal, etc. Its set_side(s) method must update both width and height to s (and setting width or height on a Square updates both), keeping the invariant $w = h$. Its string form is 'Square(side=s)' instead of 'Rectangle(width=w, height=h)'.
freeCodeCamp Scientific Computing with Python FAQ
What is in the freeCodeCamp Scientific Computing with Python syllabus?
freeCodeCamp Scientific Computing with Python is split into 6 chapters: Python Fundamentals, Data Structures, Object Oriented Python, Working with Files and Modules, Networking and Databases and Certification Projects. Together they contain 19 topics.
How many chapters are in freeCodeCamp Scientific Computing with Python?
6 chapters, containing 19 topics. The largest chapter is Certification Projects, with 5 topics.
Are there flashcards for freeCodeCamp Scientific Computing with Python?
Yes โ a 50-card Scientific Computing with Python deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.