Python Flashcards
Fundamentals
What is an algorithm?
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
What are values and data types in Python?
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.
What are operators and operands in Python?
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:
-
20 + 32
: Addition (operator: +, operands: 20, 32) -
5 ** 2
: Exponentiation (operator: **, operands: 5, 2) -
(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)
What are function calls in Python?
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 can you determine the data type of a variable in Python?
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.
What are type conversion functions in Python, and how do they work?
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.
What is a variable in Python, and how is it used?
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.
Explain the concepts of statements and expressions in Python.
- 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.
What are sub-expressions?
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.
Explain the concept of operator precedence in Python.
- 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:
//
- Multiplication:
-
Low Precedence (Evaluated Last):
- Addition:
+
- Subtraction:
-
- Addition:
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.
Explain the concept of reassignment in Python.
- 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.
Explain the concept of updating variables in Python.
… (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.
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?
“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.
What is the purpose of the “input” function in Python, and how does it work?
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.
What is debugging in the context of programming, and what are some key strategies mentioned to avoid or minimize the need for debugging?
- 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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
Dubbing is:
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.
What is a syntax error in Python?
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.