Podcast
Questions and Answers
How are blocks of code typically denoted in Python?
How are blocks of code typically denoted in Python?
- Keywords such as `BEGIN` and `END`
- Line indentation (correct)
- Curly braces `{}`
- Parentheses `()`
Which of the following is true regarding Python keywords?
Which of the following is true regarding Python keywords?
- They are case-insensitive.
- They can be reassigned like built-in functions.
- They must be imported before use.
- Except for `False`, `True`, and `None`, all keywords are lowercase. (correct)
What is the primary purpose of the backslash \
character at the end of a line in Python?
What is the primary purpose of the backslash \
character at the end of a line in Python?
- To define a multi-line string.
- To escape special characters within a string.
- To indicate that the statement continues on the next line. (correct)
- To signify the start of a comment.
Which of the following can be used to create a multi-line comment in Python?
Which of the following can be used to create a multi-line comment in Python?
What is the correct method to access all available Python keywords within the Python console?
What is the correct method to access all available Python keywords within the Python console?
Given that Python's built-in functions can be reassigned, what might be an unexpected consequence of reassigning print = 42
?
Given that Python's built-in functions can be reassigned, what might be an unexpected consequence of reassigning print = 42
?
Assuming no imports, which of these operations would definitively raise a NameError
in standard Python?
Assuming no imports, which of these operations would definitively raise a NameError
in standard Python?
Which arithmetic operator returns the remainder of a division operation?
Which arithmetic operator returns the remainder of a division operation?
What is the primary benefit of using composition in object-oriented design?
What is the primary benefit of using composition in object-oriented design?
Which relational operator checks if two operands are not equal?
Which relational operator checks if two operands are not equal?
In Python, what is the result of the expression 17 // 5
?
In Python, what is the result of the expression 17 // 5
?
If x = 5
and y = 2
, what does the expression x ** y
evaluate to?
If x = 5
and y = 2
, what does the expression x ** y
evaluate to?
Which of the following best describes the relationship established through composition?
Which of the following best describes the relationship established through composition?
Given a = 10
and b = 5
, which expression will return True
?
Given a = 10
and b = 5
, which expression will return True
?
Consider a class Engine
and a class Car
. If Car
has an attribute engine
which is an instance of the Engine
class, what design principle is being demonstrated?
Consider a class Engine
and a class Car
. If Car
has an attribute engine
which is an instance of the Engine
class, what design principle is being demonstrated?
Which of the following best describes the primary function of the __next__()
method in an iterator?
Which of the following best describes the primary function of the __next__()
method in an iterator?
Assuming x = 15
and y = 4
, what would be the result of the expression x % y + x // y * y
?
Assuming x = 15
and y = 4
, what would be the result of the expression x % y + x // y * y
?
Which of the following is an example of an iterable in Python?
Which of the following is an example of an iterable in Python?
Which statement accurately distinguishes between iterables and iterators?
Which statement accurately distinguishes between iterables and iterators?
Consider the following scenario:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
next(my_iterator)
next(my_iterator)
What will happen if you call next(my_iterator)
again?
Consider the following scenario:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
next(my_iterator)
next(my_iterator)
What will happen if you call next(my_iterator)
again?
In the context of iterators and iterables, what is the significance of an iterator maintaining its state?
In the context of iterators and iterables, what is the significance of an iterator maintaining its state?
In the context of object-oriented programming, what principle is demonstrated when a Car
class contains instances of Engine
, Wheel
, and Body
classes?
In the context of object-oriented programming, what principle is demonstrated when a Car
class contains instances of Engine
, Wheel
, and Body
classes?
When should inheritance be favored over composition in object-oriented design?
When should inheritance be favored over composition in object-oriented design?
Which of the following scenarios is best addressed using composition rather than inheritance?
Which of the following scenarios is best addressed using composition rather than inheritance?
Why does composition provide more flexibility than inheritance in defining the abilities of GameCharacter
objects?
Why does composition provide more flexibility than inheritance in defining the abilities of GameCharacter
objects?
What is the primary advantage of using composition in a PaymentSystem
that supports multiple payment methods?
What is the primary advantage of using composition in a PaymentSystem
that supports multiple payment methods?
Regarding operator overloading in Python, which statement is most accurate?
Regarding operator overloading in Python, which statement is most accurate?
What are 'dunder' methods in Python, and how are they related to operator overloading?
What are 'dunder' methods in Python, and how are they related to operator overloading?
Given two instances, instance1
and instance2
, of a user-defined class, what must be implemented in the class definition to enable the operation instance1 + instance2
?
Given two instances, instance1
and instance2
, of a user-defined class, what must be implemented in the class definition to enable the operation instance1 + instance2
?
Consider the expression 2 + 'b'
. Why does this operation result in an error in Python, and how could operator overloading potentially address this?
Consider the expression 2 + 'b'
. Why does this operation result in an error in Python, and how could operator overloading potentially address this?
In the context of Python, if you want instances of your class to support operations with the +
operator, such that instance1 + instance2
performs a meaningful custom operation, which of the following is the most comprehensive consideration?
In the context of Python, if you want instances of your class to support operations with the +
operator, such that instance1 + instance2
performs a meaningful custom operation, which of the following is the most comprehensive consideration?
What is the primary purpose of the __str__()
method in Python classes?
What is the primary purpose of the __str__()
method in Python classes?
If a class does not have a __str__()
method defined, what does the print()
function do when called on an instance of that class?
If a class does not have a __str__()
method defined, what does the print()
function do when called on an instance of that class?
What should the __str__()
method always return?
What should the __str__()
method always return?
Consider the following code:
class Example:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value * 2)
obj = Example(5)
print(obj)
What will be the output of print(obj)
?
Consider the following code:
class Example:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value * 2)
obj = Example(5)
print(obj)
What will be the output of print(obj)
?
What is a potential pitfall of overusing operator overloading in Python?
What is a potential pitfall of overusing operator overloading in Python?
Which of the following is a good practice to follow when implementing operator overloading?
Which of the following is a good practice to follow when implementing operator overloading?
In the context of printing class instances, what is the crucial step where __str__
(and potentially __repr__
) come into play when using the print()
function?
In the context of printing class instances, what is the crucial step where __str__
(and potentially __repr__
) come into play when using the print()
function?
Consider the following scenario:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # This will cause an error
Why does the last line of code result in a TypeError
?
Consider the following scenario:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # This will cause an error
Why does the last line of code result in a TypeError
?
Which of the following is NOT typically a real-world application of operator overloading?
Which of the following is NOT typically a real-world application of operator overloading?
Given a class ComplexNumber
representing complex numbers, which of the following implementations of the __mul__
method would correctly overload the multiplication operator such that (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
? Assume the class has attributes real
and imag
representing the real and imaginary parts, respectively. (Insanely Difficult)
Given a class ComplexNumber
representing complex numbers, which of the following implementations of the __mul__
method would correctly overload the multiplication operator such that (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
? Assume the class has attributes real
and imag
representing the real and imaginary parts, respectively. (Insanely Difficult)
Flashcards
PEP 8
PEP 8
A guide for Python code style, emphasizing readability.
Python Keywords
Python Keywords
Special words that Python reserves for specific purposes; they cannot be used as identifiers.
Python Indentation
Python Indentation
Indentation is crucial in Python; it defines code blocks. Conventionally uses 4 spaces.
Python String Literals
Python String Literals
Signup and view all the flashcards
Python Comments
Python Comments
Signup and view all the flashcards
Math Module
Math Module
Signup and view all the flashcards
Random Module
Random Module
Signup and view all the flashcards
Addition (+)
Addition (+)
Signup and view all the flashcards
Subtraction (-)
Subtraction (-)
Signup and view all the flashcards
Multiplication (*)
Multiplication (*)
Signup and view all the flashcards
Division (float) (/)
Division (float) (/)
Signup and view all the flashcards
Division (floor) (//)
Division (floor) (//)
Signup and view all the flashcards
Modulus (%)
Modulus (%)
Signup and view all the flashcards
Exponent (**)
Exponent (**)
Signup and view all the flashcards
Equal To (==)
Equal To (==)
Signup and view all the flashcards
Composition
Composition
Signup and view all the flashcards
Operator Overloading
Operator Overloading
Signup and view all the flashcards
Iterable
Iterable
Signup and view all the flashcards
Iterator
Iterator
Signup and view all the flashcards
next()
next()
Signup and view all the flashcards
Iterable
Iterable
Signup and view all the flashcards
How does print()
work?
How does print()
work?
Signup and view all the flashcards
__str__()
Method
__str__()
Method
Signup and view all the flashcards
Overloading __str__
Overloading __str__
Signup and view all the flashcards
Operator Overloading Pitfalls
Operator Overloading Pitfalls
Signup and view all the flashcards
Frameworks: Custom Operators
Frameworks: Custom Operators
Signup and view all the flashcards
Numeric Libraries: Custom Operators
Numeric Libraries: Custom Operators
Signup and view all the flashcards
Consistency in Overloading
Consistency in Overloading
Signup and view all the flashcards
Avoid Overusing Overloading
Avoid Overusing Overloading
Signup and view all the flashcards
Inheritance
Inheritance
Signup and view all the flashcards
Game Character Abilities
Game Character Abilities
Signup and view all the flashcards
Payment System Composition
Payment System Composition
Signup and view all the flashcards
Dunder (Magic) Methods
Dunder (Magic) Methods
Signup and view all the flashcards
Why use Operator Overloading?
Why use Operator Overloading?
Signup and view all the flashcards
int.add(x, y)
int.add(x, y)
Signup and view all the flashcards
TypeError
TypeError
Signup and view all the flashcards
Operator Overloading Benefits
Operator Overloading Benefits
Signup and view all the flashcards
Study Notes
General Class Itinerary
- An overview of class includes: Announcements for updates, a Q&A for students clarifications, a lecture delivering the content, ending with hands-on lab practice
Class Times
- Lectures begin at 8:00 AM
- There is a 20 minutes break at 9:20 AM
- Practice lab starts at 9:40 AM
- Class ends at 10:50 AM
- Times may differ mid term, presentations and final
Weekly Course Objectives
- The weekly objectives include lessons on: Python, Math, Operators, Data Types, Flow Control, Functions, Variables, File I/O, Try Exception Blocks, and OPP / Classes
Python key features
- Easy to learn and read
- GUI programming, Broad Standard Library, Database Interfaces, Interactive Mode, Portable, Easy to Maintain
Python Reserved Words (Keywords)
- Keywords can be accessed with help("keyword") in the Python console.
- Python 3.13.1 has 36 keywords
- Keywords are lowercase, True, False and None being the exceptions.
- Keywords are always available without importing.
- Keywords differ from Python's built-in functions and types, as the restrictive usage of keywords don't apply to built-in functions.
- Keywords cannot be used as identifiers.
Lines and Indentation
- Python enforces code block with line indentation
- A convention of 4 paces is standard and the style guide for python programs can be found at peps.python.org/pep-0008/.
- Statements end with a newline unless there is \ to continue the statement on a second line.
- Line continuation character is not needed inside brackets.
Quotation and Comments
- String literals can be denoted with single ('), double ("), or triple quotes (""" or ''').
- Triple quotes can span strings across multiple lines.
- Comments begin with a hash sign (#) and are ignored by interpreters, from sign to end of the physical line.
- Multi-line comments start and end with 3 quotes
Module and functions for math
Math module
is used for: number-theoretic and representative functions, power and logarithmic functions, trigonometric, hyperbolic, special and constance like PiRandom module
generates simulations, and privacy features
Arithmetic Operators in Example x
and y
- Addition
+
adds two operands:x+y
- Subtraction
-
subtracts two operands:x-y
- Multiplication
*
multiplies two operands:x*y
- Division
/
divides the first operand by the secondx/y
- Floor division
//
performs division and returns integer quotientx//y
- Modulus
%
gives the remainder of divisionx%y
- Exponent
**
is the power operator to raise the first to the power of the secondx**y
Relational Operators in Example x
and y
- Equal
==
checks if operands are equalx==y
- Not equal
!=
checks if operands are NOT equalx!=y
- Greater than
>
compares the two operands:x>y
- Greater than or equal to
>=
compares the two operands:x>=y
- Less than
<
compares the two operands:x<y
- Less than or equal to
<=
compares the two operands:x<=y
Assignment operators with variables a
and b
- Assign
=
sets to left operand result of expression from right operand,x=y+z
- Add and assign
+=
adds the operands and assigns value to left,a += b
- Subtract and assign
-=
subtracts the operands and assigns value to left,a -= b
- Multiply and assign
*=
multiplies the operands and assigns value to left,a *= b
- Divide and assign
/=
divides the operands and assigns value to left,a /= b
- Modulus and assign
%=
returns modulus and assigns value to left,a %= b
- Floor divide and assign
//=
returns floor and assigns value to left,a //= b
- Exponent and assign
**=
returns exponent and assigns value to left,a **= b
- Bitwise AND assign
&=
preforms and calculation and assigns value to left,a &= b
- Bitwise OR assign
|=
preforms or calculation and assigns value to left,a |= b
- Bitwise XOR assign
^=
preforms xor calculation and assigns value to left,a ^= b
- Bitwise right shift assign
>>=
preforms right shift and assigns value to left,a >>= b
- Bitwise left shift assign
<<=
preforms left shift and assigns value to left,a <<= b
data types
- Explicit declarations are not required.
- Data type conversions: int(x [,base]), float(x)
Data type characteristics:
String
: text encapsulated in quotations, uses slice operator ([] and [:]) to call subsets,+
to concatenate,*
to repeat string, and string formatting operators (%) are %s, %d, %f, %.<number of digits>fList
: items are separated by commas and enclosed in [], the values stores are accessed by the slice operator at indexes starting at 0 and ending at list[length] -1, and lists can be use concatenation and repetitionTuple
: elements enclosed in “()”. It's best when data is unchangeable. Can convert to lists and uses same list functionsDictionary
: key-value pairs, with ":" separating pairs, and "," to separate items
Flow Control Structures:
If statements
: Simple conditional checkIf / else Statements
: Conditional checks that offers and alternative blockIf / elif / else Statements
: Allowing multiple conditionsNested If statements
: Conditional statements within conditional statements- Conditional statements end with ":", and code must be indented
- Code must be indented by four spaces
- End a code block be un-indenting to same level
Loop control structures
While
: executes block as long as statement true. Boolean conditional, and block statement.While <statement>: <statment(s)>
for…in
: iterates over sequence until is exhausted. Has variable being iterated and block statement.for <iterating variable> in <Sequence>: statment (s)
For/While...else
: Else statement executes if loop terminates normally- Decisional structures have ":" and indentation apply
Flow control: Loop structure
- A
break
statement is used to terminate a loop iteration process and continues code execution to statements outside of loop block. For nested lookups,break
terminates loop and resumes next line of code. - Use
continue
statements to skip current iteration and recheck the condition
Functions: Introduction
- Functions enable reuse of code segments accross programs, operate independently, and encapsulate specific tasks
- Functions allow for organised code structure, combine to create applications, and can be defined once and called multiple times
- The anatomy is
def function-name(parameters ): "function_docstring" Block of statements return [expression] (optional)
Function Parameters:
- The number of arguments in the function call must match with the function, unless there is a variable length argument list.
- A
parameter
is the variable inside the parentheses in the function definition. - An
argument
is value that is sent to the function when it's called.
Function - Optional Parameters
- The default parameter has values that are provided when defining functions and assigning the assignment operator (=).
- When calling default parameters are becoming optional.
- Providing values overrides default values.
- Functions contain any number of default parameters and should be non-default.
Functions: Positional and Keyword Parameters
- Parameters are given keyword, so there’s no need to maintain order
- When calling keyword arguments match parameters define in function
- Default can be skipped with optional parameters
- Arguments must be entered with an appropriate value, the function will still work unless using keywords
- Keyword and positional can be used with order using keywords
Function - Variable length parameters
- Functions can accepts variable number of arguments and variable number of keyword arguments.
Variable Scope
- Local variables are defined inside function and cannot be accessed
- Variables can also be defined in the program and are global variable
File Operations and Attributes
- Open
file = open(file_name [, access_mode])
- Access mode where "r" opens for reading and "w" for writing
- Close
file.close()
- Write
file.write(string)
to the file - Determine the working mode of the file:
file.mode
– returns code - Call the name of the file
file.name
- Confirm that a file is closed:
file.closed
returns T or F
Try Blocks
- Try handles errors while program is processing. If error occurs during
try...except
structure the states is set, error handles and program runs normally. - Structures contains try, except, else, and can contain finally
try: "<type code to test here>"
runs a block of code that might have errorexcept “<type of exception>": “<code of exception>"
runs if error in code is detected"else: “<code executes if no exception>
" run alternative code if there is no error- Finally always executed and always executes
Object Oriented Programming (OOP)
- Methods and entities are wrapped in entities. Important in big development.
- The two main concepts are
Class
the framework, andObject
the instance. - The object stores variables which access throughout the class or variables for methods.
Classes
- Classes
create a new class
with name, data, methods and attributes. class ClassName:
is the basic structure- Instance Name = class_name (arg...) will create instance of class
__import__
allows for data to me initialized. The process is to initialize that information, set to our demands.- Pascal Notation
PascalCase
capitalizes each word in the title.
Modules and Packages
- The Python Standard Library is a collection of modules for platform independent APIs
- modules are distributed with Python and are available on your Python program. They are used to write code from scratch by delivering readily available solutions
- help(), dir() to understand the capabilities of a library: help() provides review and dir() lists attributes
- Module Examples: os and sys, datetime and time, random, collections, json, csv and others
Name space
- A container that holds a collection of names (identifiers) and maps them to corresponding objects. Namespaces unique and can be used without conflicts
- They consist of built-in objects and functions available throughout program. The global is top level for modules, but can surpassed by local and encapsulated
- Order (LEGB rule) will determine how these functions will be implemented as you progress
- Built in -> Global - > Enclosed -> Local
Imports
- Imports helps share load/reuse code from modules or packages.
- To use a module, use the import statement in another Python file.
- Modules also create their own ceces to avoid name conflicts.
Python files, code
- Modules organize Vital Python code and allow it to be reusable.
- You create folder with " init". This is Python file that can initialize
- Create files extension ".py"
- Create subpackages within folder that contains " _init _.py": import then call
Asyncio
- Concurrency is handled at overlapping times.
- Parallelism is similar execution at the same time through multiple mediums.
- Asyncio is when tasks don't always come due to the time that takes
The structure components are:
- The standard library is helpful for writing code
- An even loop provides a code management or tasks
- Asyncio is helpful for concurrency servers that are in high concurrency
Loop components functions:
- Define functions when working with "async def" for execution
- Loop component manages execution through events
- Futures allow representation during communication, with a way to retrieve result when completed
- task to or future by management of loop
- Run
Run a Coroutine
: takes a single co-routine as its argument and runs it until it completes. Manages Loop: It automatically creates and starts an event loop. Once the coroutine finishes, it stops and closes the event loop, ensuring proper cleanup. Async Code: It allows asynchronous code to run from a synchronous context - Syntax for Await: It pauses the execution of the coroutine until the awaitable object it is waiting on completes.
- Syntax for
await asyncio.sleep(2)
- Task creates a task object with wraps with Coroutine with in event run
How loops work
- Used to schedule the execution of a coroutine concurrently with other - loop object.
- The new features make the program runs immediately as control is acquired after each cycle.
- Gather allows one or more and provides coroutines are used to allow function and manages coroutines to be executed and managed properly with code
- Gather allows for async.gather (*coroutines)
Libraries in Asyncio
- Library is used for many features such as async wait, to manage the operation in code.
- The Asynchronous HTTP is useful for scale, clients operations and servers. Async provides asynchronous database features. The library reads/ writes async
- Httpx is a asynchronous client with versatile. Motor asynchronous with Monogo, Trio with alternative style
- Useful for IO bound operations in network requests, or GUI - asynchronous in system requests
- Easy for programming, data processing. Helpful as user handling that is high
Asyncio - Threading:
- Asyncio is more efficient for IO related tasks, threading is a simple
- Threading takes a lot of energy
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.