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

Is Python strongly typed?

Yes; incompatible types are not generally coerced silently.

4
New cards

Does CPython compile source code?

Yes; it compiles .py source to bytecode before executing it.

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 is the use of python --version?

Displays the version of the selected Python interpreter.

7
New cards

What is py on Windows?

A launcher/manager that can select installed Python versions.

8
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.

9
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.

10
New cards

Why use VS Code Pylance?

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

11
New cards

What does isort do?

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

12
New cards

What is Jupyter?

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

13
New cards

What is an ipykernel?

A Python execution kernel that Jupyter can use to run notebook cells.

14
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().

15
New cards

What is PascalCase used for?

Conventionally for class names.

16
New cards

What characters can Python identifiers contain?

Letters, digits, and underscores; they cannot begin with a digit.

17
New cards

What does the type() function return?

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

18
New cards

What is int?

Python's integer numeric type.

19
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.

20
New cards

What is str?

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

21
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.

22
New cards

What does input() return?

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

23
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.

24
New cards

What is a docstring?

A string literal documenting a module, class, or function.

25
New cards

What is a type hint?

An annotation describing an expected type, usually checked by tooling.

26
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.

27
New cards

What does int(3.9) return?

3; converting a float to int truncates toward zero.

28
New cards

What does / do?

True division; it produces a float for ordinary numeric operands.

29
New cards

What does // do?

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

30
New cards

What does % do?

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

31
New cards

What does ** do?

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

32
New cards

What does is compare?

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

33
New cards

How should None normally be compared?

Use is None or is not None.

34
New cards

What do and, or, not do?

Logical conjunction, disjunction, and negation.

35
New cards

Name common falsy values.

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

36
New cards

What is if/elif/else for?

Conditional branching based on expressions.

37
New cards

What does case _ mean?

A wildcard/default case that matches any value.

38
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.

39
New cards

What does break do?

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

40
New cards

What does continue do?

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

41
New cards

What is enumerate(iterable) for?

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

42
New cards

What does the walrus operator := do?

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

43
New cards

What does a chained comparison mean?

Example: 1 < x < 10 tests both bounds without repeating x.

44
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.

45
New cards

What does return do?

Ends a function call and supplies its result to the caller.

46
New cards

What is a default parameter?

A parameter with a default argument used if omitted.

47
New cards

What does *args capture?

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

48
New cards

What is a keyword argument?

An argument provided by parameter name, e.g. greet(name='Ann').

49
New cards

What is LEGB?

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

50
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.

51
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].

52
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.

53
New cards

What is s[::-1]?

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

54
New cards

What is a negative index?

An index counting backward from the end; -1 is last.

55
New cards

What does split() do?

Splits a string into a list using a delimiter or whitespace.

56
New cards

What does ' '.join(parts) do?

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

57
New cards

What does lower() do?

Returns a lowercase copy of a string.

58
New cards

What is an f-string?

A formatted string literal that evaluates expressions inside braces.

59
New cards

What is an r-string?

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

60
New cards

Are strings mutable?

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

61
New cards

What is a list?

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

62
New cards

What is a set?

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

63
New cards

What is a dict?

An insertion-ordered, mutable key-value mapping with unique hashable keys.

64
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.

65
New cards

Can a tuple contain a list?

Yes; the tuple is immutable, but the nested list can still be modified.

66
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]).

67
New cards

What is list.extend(xs)?

Appends each element of iterable xs to the list.

68
New cards

What is list.remove(x)?

Removes the first element equal to x; raises ValueError if missing.

69
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.

70
New cards

How is sorted(xs) different from xs.sort()?

sorted returns a new list; sort mutates a list and returns None.

71
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.

72
New cards

How do you sort case-insensitively?

Use key=str.lower or key=str.casefold.

73
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).

74
New cards

What does list[a:b:c] mean?

Slice from a to b exclusive, stepping by c.

75
New cards

What is a list comprehension?

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

76
New cards

Give a comprehension filtering even numbers.

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

77
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.

78
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.

79
New cards

What does tuple.count(x) do?

Counts occurrences of x.

80
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.

81
New cards

Why use a set to remove duplicates?

It retains only one occurrence of each equal, hashable element.

82
New cards

What does set.add(x) do?

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

83
New cards

How does set.remove differ from discard?

remove raises KeyError if absent; discard does not.

84
New cards

What is set union?

Elements in either set; A | B.

85
New cards

What is set intersection?

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

86
New cards

What is symmetric difference?

Elements in exactly one of the sets; A ^ B.

87
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.

88
New cards

Can a set contain a list?

No; lists are unhashable.

89
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.

90
New cards

How does d[key] differ from d.get(key)?

Missing d[key] raises KeyError; get returns its default.

91
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().

92
New cards

What does dict.values() return?

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

93
New cards

What does dict.update(mapping) do?

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

94
New cards

What does dict.popitem() do?

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

95
New cards

What is a dictionary comprehension?

A mapping built with {key_expr: value_expr for item in iterable}.

96
New cards

What is shallow copying?

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

97
New cards

What happens when b = a for a list?

Both names reference the same list; mutations through either are visible.

98
New cards

What is collections.OrderedDict?

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

99
New cards

Why use OrderedDict if dict preserves order?

For operations like move_to_end and order-sensitive behavior.

100
New cards

What does OrderedDict.popitem(last=False) do?

Removes and returns the first key-value pair.