Python Fundamentals: Syntax, Types, Operators & Functions

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/239

encourage image

There's no tags or description

Looks like no tags are added yet.

240 Terms

1
New cards

What is Python?

Python is a high-level, general-purpose language with dynamic typing and indentation-based syntax. Common uses include automation, APIs, data analysis, and AI.

2
New cards

What does dynamically typed mean?

Types belong to objects, not fixed variable declarations. A variable can refer to an integer and later to a string; type errors are checked at runtime.

3
New cards

What executes Python bytecode in CPython?

CPython first compiles .py source into bytecode, which its Python Virtual Machine executes. Python is therefore not simply "uncompiled."

4
New cards

How does Python mark blocks of code?

Indentation defines blocks after a colon, such as under if, for, def, and class. Consistent indentation is syntactically required.

5
New cards

What are .py files?

Files ending in .py contain Python source code and can be executed as scripts or imported as modules.

6
New cards

What does python app.py do?

Starts the selected Python interpreter and executes the code in app.py, using the current environment when applicable.

7
New cards

What does py -3.12 app.py do?

The Windows Python launcher selects Python 3.12 to run app.py, provided that version is installed.

8
New cards

What is Python's interactive REPL?

REPL means Read-Eval-Print Loop. It lets you enter code interactively, see immediate results, and test small snippets.

9
New cards

Why use VS Code Pylance?

Pylance provides autocompletion, symbol navigation, diagnostics, and optional static type checking in VS Code.

10
New cards

What does isort do?

isort automatically orders and groups imports consistently, reducing manual formatting and merge conflicts.

11
New cards

What is Jupyter?

Jupyter runs code in interactive cells alongside markdown and output, making it useful for analysis and demonstrations.

12
New cards

Are Python identifiers case-sensitive?

Yes. Variables called name and Name are different because Python distinguishes uppercase and lowercase letters.

13
New cards

What is snake_case used for?

PEP 8 commonly uses snake_case for variables, function names, and modules, such as student_name and get_student().

14
New cards

What is UPPER_SNAKE_CASE used for?

UPPER_SNAKE_CASE conventionally marks constants such as MAX_RETRIES; Python does not enforce immutability.

15
New cards

What does the type() function return?

type(obj) returns the object's class or type; e.g., type(42) is int.

16
New cards

What does isinstance(x, int) check?

Returns True if x is an int or an instance of its subclass; bool is a subclass of int in Python.

17
New cards

What is float?

float is Python's floating-point number type for values such as 3.14; many decimal values are approximations in binary.

18
New cards

What is str?

str is the immutable Unicode text type. Indexing and slicing work, but characters cannot be reassigned in place.

19
New cards

What type is None?

None is the sole instance of NoneType and commonly represents a missing or absent result; compare it using is None.

20
New cards

What does input() return?

input() always returns text as str. Convert with int() or float() when numerical input is required.

21
New cards

How do you write a single-line comment?

Use # to begin a comment until the end of the line; comments explain intent without affecting execution.

22
New cards

What does len() return?

len(obj) reports the number of elements for supported objects, such as a list's items or a string's characters.

23
New cards

Are type hints enforced automatically at runtime?

No. Annotations document intended types and support tools; Pydantic or explicit code can validate them at runtime.

24
New cards

What does int('42') return?

It converts the numeric string "42" into the integer 42, which can then be used in arithmetic.

25
New cards

What happens for int('hello')?

int("hello") raises ValueError because the string cannot be interpreted as a valid integer.

26
New cards

What does // do?

// performs floor division, rounding toward negative infinity: 7 // 2 == 3, but -7 // 2 == -4.

27
New cards

What does % do?

% calculates the remainder consistent with floor division. For example, 10 % 3 == 1; commonly used to test evenness.

28
New cards

What does ** do?

** raises a value to a power, such as 2 ** 3 == 8. It also supports fractional exponents.

29
New cards

What does is compare?

is checks whether two names refer to the exact same object; == checks whether their values compare equal.

30
New cards

What does in test?

in checks membership, e.g., 2 in [1,2] or "py" in "python"; dictionaries test membership among keys.

31
New cards

What is a falsy value?

A falsy value behaves like False in if or while conditions, even if it is not the bool object False.

32
New cards

Name common falsy values.

False, None, 0, 0.0, "", [], {}, (), and set() are falsy; most nonempty objects are truthy.

33
New cards

What is match/case?

match/case selects branches using structural patterns; case _ is a wildcard fallback. It is more powerful than a basic switch.

34
New cards

What is a match guard?

A match guard is an additional condition written as case pattern if condition:; the case matches only if both succeed.

35
New cards

What does break do?

break immediately ends the nearest for or while loop, then execution continues after the loop.

36
New cards

What does continue do?

continue skips the rest of the current loop iteration and proceeds to the next iteration.

37
New cards

What is enumerate(iterable) for?

enumerate(items) yields (index, value) pairs; useful when you need a position while iterating.

38
New cards

What does the walrus operator := do?

The := operator assigns a value as part of an expression, such as while (line := file.readline()):.

39
New cards

What does def do?

def introduces a function definition: def add(a, b): return a + b. The body runs when the function is called.

40
New cards

What is the difference between parameter and argument?

A parameter is a name in the function definition; an argument is the actual value passed by a caller.

41
New cards

What does a function return by default?

A function without a return statement, or with a bare return, returns None.

42
New cards

What does *args capture?

*args gathers extra positional arguments into a tuple, enabling functions to accept varying numbers of positional inputs.

43
New cards

What does **kwargs capture?

**kwargs collects extra keyword arguments into a dictionary of parameter names and values.

44
New cards

What is LEGB?

LEGB is Python's name lookup order: Local, Enclosing, Global, and Built-in.

45
New cards

What does nonlocal do?

nonlocal lets an inner function rebind a variable in the nearest enclosing function scope rather than creating a new local.

46
New cards

What is a common lambda use?

lambda defines a short anonymous expression-based function, often a key function for sorting: key=lambda x: x[1].

47
New cards

What is a mutable default argument pitfall?

Mutable defaults such as def f(items=[]) are reused across calls. Use None and create a new list inside the function.

48
New cards

What is s[::-1]?

s[::-1] returns a reversed copy of the string using a slice with a step of -1.

49
New cards

What does strip() do?

strip() returns a copy without leading or trailing whitespace. It does not remove spaces in the middle of the string.

50
New cards

What does ' '.join(parts) do?

" ".join(parts) combines the strings in parts, inserting a space between neighboring elements.

51
New cards

What does replace(old, new) do?

replace(old, new) returns a new string with matching substrings substituted; the original str is unchanged.

52
New cards

What does title() do?

title() produces a new title-cased string, typically capitalizing words; it may not match linguistic title-case rules.

53
New cards

What is an r-string?

An r-prefixed literal treats most backslashes literally, useful for regular expressions and Windows paths.

54
New cards

Are strings mutable?

No. Strings are immutable; methods like upper(), replace(), and strip() return a new string.

55
New cards

What is a list?

A list is an ordered, mutable sequence supporting duplicate and mixed-type elements; e.g., [1, "a", 1].

56
New cards

What is a set?

A set contains unique, hashable elements and does not guarantee insertion order; ideal for membership and deduplication.

57
New cards

Which collections preserve insertion order?

Lists and tuples are ordered sequences; dictionaries preserve key insertion order in modern Python. Sets guarantee no ordering.

58
New cards

Which Python built-in collections are mutable?

list, dict, and set are mutable; tuple, str, and frozenset are immutable. A tuple may still contain a mutable object.

59
New cards

What is list.append(x)?

append(x) adds x as a single final element. append([2,3]) adds one nested list, unlike extend([2,3]).

60
New cards

What is list.insert(i, x)?

insert(i, x) adds x immediately before position i, shifting later list items right.

61
New cards

What does list.pop() do?

pop() removes and returns the last list item by default; pop(i) removes at index i. Empty lists raise IndexError.

62
New cards

What does list.clear() do?

clear() mutates the existing list, removing all elements without creating a replacement list.

63
New cards

How do you sort a list descending?

items.sort(reverse=True) modifies the list; sorted(items, reverse=True) creates a new sorted list.

64
New cards

What does list.reverse() do?

reverse() reverses the existing list in place and returns None; reversed(items) produces a reverse iterator.

65
New cards

How do you test membership in a list?

Use item in items. For lists, membership testing checks values sequentially and is generally O(n).

66
New cards

What is a list comprehension?

A list comprehension creates a new list concisely: [x*x for x in nums if x > 0].

67
New cards

Give a comprehension filtering even numbers.

[x for x in nums if x % 2 == 0] includes only values divisible by 2.

68
New cards

How does a conditional expression differ inside comprehensions?

[x if cond else y for ...] picks an output for each element; [x for ... if cond] removes elements not meeting the condition.

69
New cards

How do you make a one-element tuple?

Use (42,) or 42,; the comma, not the parentheses alone, creates the one-element tuple.

70
New cards

What does tuple.index(x) do?

tuple.index(x) returns the position of the first matching element and raises ValueError if the value is absent.

71
New cards

How can you modify values represented by a tuple?

You cannot assign tuple elements. Create a new tuple, or modify a mutable object already stored inside it.

72
New cards

What does set.add(x) do?

add(x) inserts one hashable element if not already present; set elements remain unique.

73
New cards

What does set.pop() remove?

set.pop() removes and returns an arbitrary element. Unlike list.pop(), it does not mean the last item.

74
New cards

What is set intersection?

A & B returns elements shared by both sets, e.g., {1,2} & {2,3} gives {2}.

75
New cards

What is set difference?

A - B returns members present in A but not B; set difference is not symmetric.

76
New cards

What is frozenset?

frozenset is an immutable, hashable set type (when its elements are hashable), useful as a dictionary key or set member.

77
New cards

Why can True and 1 be duplicates in a set?

True == 1 and hash(True) == hash(1); a set treats them as equivalent and stores one representative.

78
New cards

What does dict.get(key) do?

get(key, default=None) retrieves a value without raising KeyError if the key is missing; missing keys yield the default.

79
New cards

What does dict.items() return?

items() provides a dynamic view of (key, value) pairs for iteration, e.g., for k,v in d.items().

80
New cards

What does dict.values() return?

values() produces a dynamic view of the dictionary's current values rather than an independent list.

81
New cards

What does dict.update(mapping) do?

update(other) adds new key-value pairs and overwrites values for existing keys in place.

82
New cards

What does dict.popitem() do?

popitem() removes and returns the most recently inserted pair in modern Python; raises KeyError when empty.

83
New cards

What is shallow copying?

A shallow copy duplicates only the outer container. Nested mutable objects are still shared between the two copies.

84
New cards

What is deepcopy()?

copy.deepcopy(obj) recursively copies supported nested objects, avoiding shared references in many mutable structures.

85
New cards

What is collections.OrderedDict?

OrderedDict is a dict subclass with explicit reordering operations such as move_to_end(), beyond ordinary dict ordering.

86
New cards

What does OrderedDict.move_to_end(k) do?

move_to_end(key) moves an existing entry to the end; last=False moves it to the beginning.

87
New cards

What is collections.namedtuple?

namedtuple creates an immutable tuple subtype with named attributes, e.g., Point(2,3).x, while retaining index access.

88
New cards

Is a namedtuple mutable?

Yes, it is immutable: named fields cannot be reassigned. Use _replace() to produce a modified copy.

89
New cards

What does namedtuple._replace(x=5) do?

_replace(x=5) creates a new namedtuple with x changed; it leaves the original object untouched.

90
New cards

What does Counter('banana')['a'] equal?

Counter("banana") counts characters; "a" appears three times, so its count is 3.

91
New cards

What does Counter.most_common(2) return?

most_common(2) returns up to two (item, count) pairs ranked by frequency, useful for top-occurrence queries.

92
New cards

What does Counter.subtract(iterable) do?

subtract(iterable) decreases frequencies based on occurrences; unlike normal set subtraction, negative counts can remain.

93
New cards

What does Counter A | B compute?

A | B combines Counters using the maximum count per key, not ordinary set-style uniqueness.

94
New cards

What is procedural programming?

Procedural programming organizes a program around a sequence of commands and functions rather than object state.

95
New cards

What is a class?

A class defines the data and behavior of instances, e.g., class Student:; each created object is an instance.

96
New cards

What is self?

self is the conventional name for the instance passed to an instance method; used to access self.name or other attributes.

97
New cards

Does self have to be named self?

Technically no: self is a naming convention. However, using another name would confuse readers and tools.

98
New cards

What does __init__ do?

__init__ initializes an object after creation, often assigning instance attributes; __new__ actually creates the instance.

99
New cards

What is a class attribute?

A class attribute belongs to the class and is looked up by instances unless an instance attribute shadows it.

100
New cards

What does __str__ define?

__str__ returns an informal, human-readable representation used by str(obj) and usually print(obj).