Python Basics

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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?

  • 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?

  • 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?

<p>Enclosing the comment between three single quotes <code>'''</code> or three double quotes <code>&quot;&quot;&quot;</code>. (D)</p> Signup and view all the answers

What is the correct method to access all available Python keywords within the Python console?

<p><code>help(&quot;keywords&quot;)</code> (D)</p> Signup and view all the answers

Given that Python's built-in functions can be reassigned, what might be an unexpected consequence of reassigning print = 42?

<p>Subsequent calls to <code>print()</code> will result in a <code>TypeError</code> because it is no longer a function. (D)</p> Signup and view all the answers

Assuming no imports, which of these operations would definitively raise a NameError in standard Python?

<p><code>undefined_variable + 1</code> (A)</p> Signup and view all the answers

Which arithmetic operator returns the remainder of a division operation?

<p>% (A)</p> Signup and view all the answers

What is the primary benefit of using composition in object-oriented design?

<p>Code reuse and modularity (B)</p> Signup and view all the answers

Which relational operator checks if two operands are not equal?

<p>!= (B)</p> Signup and view all the answers

In Python, what is the result of the expression 17 // 5?

<p>3.0 (A), 3 (C)</p> Signup and view all the answers

If x = 5 and y = 2, what does the expression x ** y evaluate to?

<p>25 (B)</p> Signup and view all the answers

Which of the following best describes the relationship established through composition?

<p>Has-a (B)</p> Signup and view all the answers

Given a = 10 and b = 5, which expression will return True?

<p>a &gt;= b (D)</p> Signup and view all the answers

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?

<p>Composition (A)</p> Signup and view all the answers

Which of the following best describes the primary function of the __next__() method in an iterator?

<p>To return the next item in the stream of data. (A)</p> Signup and view all the answers

Assuming x = 15 and y = 4, what would be the result of the expression x % y + x // y * y?

<p>19 (A)</p> Signup and view all the answers

Which of the following is an example of an iterable in Python?

<p>A list (A)</p> Signup and view all the answers

Which statement accurately distinguishes between iterables and iterators?

<p>All iterators are iterables, but not all iterables are iterators. (D)</p> Signup and view all the answers

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?

<p>It will return <code>3</code> and then raise a <code>StopIteration</code> error on the subsequent call. (A)</p> Signup and view all the answers

In the context of iterators and iterables, what is the significance of an iterator maintaining its state?

<p>It enables the iterator to resume iteration from where it left off. (B)</p> Signup and view all the answers

In the context of object-oriented programming, what principle is demonstrated when a Car class contains instances of Engine, Wheel, and Body classes?

<p>Composition (A)</p> Signup and view all the answers

When should inheritance be favored over composition in object-oriented design?

<p>When a clear 'is-a' relationship exists between two classes. (A)</p> Signup and view all the answers

Which of the following scenarios is best addressed using composition rather than inheritance?

<p>Implementing different payment methods (CreditCard, PayPal) for a <code>PaymentSystem</code>. (A)</p> Signup and view all the answers

Why does composition provide more flexibility than inheritance in defining the abilities of GameCharacter objects?

<p>Composition allows abilities to be mixed and matched dynamically. (A)</p> Signup and view all the answers

What is the primary advantage of using composition in a PaymentSystem that supports multiple payment methods?

<p>It allows easy addition or removal of payment methods without modifying the <code>PaymentSystem</code> core. (A)</p> Signup and view all the answers

Regarding operator overloading in Python, which statement is most accurate?

<p>It enables customized behavior of operators for instances of user-defined classes. (D)</p> Signup and view all the answers

What are 'dunder' methods in Python, and how are they related to operator overloading?

<p>They are special methods with double underscores that define the behavior of operators. (D)</p> Signup and view all the answers

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?

<p>The <code>__add__</code> method. (A)</p> Signup and view all the answers

Consider the expression 2 + 'b'. Why does this operation result in an error in Python, and how could operator overloading potentially address this?

<p>Operator overloading could be used to define a custom <code>__add__</code> method that handles the addition of an integer and a string, but it requires careful type checking to avoid unexpected behavior. (B)</p> Signup and view all the answers

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?

<p>Ensure both <code>instance1</code> and <code>instance2</code> are of compatible types, and define <code>__add__</code> in the class of <code>instance1</code> to handle the operation with consideration for the type of <code>instance2</code>. (B)</p> Signup and view all the answers

What is the primary purpose of the __str__() method in Python classes?

<p>To control how an object is converted to a string for display. (B)</p> Signup and view all the answers

If a class does not have a __str__() method defined, what does the print() function do when called on an instance of that class?

<p>Calls the <code>__repr__()</code> method if it exists, otherwise uses the default object representation. (B)</p> Signup and view all the answers

What should the __str__() method always return?

<p>A string. (C)</p> Signup and view all the answers

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)?

<p><code>10</code> (A)</p> Signup and view all the answers

What is a potential pitfall of overusing operator overloading in Python?

<p>It can reduce code clarity. (C)</p> Signup and view all the answers

Which of the following is a good practice to follow when implementing operator overloading?

<p>Ensure overloaded operators behave consistently with expectations. (A)</p> Signup and view all the answers

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?

<p>When the <code>str()</code> function is called on the object. (D)</p> Signup and view all the answers

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?

<p>The <code>Vector</code> class does not have an <code>__add__</code> method defined. (D)</p> Signup and view all the answers

Which of the following is NOT typically a real-world application of operator overloading?

<p>Automatically generating documentation for Python code. (A)</p> Signup and view all the answers

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)

<pre><code class="language-python">def __mul__(self, other): real_part = self.real * other.real - self.imag * other.imag imag_part = self.real * other.imag + self.imag * other.real return ComplexNumber(real_part, imag_part) ``` (D) </code></pre> Signup and view all the answers

Flashcards

PEP 8

A guide for Python code style, emphasizing readability.

Python Keywords

Special words that Python reserves for specific purposes; they cannot be used as identifiers.

Python Indentation

Indentation is crucial in Python; it defines code blocks. Conventionally uses 4 spaces.

Python String Literals

You can use single quotes (''), double quotes (""), or triple quotes (''' or """) to define string literals.

Signup and view all the flashcards

Python Comments

Use the hash symbol (#) to add explanatory comments to your code.

Signup and view all the flashcards

Math Module

A Python module that provides access to various mathematical functions.

Signup and view all the flashcards

Random Module

This module implements pseudo-random number generators for various distributions.

Signup and view all the flashcards

Addition (+)

Adds two operands.

Signup and view all the flashcards

Subtraction (-)

Subtracts the second operand from the first.

Signup and view all the flashcards

Multiplication (*)

Multiplies two operands.

Signup and view all the flashcards

Division (float) (/)

Divides the first operand by the second, resulting in a floating-point number.

Signup and view all the flashcards

Division (floor) (//)

Divides and returns the integer quotient.

Signup and view all the flashcards

Modulus (%)

Returns the remainder of a division.

Signup and view all the flashcards

Exponent (**)

Returns the first operand raised to the power of the second.

Signup and view all the flashcards

Equal To (==)

Checks if two operands have the same value.

Signup and view all the flashcards

Composition

A design technique where a class includes objects of other classes as attributes.

Signup and view all the flashcards

Operator Overloading

Using operators (like +, -, *) to work with custom objects, allowing them to behave like built-in data types.

Signup and view all the flashcards

Iterable

Any Python object you can loop through, like lists, tuples, strings, and dictionaries.

Signup and view all the flashcards

Iterator

An object that provides __iter__() and __next__() methods to traverse an iterable. It maintains state.

Signup and view all the flashcards

next()

Method in iterators that retrieves the next element; raises StopIteration when finished.

Signup and view all the flashcards

Iterable

An object that can be iterated over. It provides an iterator.

Signup and view all the flashcards

How does print() work?

When an object is printed, Python looks for a str() method. If not found, it uses repr() or a default representation.

Signup and view all the flashcards

__str__() Method

A special method in a class that controls how an object is represented as a string. Used by print() and str().

Signup and view all the flashcards

Overloading __str__

Overloading __str__ lets you customize the output when printing objects of that class, providing user-friendly string representation.

Signup and view all the flashcards

Operator Overloading Pitfalls

Overloading methods should maintain logical consistency to prevent unexpected behavior. Operations like addition (+) should behave as expected regarding commutativity.

Signup and view all the flashcards

Frameworks: Custom Operators

Custom classes often overload operators to add/modify functionality.

Signup and view all the flashcards

Numeric Libraries: Custom Operators

Extensively uses math and other operators for element-wise operations

Signup and view all the flashcards

Consistency in Overloading

Ensure overloaded operators behave as expected to avoid confusion.

Signup and view all the flashcards

Avoid Overusing Overloading

Limit overloading to maintain readability and avoid unexpected behavior.

Signup and view all the flashcards

Inheritance

An 'is-a' relationship where a class inherits properties and behaviors from a parent class.

Signup and view all the flashcards

Game Character Abilities

Using composition to dynamically combine abilities for different characters.

Signup and view all the flashcards

Payment System Composition

Allows a system to use different payment methods without inheriting from them.

Signup and view all the flashcards

Dunder (Magic) Methods

Special methods with double underscores that redefine operator behavior.

Signup and view all the flashcards

Why use Operator Overloading?

The ability to make operators work with user-defined classes.

Signup and view all the flashcards

int.add(x, y)

A function that can be used to add two integer objects together.

Signup and view all the flashcards

TypeError

A common mistake when adding operands with different datatypes.

Signup and view all the flashcards

Operator Overloading Benefits

Allows a class to define custom behavior when used with standard mathematical operators.

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 Pi
  • Random 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 second x/y
  • Floor division // performs division and returns integer quotient x//y
  • Modulus % gives the remainder of division x%y
  • Exponent ** is the power operator to raise the first to the power of the second x**y

Relational Operators in Example x and y

  • Equal == checks if operands are equal x==y
  • Not equal != checks if operands are NOT equal x!=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>f
  • List: 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 repetition
  • Tuple: elements enclosed in “()”. It's best when data is unchangeable. Can convert to lists and uses same list functions
  • Dictionary: key-value pairs, with ":" separating pairs, and "," to separate items

Flow Control Structures:

  • If statements: Simple conditional check
  • If / else Statements: Conditional checks that offers and alternative block
  • If / elif / else Statements: Allowing multiple conditions
  • Nested 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 error
  • except “<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, and Object 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.

Quiz Team

Related Documents

More Like This

Python Syntax Errors Quiz
10 questions
Python Basic Syntax Quiz
6 questions
Python Basic Operators and Syntax
16 questions

Python Basic Operators and Syntax

UserFriendlyAstrophysics avatar
UserFriendlyAstrophysics
Python Syntax and Comments
8 questions
Use Quizgecko on...
Browser
Browser