Variables

0.0(0)
studied byStudied by 0 people
GameKnowt Play
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/17

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

18 Terms

1
New cards

Variable

An identifier or name bound to a value held in memory.

2
New cards

Parameter

A special kind of variable used in function definitions that receives argument values during function calls.

3
New cards

Variable Declaration

Defines and establishes a variable name and its data type.

4
New cards

Variable Assignment Statement

A statement where the left-hand side is a variable name and the right-hand side is an expression that evaluates to a value to be bound to the variable.

5
New cards

Variable Initialization

The first assignment of a value to a variable, which must occur before the variable can be accessed.

6
New cards

Variable Access

The usage of a variable’s identifier in an expression, allowing the retrieval of its current bound value.

7
New cards

UnboundLocalError

An error that occurs when accessing a local variable before it has been initialized.

8
New cards

NameError

An error that occurs when trying to access a variable that has not been defined.

9
New cards

Double Function Example

A function demonstrating variable declaration and initialization, where y = x * 2 underlines variable usage.

10
New cards

State of a Program

The current values stored in variables which determine how a program behaves during execution.

11
New cards

Storage of Computed Values

Variables store results of computations for later use, enhancing code efficiency and readability.

12
New cards

Updating Variable State

The capability of variables to change values over time, allowing dynamic program behavior.

13
New cards

Explain how a 'variable' fundamentally differs from a 'parameter' in the context of a function executing within a program.

A variable is a named storage location for a value in memory, used throughout a program or within a specific scope. A parameter, while also a variable, is specifically a placeholder defined in a function's signature that receives a value (an argument) when the function is called. Its scope is typically limited to the function's execution.

14
New cards

Consider a language like C++ where variable declaration is explicit. If you write int x; and then immediately try to use x in an expression like y = x + 5; without initialization, what is the most likely outcome, and why might Python behave differently?

In C++, int x; declares the variable x but does not initialize it, meaning x holds an unpredictable 'garbage' value. Using it would lead to undefined behavior or a runtime error. Python, being dynamically typed and requiring initialization before use, would raise a UnboundLocalError (if x were local to a function) or a NameError (if x was never assigned in its current scope), preventing access to an uninitialized value.

15
New cards

Analyze the following Python code snippet:

def calculate_product(a, b):
    result = a * b
    return result

val1 = 10
val2 = 20
product = calculate_product(val1, val2)
print(product)

Identify:

  1. A variable declaration (conceptually, as Python doesn't have explicit type declarations).
  2. A variable assignment statement.
  3. A parameter.
  4. A variable initialization.
  1. Variable Declaration (conceptually): val1 = 10, val2 = 20, product = calculate_product(...), result = a * b. In Python, the act of assigning a value to a new name makes it a variable, effectively 'declaring' it. For a and b, they are declared as parameters when calculate_product is defined.
  2. Variable Assignment Statement: Examples include val1 = 10, val2 = 20, result = a * b, product = calculate_product(val1, val2).
  3. Parameter: a and b in the function definition def calculate_product(a, b):.
  4. Variable Initialization: val1 = 10, val2 = 20, result = a * b, and product = calculate_product(...) are all examples where the variables are given their first values.
16
New cards

Explain the precise difference between an UnboundLocalError and a NameError in Python, providing a minimal code example that would trigger each.

  • UnboundLocalError: Occurs when a local variable is referenced before it has been assigned a value within its local scope. This typically happens inside a function when a variable is used before its initialization.
    python def func(): print(x) # Raises UnboundLocalError x = 10 func()
  • NameError: Occurs when an identifier (variable name, function name, etc.) is referenced but has not been defined at all in any accessible scope (local, enclosing, global, or built-in).
    python print(y) # Raises NameError, as 'y' is not defined
17
New cards

Consider the 'Double Function Example': def double(x): y = x * 2; return y. How does this simple function exemplify the 'State of a Program' and 'Updating Variable State' concepts, even with just two local variables?

This function demonstrates the 'State of a Program' by showing that at any given point during its execution, the values of x and y define its current state. For instance, if x is 5, the state immediately after y = x * 2 would have x=5 and y=10.

It exemplifies 'Updating Variable State' because when double() is called with a different argument (e.g., double(7)), the value of x changes from its previous call, and consequently, the calculation y = x * 2 updates the value of y based on this new x. This dynamic binding of different values to x and y illustrates the essence of updating variable state to achieve varied program behavior.

18
New cards

Justify why the 'Storage of Computed Values' in variables is crucial for both code efficiency AND readability, using an example beyond a simple arithmetic operation (e.g., consider object creation or complex string manipulation).

Storing computed values in variables is crucial because:

  • Efficiency: If a complex or time-consuming computation (e.g., fetching data from a database, parsing a large XML file, or a computationally intensive mathematical model) is needed multiple times, storing its result in a variable prevents redundant re-computation. Calling result = expensive_calculation() once and then using result multiple times is far more efficient than calling expensive_calculation() every time it's needed.

  • Readability: Variables allow you to give meaningful names to intermediate or final results, making the code's intent clearer. Instead of process_data(read_file('config.json')['users'][0]['id'], sha256(get_password_hash()).hexdigest()), you can write:
    python user_config = read_file('config.json') first_user_id = user_config['users'][0]['id'] hashed_password = sha256(get_password_hash()).hexdigest() process_data(first_user_id, hashed_password)
    This significantly improves readability by breaking down a complex line into understandable components, each identified by a descriptive variable name.