Python Flashcards

Fundamentals

1
Q

What is an algorithm?

A

An algorithm is a step-by-step set of instructions or rules designed to solve a specific problem or perform a task.

It’s like a recipe for solving a problem, providing a clear and unambiguous sequence of actions.

Our goal in computer science is to take a problem and develop an algorithm that can serve as a general solution.

Once we have such a solution, we can use our computer to automate its execution using programming.

Programming is a skill that allows a computer scientist to take an algorithm and represent it in a notation (a program) that can be followed by a computer.

Key Points:
1. Input/Output: Algorithms take input and produce output.
2. Finite: They must finish after a certain number of steps.
3. Precise: Each step must be clear and unambiguous.
4. Effective: Algorithms efficiently solve problems.

Example:

Think of an algorithm as a cooking recipe. Each step tells you exactly what to do, from gathering ingredients (input) to producing a dish (output).

Importance:

Understanding algorithms is crucial for programmers as they form the foundation for writing efficient and logical code.

For improved precision, algorithms are often written in pseudocode.

Pseudocode is a notation that is more precise than English but generally not as precise as a programming language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are values and data types in Python?

A

Values:**

  • Values are fundamental entities manipulated by a program, such as numbers or words, categorized into different data types/classes. Examples include 5 (result of 2 + 3) and “Hello, World!”.

Data Types:**

  • Values are categorized into different data types/classes. For instance, 4 is an integer, and “Hello, World!” is a string.

Specifying Values in Python:**

  • Values are specified directly in Python programs. Numbers are literals (e.g., 5 or 4.32), and strings are specified by enclosing characters in quotation marks (e.g., “Hello, World!”).

Internal Representation:**

  • The Python interpreter creates internal representations (objects) of specified literals during program execution. These representations allow manipulation, such as multiplying numbers.

Printed Representation:**

  • Internal representations can’t be directly seen, but the print function shows a printed representation in the output window.
  • The printed representation of a number follows the familiar decimal format.
  • For character strings, the printed representation omits the quotation marks used in the program’s literal.

Example:**

print(3.2)
print("Hello, World!")

Note:

In Python, numbers with decimal points belong to the float class.
The terms class and type can be used interchangeably at this stage.
Later, you may encounter other object types like lists and dictionaries, each with its own literal representation and print format.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are operators and operands in Python?

A

Operators and Operands:

  • Operators are special tokens representing computations, such as addition, multiplication, and division.
  • The values that operators work on are called operands.

Examples:

  1. 20 + 32: Addition (operator: +, operands: 20, 32)
  2. 5 ** 2: Exponentiation (operator: **, operands: 5, 2)
  3. (5 + 9) * (15 - 7): Combination of operators and parentheses.

Division in Python:

  • The division operator (/) produces a floating-point result in Python 3 (even for integer results).
  • Truncated division, ignoring the remainder, is done using the // operator (e.g., 5//2 is 2).

Modulus Operator:

  • The modulus operator (%), sometimes called the remainder operator, yields the remainder when the first operand is divided by the second.
  • Example: print(7 % 3) produces 1.

Usefulness:

  • Modulus operator is useful for checking divisibility and extracting digits.

Examples:**

print(18 / 4)      # Outputs: 4.5
print(18.0 // 4)   # Outputs: 4.0 (even though truncating, it produces a float)
print(18 % 4)      # Outputs: 2 (remainder after division)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are function calls in Python?

A

Function Definitions (Hidden for simplicity)

A function is a reusable block of code that performs a specific task. It takes input parameters, processes them, and returns a computed value.

Function Invocation/Calling:
- Invoking or calling a function involves using the function’s name followed by parentheses, e.g., function_name().

  • Input values, called arguments, can be passed within the parentheses. If a function doesn’t require arguments, the parentheses are still present, e.g., function_without_args().

Example:

def square(x):
    return x * x
def sub(a, b):
    return a - b

Function calls

result1 = square(3)
result2 = sub(6, 4)

Print results

print(result1)
print(result2)

Return Value vs. Output Window:

The return value is the result computed by the function and can be stored in variables or used in expressions.

The output window shows values when explicitly printed using print(). Not all function calls’ results are automatically displayed; printing is required.

Additional Note:

Functions in Python are like factories, taking inputs (arguments), performing operations, and returning outputs.

Functions can be part of complex expressions, allowing for flexible and powerful computations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you determine the data type of a variable in Python?

A

To determine the data type of a variable in Python, you can use the type function.

  • The type function is applied to the variable, and it returns the class (data type) the value belongs to.

Example:

Using the type function

print(type("Hello, World!"))   # Outputs: <class 'str'>
print(type(17))                 # Outputs: <class 'int'>
print(type(3.2))                # Outputs: <class 'float'>

String Enclosure:

Strings in Python can be enclosed in single quotes (‘), double quotes (“), or triple quotes (‘’’ or “””).

Triple quoted strings can span multiple lines.

Example:

print(type('This is a string.'))                         # Outputs: <class 'str'>
print(type("""This is also a string."""))           # Outputs: <class 'str'>

Note:
The surrounding quotes used to define strings in Python are not part of the value and do not affect how Python stores the value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are type conversion functions in Python, and how do they work?

A

Using type conversion functions

  • Type conversion functions in Python are functions that allow us to convert values from one type to another.
  • The three main type conversion functions are:
    • int: Converts a floating-point number or string to an integer. It discards the decimal portion, a process called truncation towards zero.
    • float: Converts an integer, float, or syntactically legal string to a float.
    • str: Converts its argument into a string.

**Examples:

print(3.14, int(3.14))              # int function on a floating-point number
print(float("123.45"))               # float function on a string
print(str(17))                       # str function on an integer

Type Conversion in Concatenation:

Type conversion is often used when concatenating strings with numeric values.

Numeric values need to be converted to strings before concatenation.

Example:

Concatenating strings with numeric values

value = 55
print("The value is " + str(value))     # Convert the integer to a string for concatenation

Note:

Type conversion ensures that different types can work together in operations like concatenation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a variable in Python, and how is it used?

A

A variable in Python is a name that refers to a value. It is a way to store and manage data in a program.

Variable Assignments:
- Variables are created and given values using assignment statements.

  message = "What's up, Doc?"
  n = 17
  pi = 3.14159

In this example, message, n, and pi are variables, and they are assigned values of a string, an integer, and a floating-point number, respectively.

Using Variables:

Variables are used to store and remember values. When a variable is used in an expression, it produces the value that is linked to the variable at the time of execution.

print(message)
print(n)
print(pi)

These statements print the values stored in the variables message, n, and pi.

Variables are “Variable”:

The term “variable” in programming signifies that variables can change over time. They can be assigned different values during the execution of a program.

day = "Thursday"
print(day)
day = "Friday"
print(day)
day = 21
print(day)

In this example, the variable day is assigned different values (“Thursday,” “Friday,” and 21) at different points in the program.

Note:

Variables in Python don’t have types; values do.

A variable can refer to an integer and later refer to a string, though this practice is generally discouraged for clarity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain the concepts of statements and expressions in Python.

A
  • A statement is an instruction that the Python interpreter can execute.
  • Examples include assignment statements (e.g., x = 5), while statements, for statements, if statements, and import statements. Statements perform actions and make things happen in the program.

Expressions in Python:

  • An expression is a combination of literals, variable names, operators, and function calls. Expressions need to be evaluated, and the result of evaluating an expression is a value or object. Expressions can appear on the right-hand side of assignment statements and produce values when printed.

Statement Example:

x = 5

Here, x = 5 is an assignment statement that creates a new variable x and assigns it the value 5.

print(1 + 1 + (2 * 3))
print(len("hello"))

In these examples, 1 + 1 + (2 * 3) and len(“hello”) are expressions. The first evaluates to a numeric value, and the second evaluates to the length of the string “hello.”

Roles in Programming:

Statements:

Perform actions and carry out operations.
Control the flow of the program through conditions and loops.
Manage imports and external modules.

Expressions:

Produce values that can be used in statements.
Play a crucial role in mathematical and logical computations.
Can include literals, variables, and function calls.

Parsing and Evaluation:

The Python interpreter parses lines of code by examining symbols like = and tries to determine the nature of each line.

For expressions, the interpreter evaluates sub-expressions, combining values using operators or calling functions.

Understanding the distinction between statements and expressions is fundamental to reading and writing Python code effectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are sub-expressions?

A

A sub-expression is a part of a larger expression.

An expression is a combination of values, variables, and operators that can be evaluated to produce a result. Sub-expressions are the smaller, constituent parts of an overall expression.

Here’s an example of an expression with sub-expressions:

result = (3 * 4) + (5 / 2)

In this expression, there are two sub-expressions: (3 * 4) and (5 / 2). Each of these sub-expressions is evaluated independently before the larger expression is computed. The result of each sub-expression is then used in the final computation:

Sub-expression (3 * 4) evaluates to 12.
Sub-expression (5 / 2) evaluates to 2.5.
The larger expression becomes 12 + 2.5, and the final result is 14.5.

So, in this example, (3 * 4) and (5 / 2) are sub-expressions that contribute to the overall computation of the expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the concept of operator precedence in Python.

A
  • Operator precedence refers to the order in which operators are evaluated in an expression. Python follows the same precedence rules as mathematics.
  • When more than one operator appears in an expression, the order of evaluation is determined by the precedence of operators.

Examples of Operator Precedence:
- High Precedence (Evaluated First):
- Parentheses: ()
- Exponentiation: **

  • Medium Precedence:
    • Multiplication: *
    • Division: /
    • Floor Division: //
  • Low Precedence (Evaluated Last):
    • Addition: +
    • Subtraction: -

Role of Parentheses:
- Parentheses have the highest precedence and can be used to force a specific order of evaluation.
- For example, (2 * (3 - 1)) ensures that the subtraction is done before multiplication.
- Parentheses are also useful for making expressions more readable, even if they don’t change the result.

Left-Associativity:
- Operators with the same precedence are evaluated from left to right (left-associative).
- For example, in 6 - 3 + 2, subtraction is evaluated first, followed by addition.

Exception for Exponentiation:
- The exponentiation operator ** is right-associative, meaning it evaluates from right to left.
- It is recommended to use parentheses to control the order when exponentiation is involved.

Example Expression:

result = 16 - 2 * 5 // 3 + 1

The expression is evaluated as (2 * 5) first, then (10 // 3), then (16 - 3), and finally (13 + 1).

Key Takeaway:
Understanding operator precedence is crucial for predicting the order of operations in complex expressions.

Parentheses provide a way to explicitly control the order of evaluation and avoid ambiguity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain the concept of reassignment in Python.

A
  • Reassignment is the process of assigning a new value to an existing variable.
  • A new assignment makes the variable refer to a new value, replacing its previous reference.

Example of Reassignment:

bruce = 5
print(bruce)
bruce = 7
print(bruce)

The variable bruce is initially assigned the value 5, then reassigned to the value 7. Each print statement displays the current value of bruce.
Visualization of Reassignment:

In a reference diagram, reassignment is depicted as a change in the value (object) a variable refers to. The variable can point to different objects during program execution.

Changing Equality in Python:

Unlike mathematics, where equality is always true, Python allows variables to refer to the same object initially but doesn’t enforce a permanent equality relationship.

a = 5
b = a                    # a and b are initially equal
print(a, b)
a = 3                       # a and b are no longer equal
print(a, b)

The reassignment of a does not affect the value of b, and they become unequal.

Mental Model of Python Evaluation:

When evaluating an assignment statement, the interpreter first evaluates the right-hand side expression and then associates a name (variable) with that value.

Key Takeaway:

Reassignment allows variables to dynamically change their values during program execution.

It is essential to understand that variables can be reassigned to different values, and equality in Python is not necessarily permanent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain the concept of updating variables in Python.

A

… (continue updating based on the old values)

  • Updating variables involves changing their values based on the current values.
  • Common forms of updating include incrementing (adding) or decrementing (subtracting) a value from the existing variable.

Increment and Decrement:
Incrementing: Increasing the variable value, often by 1.
- Represented as x = x + 1 or x += 1.

Decrementing: Decreasing the variable value, often by 1.
- Represented as x = x - 1 or x -= 1.

Syntax Simplification with += and -=:

Python provides shorthand syntax for increment and decrement operations.
- x += 3 is equivalent to x = x + 3 (Increment by 3).
- x -= 1 is equivalent to x = x - 1 (Decrement by 1).

Example of Increment and Decrement:

x = 6        # initialize x
print(x)
x += 3       # increment x by 3; same as x = x + 3
print(x)
x -= 1       # decrement x by 1
print(x)

Updating Variables with Dependence on Old Values:
Update where the new value depends on the old value.

s = 1
print(s)
s = s + 2
print(s)

Key Takeaways:

Updating variables is a common programming task.
Increment and decrement operations are essential for modifying variable values.
Shorthand syntax like += and -= simplifies the process of updating variables, making the code more concise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does “hard-coding” mean in the context of programming?

Why is it generally advised against, and what is the preferred approach when writing code or solving programming problems?

A

“Hard-coding” in programming refers to the practice of directly inserting specific values or computations into the code without considering variable changes or adaptability.

Advisory Against Hard-Coding:

  • It is generally advised against because hard-coded solutions are rigid and may only work for specific scenarios.
  • Hard-coding restricts adaptability, and the code may fail or provide incorrect results if input values change.

Preferred Approach:

  • The preferred approach is to write code that can handle varying inputs and scenarios.
  • Instead of hard-coding specific values, use variables and expressions that make the code applicable to different situations.
  • The goal is to create flexible and reusable code that can adapt to changes without manual intervention.

Example:

  • Hard-Coding Example: zx = 55 (specific value)
  • Preferred Approach: zx = y + x (adaptive to different x and y values)

Key Takeaways:

  • Hard-coding limits the versatility of code and is discouraged in programming.
  • Code should be designed to handle changing inputs and scenarios.
  • Use variables and expressions for adaptability, avoiding reliance on fixed values.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of the “input” function in Python, and how does it work?

A

The “input” function in Python is used to receive user input during the execution of a program.

  • It allows the programmer to prompt the user for information by displaying a specified prompt string.

Example:

n = input("Please enter your name: ")

In this example, the user is prompted to enter their name. The entered text is returned by the “input” function and assigned to the variable “n.”

Return Type:

The “input” function returns a string value, regardless of the type of information entered by the user.

It is essential for the programmer to convert this string to the desired type (e.g., int or float) if numeric values are expected.
Note:

User inputs are treated as strings, and manual conversion may be necessary for numerical calculations.

age_str = input("Please enter your age: ")
age = int(age_str)  # Convert string to integer

Key Takeaways:

“input” facilitates interaction by prompting users for input.

The returned value is always a string, requiring explicit conversion for numerical operations.
Example usage involves displaying a prompt, receiving user input, and processing as needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is debugging in the context of programming, and what are some key strategies mentioned to avoid or minimize the need for debugging?

A
  • Debugging refers to the process of identifying, locating, and correcting errors (bugs) in a computer program.
  • Errors may occur during programming, and debugging is essential for ensuring the program runs as intended.

Key Strategies to Avoid Debugging:
1. Understand the Problem:
- Gain a solid understanding of the problem you are solving and the expected program behavior.
- Focus on specific aspects of the problem and what the program should achieve for given inputs.

  1. Start Small:
    • Begin with a small portion of the program, ensuring it runs correctly before expanding.
    • Avoid attempting to code an entire program at once, as it becomes challenging to identify errors.
  2. Keep Improving:
    • Build on small successes by continuously improving and expanding the program incrementally.
    • Add small pieces one at a time, testing each addition to identify and fix errors promptly.
  3. Test Each New Code:
    • Test each new piece of code added to the program to catch errors early.
    • The likelihood of errors in new code is higher, making it easier to locate and address issues.
  4. Type Consistency:
    • Ensure consistent data types throughout the program to prevent unexpected errors.
    • Explicitly convert variables to the required types, especially when dealing with user inputs.
  5. Test on a Range of Inputs:
    • Test the program on various inputs, including boundary conditions and extreme cases.
    • Identify and address issues related to specific input values or scenarios.
  6. Use Modular Development:
    • Adopt modular development practices, breaking down the program into manageable, independent modules.
    • Debugging becomes more straightforward when dealing with smaller, well-defined components.
  7. Embrace Agile Development:
    • Follow Agile software development principles, emphasizing iterative development and frequent testing.
    • Address issues early in the development process, avoiding accumulation of complex bugs.

Note:
- Debugging is a critical skill in programming, and adopting proactive strategies can significantly reduce the need for extensive debugging.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Dubbing is:

A

Debugging is the process of tracking down and correcting programming errors or bugs. It is an essential skill in programming to ensure the proper functioning of code.

Programming errors are inevitable and are referred to as bugs.

Bugs can range from syntax errors to logical mistakes in the code.
Importance of Debugging:

Debugging is crucial in the programming process, as errors can lead to incorrect program behavior.

Acquiring debugging skills is essential for success in programming.

Debugging Interludes:

The module introduces “debugging interludes,” providing tips and tricks specific to different aspects of Python programming.

Avoidance of Debugging:

Debugging can often be avoided by working carefully and understanding the problem thoroughly.

Starting small and continuously improving code helps in early error identification.
Testing and Iteration:

Testing each small piece of code is crucial for identifying errors.

Iterative development, adding small pieces at a time, makes it easier to locate and fix problems.

The example involves a program to calculate the time on a clock after a specified waiting period.

Demonstrates the process of starting small, testing, and improving code iteratively.

Handling Input:

In the example, converting input values to the appropriate data type (e.g., converting strings to integers) is crucial for accurate computations.

Modulo Operator:

The modulo operator is introduced to handle cases where the resulting time exceeds 23 hours on the clock.

Check Your Understanding:

Debugging is the process of:

A. tracking down programming errors and correcting them.
B. removing all the bugs from your house.
C. finding all the bugs in the program.
D. fixing the bugs in the program.

Note:

Debugging is an essential skill in programming, involving the identification and correction of errors to ensure the proper execution of code. The process includes starting small, continuous improvement, and thorough testing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a syntax error in Python?

A

A syntax error in Python occurs when a program is not syntactically correct, meaning it violates the rules and structure defined by the Python language.

Python requires adherence to specific syntax rules, such as proper indentation, correct placement of colons, and appropriate use of parentheses and quotes. Syntax errors prevent the interpreter from executing the program and result in an error message.

Examples of syntax errors:

print(Hello, world!)
print "Hello, world!"
print(5 + )

Identifying syntax errors:

  • The error message for syntax errors, such as SyntaxError, indicates a problem with the program’s structure.
  • The error is associated with a specific line number, helping pinpoint the location of the syntax error.

Syntax errors prevent the execution of any part of the program.

Note on indentation in Python:

Python enforces indentation rules, requiring statements to start at the beginning of the line. However, flow control statements like for or if allow indentation variations.

Check your understanding:

Which of the following is a syntax error?

A. Attempting to divide by 0.
B. Forgetting a colon at the end of a statement where one is required.
C. Forgetting to divide by 100 when printing a percentage amount.

Answer: B. Forgetting a colon at the end of a statement where one is required.

Who or what typically finds syntax errors?

A. The programmer.
B. The compiler / interpreter.
C. The computer.
D. The teacher / instructor.

Answer: B. The compiler / interpreter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a runtime error in Python?

A

A runtime error in Python occurs when a program, having passed the interpreter’s syntax checks, starts execution but encounters an error during the execution of one of its statements.

This error causes the interpreter to stop executing the program and display an error message.

Runtime errors are also known as exceptions and usually indicate that something exceptional (and bad) has happened.

Examples of common runtime errors:

  • Misspelled or incorrectly capitalized variable and function names.
  • Attempts to perform operations (such as math operations) on data of the wrong type (e.g., attempting to subtract two variables that hold string values).
  • Dividing by zero.
  • Attempts to use a type conversion function, such as int, on a value that can’t be converted to an int.

How to identify a runtime error:

If the error message mentions SyntaxError, it indicates a syntax-related problem.

If the program runs partially and then crashes, it signals a runtime error. Programs with syntax errors don’t execute even one line.

Check your understanding:

Which of the following is a run-time error?

A. Attempting to divide by 0.
B. Forgetting a colon at the end of a statement where one is required.
C. Forgetting to divide by 100 when printing a percentage amount.

✔️ Python cannot reliably tell if you are trying to divide by 0 until it is executing your program (e.g., you might be asking the user for a value and then dividing by that value—you cannot know what value the user will enter before you run the program).

Who or what typically finds runtime errors?

A. The programmer.
B. The interpreter.
C. The computer.
D. The teacher / instructor.

✔️ If an instruction is illegal to perform at that point in the execution, the interpreter will stop with a message describing the exception.

19
Q

What is a semantic error in programming?

A

Incorrect program

A semantic error, also known as a logic error, occurs when a program runs without syntax errors but does not produce the intended or correct output.

In other words, the program performs the actions specified by the code, but those actions do not align with the programmer’s intentions.

Semantic errors can be challenging to identify because they do not trigger error messages, and the program’s output seems reasonable.

Example of a semantic error:

num1 = input('Enter a number:')
num2 = input('Enter another number:')
sum = num1 + num2
print('The sum of', num1, 'and', num2, 'is', sum)
num1 = int(input('Enter a number:'))
num2= int(input('Enter another number:'))
sum = num1 + num2
print('The sum of', num1, 'and', num2, 'is', sum)

In this example, the program concatenates the input values instead of performing addition because the inputs are treated as strings. This is a semantic error.

Detecting and correcting semantic errors:

Test cases are essential for detecting semantic errors. A test case consists of input values and the expected output for those inputs.

By comparing the actual program output with the expected output for various test cases, programmers can identify semantic errors.

Correcting semantic errors involves understanding the program’s intended logic and modifying the code accordingly.

Significance of test cases:

Test cases help ensure that programs produce the correct results for various scenarios.

Quality assurance departments often use test cases to verify program correctness without requiring programming expertise.

Check your understanding:

Which of the following is a semantic error?

A. Attempting to divide by 0.
B. Forgetting a semi-colon at the end of a statement where one is required.
C. Forgetting to divide by 100 when printing a percentage amount.
Answer: C. Forgetting to divide by 100 when printing a percentage amount.
Who or what typically finds semantic errors?

A. The programmer.
B. The compiler / interpreter.
C. The computer.
D. The teacher / instructor.
Answer: A. The programmer.

20
Q

What is a module in Python?

A

A module in Python is a file that includes Python definitions and statements, designed to be utilized in other Python programs.

Python comes with a variety of modules as part of the standard library, offering additional functionality. Importing functions from a module establishes a separate namespace for those functions, ensuring distinct names within that namespace.

The concept of namespaces can be likened to the uniqueness of street names within a city or the organization of files in different folders within a file system.

This organizational structure prevents naming conflicts.

The Python Documentation site for Python version 3.6 serves as a comprehensive reference for Python, listing standard modules, providing a Standard Library Reference, a Tutorial, and various resources for users.

21
Q

What is the process of importing modules in Python, and what does an import statement do?

A

To use Python modules, they must be imported into a Python program using an import statement, consisting of the keyword “import” followed by the module name.

This statement, which is case-sensitive, essentially signifies, “there’s some code in another file; please make its functions and variables available in this file.”

The import statement triggers the execution of all code in the specified file, and any variables or functions defined during this execution become accessible in the current file.

Conventionally, import statements are placed at the top of the file for clarity. These external files could be ones you’ve written or code obtained from others.

For instance, if a file “myprog.py” in directory “~/Desktop/mycode/” contains the line “import morecode,” the Python interpreter will look for a file named “morecode.py,” execute its code, and make its object bindings available for reference in “myprog.py.”

Importantly, it’s “import morecode,” not “import morecode.py,” but the other file must be named “morecode.py.”

Additionally, caution is advised not to accidentally overwrite standard library modules, as the interpreter will prioritize locally created files over standard library modules if naming conflicts arise.

22
Q

How do you create a new instance of a class in Python?

A

Class library

To create a new instance of a class in Python, you use the class constructor as follows:

import turtle

Creating a new instance of the Turtle class
alex = turtle.Turtle()

Explanation: In this example, turtle is the module, and Turtle() is the class constructor.

Calling turtle.Turtle() creates a new instance of the Turtle class, and the instance is named alex.

This instance (alex) can then be used to perform various actions.

23
Q

What is the significance of creating instances in object-oriented programming (OOP)?

A

In OOP, creating instances is essential for modeling and representing real-world entities.

Instances are objects that follow the structure and behavior defined by classes, providing a way to organize and structure code.

This concept allows us to design and interact with objects, making Python an object-oriented programming language.

24
Q

What are attributes in Python classes, and how are they assigned and accessed?

A

Attributes are variables that belong to instances of a class and are sometimes called instance variables.

Assigned using assignment statements with = within the class or outside it.

Assigning values to attributes
~~~
alex.price = 500
tess.price = 600
~~~

Accessing and using attributes
~~~
total_price = alex.price + tess.price
print(total_price) # Output: 1100
~~~

25
Q

What are methods in Python classes, how are they invoked, and what is the role of the instance in method calls?

A

Methods are special functions associated with classes in Python.

Invoked using the syntax instance.method().

The instance itself is passed as the first parameter to the method (usually named self). Methods can manipulate the state of the instance and may return values.

Using a method in a Turtle class instance
alex.forward(50)

Calling a method with parameters
~~~
tess.forward(x + y)
~~~

Using methods to set attributes
~~~
alex.pensize(3)
alex.color(“red”)
~~~

26
Q

Creating a user-defined class

Explain the key concepts of user-defined classes in Python, including instances, attributes, and methods. Provide a brief example demonstrating the use of these concepts.

A

Creating a user-defined class

User-defined classes allow the creation of new types of objects.

Instances of a class are created using a syntax similar to function calls.

Each instance can have attributes (or instance variables) that are assigned values using assignment statements.

Methods, which are special functions associated with classes, can be invoked on instances. These methods may modify attributes or perform other actions related to the class.

In the example provided, the Turtle class has instances alex and tess, each with a price attribute.

The forward method is invoked to make the turtles move, and attributes are accessed and manipulated in expressions.

class Turtle:
    def \_\_init\_\_(self, name):
        self.name = name
        self.price = 0

    def forward(self, distance):
        print(f"{self.name} is moving forward by {distance} units.")

** Creating instances of the Turtle class**
~~~
alex = Turtle(“Alex”)
tess = Turtle(“Tess”)
~~~

Assigning values to attributes
~~~
alex.price = 500
tess.price = 600
~~~

Accessing and using attributes in an expression
~~~
total_price = alex.price + tess.price
print(f”Total price: {total_price}”)
~~~

Invoking methods of the Turtle class
~~~
alex.forward(50)
tess.forward(30)
~~~

27
Q

Describe the key aspects of a for loop in Python, and how does the range function contribute to its functionality?

A

A for loop is a control structure that executes a set of lines repeatedly in a non-linear fashion.

Instead of evaluating code line by line, a for loop runs a specified number of times.

The range function is often used with for loops to determine the number of iterations.

In the example provided, lines inside the loop (line 4 and 5) execute three times, controlled by the range(3) parameter.

for _ in range(3):
    print("This line will execute three times")
    print("This line will also execute three times")
print("But this line will only print once")

Indentation is crucial;

indented lines are part of the loop, while non-indented lines are outside the loop.

Key Points:

Indentation controls the flow of the program within and outside the loop.

The number of loop iterations is determined by the parameter passed to the range function.
For loops provide an efficient way to execute repetitive tasks in Python.

Another example:
numbers = list(range(53))

28
Q

Differentiate between strings, lists, and tuples in Python, highlighting their key characteristics and use cases.

A

Strings

Strings:

Sequential collections of characters with a specific order.
The empty string is represented by '' or "". Example: "hello".

Lists:

Sequential collections of data values, where each value is identified by an index.
Elements can be of any type and enclosed in square brackets ([]). Example: [10, 20, 30, 40].

**Tuples: **

Similar to lists but immutable, meaning their contents cannot be changed after creation.

Represented by a comma-separated sequence of values enclosed in parentheses (). Example: ("Julia", "Roberts", 1967, "Duplicity").

Key Points:

  • Elements in strings and lists maintain a specific order from left to right.
  • Lists allow different types of elements but are generally advised to be of the same type for simplicity.
  • Tuples are immutable, and their representation uses parentheses instead of square brackets.
  • To create a tuple with a single element, include a final comma after the element.

Examples:

word = “hello”

numbers = [10, 20, 30, 40]
names = [“spam”, “bungee”, “swallow”]

Tuples
celebrity_info = (“Julia”, “Roberts”, 1967, “Duplicity”)`

Question for Further Understanding:

Explain why lists are considered more versatile than strings in Python, providing an example of a situation where a list’s flexibility is advantageous.

Answer:

Lists are considered more versatile than strings in Python because they can hold elements of any data type and allow for a mix of different types within the same list. This flexibility is advantageous in situations where a collection of diverse data needs to be stored or manipulated.

For example, consider a scenario where you want to store information about a group of students. A list could efficiently represent this data, including their names (strings), ages (integers), and average grades (floats) in a single structure. This flexibility allows for a concise and organized representation of varied information related to each student within a single list.

29
Q

How do you create a list of numbers from 1 to 10 in Python?

A

You can use the range() function to generate a sequence of numbers from 1 to 10 and then convert it to a list. Here is an example:

my_list = list(range(1, 11))

or

my_list = []
for i in range(1, 11):
my_list.append(i)

This creates a list named my_list with 10 elements: integers from 1 to 10.

I hope this helps you study! Let me know if you have any more questions.

30
Q

Explain the purpose of the indexing operator in Python and how it is used with strings, lists, and tuples.

Provide an example for each. Why is it important to know that Python uses a zero-based index?

Consider the string school = "Luther College".

Using the indexing operator, if we write m = school[2]

what does m represent, and what will be printed when print(m) is executed?

A

The indexing operator in Python is used to select a single element from a sequence, such as a character from a string or an item from a list or tuple.

In the example school[2], the indexing selects the character at index 2 (zero-based) in the string, and the variable m refers to this character.

Therefore, print(m) will output the letter “t” since it is the character at index 2 in “Luther College”.

It’s important to know that Python uses a zero-based index, meaning the first element is at index 0.

This convention is crucial for accurate indexing and avoids off-by-one errors. The zero-based index applies to strings, lists, and tuples in Python.

31
Q

Explain the dual role of square brackets [] in Python, particularly focusing on their use in creating lists and indexing into lists or strings.

Provide examples to illustrate the distinction between creating and indexing, and why specifying the target list is crucial during indexing.

lst = [0]
n_lst = lst[0]
print(lst)
print(n_lst)

Explain the role of square brackets in this code and how it demonstrates the difference between creating and indexing a list.

A

In Python, square brackets [] serve a dual purpose.

When used to enclose elements directly, as in new_lst = []they indicate list creation.

This results in an empty list.

Conversely, when used to access elements from an existing list or string, the brackets signify indexing.

For example, part_of_new_lst = new_lst[0] retrieves the element at index 0 of new_lst.

It’s crucial to specify the target list during indexing because Python needs to know which list or string to reference.

In the provided code snippet, lst = [0] demonstrates list creation, and n_lst = lst[0] illustrates indexing by extracting the value associated with the first element of lst.

lst = [0]
n_lst = lst[0]
print(lst)
print(n_lst)

The subsequent print statements emphasize the distinction between the created list ([0]) and the indexed value (0).

32
Q

Explain the role of the len function in Python and demonstrate its application to both strings and lists.

Provide a specific example to illustrate the correct usage of len with strings and the precautions necessary when accessing elements, such as the last character, in a sequence.

Consider the code snippet:

fruit = "Banana"
sz = len(fruit)
lastch = fruit[sz-1]
print(lastch)

Discuss the purpose of the len function in determining the length of the string “Banana” and extracting its last character. Explain why subtracting 1 from the length is necessary.

A

The len function in Python is employed to retrieve the length of a sequence, whether it’s a string or a list.

In the given code snippet, sz = len(fruit) calculates the length of the string “Banana.”

Since indexing starts from 0, accessing the last character is done using fruit[sz-1] to prevent an IndexError.

An alternative and more concise option is to utilize negative indexing, making fruit[-1] a suitable choice for obtaining the last character in a sequence.

The len function is versatile and extends its utility to lists, providing the count of items in the list. However, it’s essential to clarify that it only considers the top-most length and does not account for nested sequences within the list.

nested_list = ["apple", [1, 2, 3], "orange", ["banana", "grape", "kiwi"]]
top_level_length = len(nested_list)
#Accessing the length of the first element in the list (a string)
string_length = len(nested_list[0])
#Accessing the length of the second element in the list (a nested list)
nested_length = len(nested_list[1])
print("Top-level length:", top_level_length)
print("Length of the first element (string):", string_length)
print("Length of the second element (nested list):", nested_length)

In the provided example, “banana” is part of a nested list. To get the length of “banana,” you would access it through indexing and then apply the len function. Here’s how you can do it:

Accessing the nested list
nested_inner_list = nested_list[3]

Accessing the length of “banana”
banana_length = len(nested_inner_list[0])
print("Length of 'banana':", banana_length)

33
Q

Explain the concept of string slices in Python, and provide an example.

Example:
s = “python rocks”
print(s[3:8])

A

In Python, string slices are obtained using the slice operator [n:m].

This operation returns a substring starting from the character at index n and goes up to but does not include the character at index m.

To clarify, the character at index n is included in the slice, but the character at index m is not.

Omitting the starting index starts the slice from the beginning of the string, and omitting the ending index goes to the end.

Example: s[3:8] retrieves characters from index 3 to 7 in the string “python rocks” or “hon r”, excluding ‘o’.

Example:
s = “python rocks”
print(s[3:8])

34
Q

Illustrate the concept of list slices in Python, highlighting how they are employed and provide an example.

Example:
a_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
print(a_list[1:3])

A

List slices in Python, similar to string slices, use the syntax [n:m].

They return a sublist starting from the element at index n and going up to but not including the element at index m.

Omitting the starting index starts the slice from the beginning of the list, and omitting the ending index goes to the end.

In the example, a_list[1:3] retrieves elements from index 1 to 2 in the list [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’].

Example:
a_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
print(a_list[1:3])

35
Q

Explain the use of the + operator for lists in Python. Provide an example to illustrate the concept.

Example:
fruit = [“apple”, “orange”, “banana”, “cherry”]
result = fruit + [6, 7, 8, 9]
print(result)

A

In Python, the + operator concatenates lists.

It creates a new list containing all the elements of the operands.

For instance, given fruit = [“apple”, “orange”, “banana”, “cherry”] and [6, 7, 8, 9], using result = fruit + [6, 7, 8, 9] produces a new list result with the combined elements of both lists.

Example:
fruit = [“apple”, “orange”, “banana”, “cherry”]
result = fruit + [6, 7, 8, 9]
print(result)

[‘apple’, ‘orange’, ‘banana’, ‘cherry’, 6, 7, 8, 9]

36
Q

How does the * operator function with lists in Python?

Provide an example for clarification.

Example:
alist = [1, 3, 5]
repeated_list = alist * 3
print(repeated_list)

A

In Python, the * operator repeats the items in a list a specified number of times.

For instance, with alist = [1, 3, 5], repeated_list = alist * 3 results in a new list where the elements of alist are repeated three times consecutively.

alist = [1, 3, 5]
repeated_list = alist * 3
print(repeated_list)

[1, 3, 5, 1, 3, 5, 1, 3, 5]

37
Q

Explain the purpose of the index method in Python for both strings and lists.

Provide an example for each, emphasizing its functionality.

Example:
music = “Pull out your music and dancing can begin”
index_result_str = music.index(“m”)
print(index_result_str)

List Index Example
bio = [“Metatarsal”, “Metatarsal”, “Fibula”, [], “Tibia”, “Tibia”, 43, “Femur”, “Occipital”, “Metatarsal”]
index_result_list = bio.index(“Metatarsal”)
print(index_result_list)

A

The index method in Python is used to find the leftmost occurrence of a specified element and return its index.

For strings, as in music.index(“m”), it returns the index of the leftmost occurrence of the specified character, or 14.

For lists, like bio.index(“Metatarsal”), it returns the index of the leftmost occurrence of the specified element, or 0.

Both examples illustrate how the index method functions.

Example:
music = “Pull out your music and dancing can begin”
index_result_str = music.index(“m”)
print(index_result_str)

List Index Example
bio = [“Metatarsal”, “Metatarsal”, “Fibula”, [], “Tibia”, “Tibia”, 43, “Femur”, “Occipital”, “Metatarsal”]
index_result_list = bio.index(“Metatarsal”)
print(index_result_list)

38
Q

Explain the purpose and functionality of the split and join methods in Python for strings.

Provide examples for both methods, highlighting any optional arguments.

A

The split method in Python is used to break a string into a list of words, with whitespace characters as the default word boundaries.

Example:

song = "The rain in Spain..."
wds = song.split()
print(wds)

['The', 'rain', 'in', 'Spain...']

Split Method with Delimiter Example**

song = "The rain in Spain..."
wds_delimiter = song.split('ai')
print(wds_delimiter)

['The r', 'n in Sp', 'n...']

The join method, on the other hand, combines a list of strings into a single string using a specified separator (glue).

Join Method Example**

wds_to_join = ["red", "blue", "green"]
glue = ';'
result_str = glue.join(wds_to_join)
print(result_str)

['The r', 'n in Sp', 'n...']

Join Method with Different Glue Examples**

print("***".join(wds_to_join))
print("".join(wds_to_join))

red***blue***green
redbluegreen
39
Q

The for Loop in Python

A

The for loop in Python is a control flow statement that allows code to be repeatedly executed. It iterates over a sequence (such as a list or string) and performs the specified block of code for each element in the sequence.

Syntax:
~~~
for <loop_var_name> in <sequence>:
# Indented block of code to be executed in each iteration
~~~</sequence></loop_var_name>

Example:
~~~
friends = [“Joe”, “Amy”, “Brad”, “Angelina”, “Zuki”, “Thandi”, “Paris”]
for name in friends:
print(“Hi”, name, “Please come to my party on Saturday!”)
~~~

-Name is the loop variable or iterator variable.
-The loop iterates over the sequence friends (list of names).
-The indented block of code (loop body) is executed for each name in the list.
-After each iteration, the loop variable (name) is updated to refer to the next item in the list.
-The loop continues until all items in the sequence are processed.

Key Points:

The for loop is used for iteration.
The loop variable takes on the values of the elements in the sequence.
The loop body is indented and executed for each iteration.

40
Q

Explain how a for loop iterates over characters in a string in Python. Provide an example.

A

When a for loop is used with a string, it automatically iterates over each character in the string. This process is known as “iteration by item.”

The loop variable is assigned the value of each character in the string successively, and the loop body is executed for each iteration.

For example, in the code for achar in “Go Spot Go”: print(achar), the loop variable achar takes on the values ‘G’, ‘o’, ‘ ‘, ‘S’, ‘p’, ‘o’, ‘t’, ‘ ‘, ‘G’, ‘o’ as the loop iterates over each character in the string “Go Spot Go.” The output would be each character printed on a new line.

Example:
~~~
for achar in “Go Spot Go”:
print(achar)
~~~

Definition: When using a for loop with a string in Python, the loop iterates over each character in the string automatically. This type of sequence iteration is referred to as “iteration by item.”

41
Q

Explain how a for loop iterates over items in a list in Python. Provide an example.

A

When a for loop is used with a list, it automatically iterates over each item in the list.

This process is known as “iteration by item.” The loop variable is assigned the value of each item in the list successively, and the loop body is executed for each iteration.

For example, in the code for afruit in fruits: print(afruit), the loop variable afruit takes on the values ‘apple’, ‘orange’, ‘banana’, ‘cherry’ as the loop iterates over each item in the list “fruits.” The output would be each item (fruit) printed on a new line.

fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits:     # by item
    print(afruit)

Explanation:
The loop variable afruit is automatically reassigned to each item in the list “fruits.”
The for loop processes each item in the list one at a time, printing the item in this example.

The output would be each item (fruit) printed on a new line.
apple
orange
banana
cherry

In Python, the for loop can be used to perform list traversal using “iteration by item.” A list, being a sequence of items, allows the for loop to iterate over each item in the list automatically.

42
Q

Accumulator pattern

A

The accumulator pattern is a programming technique where you iterate through the elements of a list, accumulating a single value (e.g., sum) during the process.

The process includes initializing the accumulator variable, iterating through the list, updating the accumulator by performing an operation (e.g., addition) on each element, and finally, using the accumulated value after processing all elements.

In the example provided, the accumulator accum is initialized to 0, and for each element w in the list nums, the accumulator is updated by adding the current element.

The final accumulated value is then printed, representing the sum of all elements in the list.

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
accum = 0                                    # Initialize accumulator
for w in nums:
    accum = accum + w               # Update accumulator by adding each element
print(accum)                               # Print the accumulated value (sum)
43
Q
A