Podcast
Questions and Answers
Which of the following is the correct way to use the modulo operator to format a string in Python?
Which of the following is the correct way to use the modulo operator to format a string in Python?
- `'Hello, %s! You are %d years old.' % ('Alice', 30)` (correct)
- `'Hello, %name! You are %age years old.' % {name: 'Alice', age: 30}`
- `'Hello, {name}! You are {age} years old.' % (name='Alice', age=30)`
- `'Hello, {0}! You are {1} years old.'.format('Alice', 30)`
In Python, what is the primary purpose of comments in code?
In Python, what is the primary purpose of comments in code?
- To optimize the code for faster execution.
- To be executed by the Python interpreter as instructions.
- To define the data types of variables used in the code.
- To provide information for human readers to understand the code. (correct)
Which of the following is NOT a valid rule for naming identifiers in Python?
Which of the following is NOT a valid rule for naming identifiers in Python?
- Identifiers are case-insensitive. (correct)
- Identifiers can be of any length.
- Identifiers must start with a letter or an underscore.
- Identifiers can contain letters, digits, and underscores.
What happens when you try to use a keyword
as a variable name in Python?
What happens when you try to use a keyword
as a variable name in Python?
In Python, what is the significance of the None
type?
In Python, what is the significance of the None
type?
Which of the following data types is immutable in Python?
Which of the following data types is immutable in Python?
What is the result of the following Python code?
x = 10
y = 3.14
z = x + y
print(z)
What is the result of the following Python code?
x = 10
y = 3.14
z = x + y
print(z)
What does the term 'object sharing' or 'aliasing' refer to in Python?
What does the term 'object sharing' or 'aliasing' refer to in Python?
What is the purpose of the del
statement in Python?
What is the purpose of the del
statement in Python?
Given the following code, what will be output?
a = [1, 2]
b = a
print(a is b)
Given the following code, what will be output?
a = [1, 2]
b = a
print(a is b)
What is the associativity of most operators in Python, and how does it affect evaluation?
What is the associativity of most operators in Python, and how does it affect evaluation?
What makes the exponentiation operator (**
) unique in terms of associativity?
What makes the exponentiation operator (**
) unique in terms of associativity?
In Python, what are the three key attributes that every object has?
In Python, what are the three key attributes that every object has?
What is the difference between rebinding a variable and mutating an object in Python?
What is the difference between rebinding a variable and mutating an object in Python?
Given the code below, what will be the final output?
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Given the code below, what will be the final output?
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Which of the following scenarios best illustrates the importance of understanding mutability in Python?
Which of the following scenarios best illustrates the importance of understanding mutability in Python?
What is the key difference between a function and a method in Python?
What is the key difference between a function and a method in Python?
How do you list all available methods for a given type in Python?
How do you list all available methods for a given type in Python?
Which of the following statements correctly describes the use of modules and importing in Python?
Which of the following statements correctly describes the use of modules and importing in Python?
What is the primary role of indentation in Python code?
What is the primary role of indentation in Python code?
Flashcards
What is the input()
function?
What is the input()
function?
A function that takes a prompt as an argument and returns the user's input as a string.
What is Old-style String Formatting?
What is Old-style String Formatting?
A method using the modulo operator (%) to format strings, similar to C's printf function.
String Formatting Method
String Formatting Method
A string formatting method where values are substituted using .format().
What are f-Strings?
What are f-Strings?
Signup and view all the flashcards
What are Comments in Python?
What are Comments in Python?
Signup and view all the flashcards
What are Identifiers in Python?
What are Identifiers in Python?
Signup and view all the flashcards
What are Keywords in Python?
What are Keywords in Python?
Signup and view all the flashcards
What is a Variable in Python?
What is a Variable in Python?
Signup and view all the flashcards
What are Python's Numeric data types?
What are Python's Numeric data types?
Signup and view all the flashcards
What are Container Types?
What are Container Types?
Signup and view all the flashcards
What is a String in Python?
What is a String in Python?
Signup and view all the flashcards
What is a List in Python?
What is a List in Python?
Signup and view all the flashcards
What is a Tuple in Python?
What is a Tuple in Python?
Signup and view all the flashcards
What is a Dictionary in Python?
What is a Dictionary in Python?
Signup and view all the flashcards
What is a Set in Python?
What is a Set in Python?
Signup and view all the flashcards
What is Implicit Type Conversion?
What is Implicit Type Conversion?
Signup and view all the flashcards
What is Explicit Type Casting?
What is Explicit Type Casting?
Signup and view all the flashcards
What is the Identity of an Object?
What is the Identity of an Object?
Signup and view all the flashcards
What is Object Sharing or Aliasing?
What is Object Sharing or Aliasing?
Signup and view all the flashcards
What is Dynamic Typing?
What is Dynamic Typing?
Signup and view all the flashcards
Study Notes
Python Fundamentals: Input/Output
- The
input()
function displays a prompt and gets user input as a string. name = input("Enter your name: ")
prompts the user for their name.age = int(input("Enter your age: "))
prompts for age and converts the input to an integer.print("Hello World")
outputs a string.print("and your age,", age)
outputs a string and the value of theage
variable.
Output Formatting in Python
- Python has multiple string formatting methods each with unique syntax and advantages.
- Old-style string formatting utilizes the (%) modulo operator, similar to C's
printf
function. %s
is a placeholder for strings, and%d
is a placeholder for integers.- Values are substituted based on their order in a tuple.
- Example:
name = "Alice" age = 30 print("Hello, %s! You are %d years old." % (name, age)) # Output: Hello, Alice! You are 30 years old.
- The string formatting method uses
.format()
with{}
placeholders.name = "Bob" age = 25 print("Hello, {}! You are {} years old.".format(name, age)) # Output: Hello, Bob! You are 25 years old.
- F-strings (formatted string literals) use an
f
before the string and evaluate variables directly inside curly braces{}
.name = "Charlie" age = 35 print(f"Hello, {name}! You are {age} years old.") # Output: Hello, Charlie! You are 35 years old.
- Format specifiers inside curly braces customize number and string formatting.
number = 3.14159 formatted_number = f"Pi is approximately {number:.2f}" print(formatted_number) # Output: Pi is approximately 3.14
.2f
formats the number as a floating-point number with two decimal places.- Other format specifiers:
f
: Floating-point numbere
: Scientific notation%
: Percentage
Comments
- Comments are ignored by the Python interpreter.
- Single-line comments begin with
#
. - Multi-line comments (docstrings) are enclosed in triple quotes
"""Docstring goes here"""
. - Comments improve code readability, facilitate maintenance, and aid in debugging.
Identifiers
- Identifiers are names for variables, functions, classes, etc.
- Identifiers must begin with a letter or underscore.
- Identifiers can contain letters, digits, and underscores.
- There is no limit to identifier length.
- Identifiers are case-sensitive.
- Keywords are reserved with predefined meanings and can't be identifiers.
- Use
help('keywords')
to list them. - Avoid using built-in names as identifiers.
- Use meaningful and descriptive identifier names.
- Use lowercase with underscores for variables and functions, and CapWords for classes.
- Avoid single or double leading underscores.
Variables and Data Types
- A variable is a named storage location for a value.
- Python automatically assigns the data type based on the assigned value, without explicit declaration.
- Numeric types:
int
: Integer numbers (e.g., 10, -5, 0)float
: Floating-point numbers (e.g., 3.14, -2.5)complex
: Complex numbers (e.g., 2+3j)
bool
: Boolean (True
orFalse
)None
: Represents the absence of a value- Container types hold collections of objects.
- Sequential Collections:
str
: Sequence of characters (e.g., "Hello, world!")list
: Ordered collection of items (e.g.,[1, 2, 3, "apple"]
)tuple
: Ordered, immutable collection of items (e.g.,(1, 2, 3)
)
- Associative Collections:
dict
: Unordered collection of key-value pairs (e.g.,{ "name": "Alice", "age": 30}
)set
: Unordered collection of unique items (e.g.,{1, 2, 3}
)
Type Conversions
- Implicit type conversion: Python automatically converts data types when necessary.
- Explicit type conversion (type casting): Use functions like
int()
,float()
, andstr()
.x = 10 # int y = float(x) # y will be a float (10.0)
Object
- Everything in Python is an object with a type, identity, and value.
- Objects are chunks of memory used to store data.
- Type: The kind of object (e.g.,
int
,list
). - Identity: A unique integer identifier for the object (memory address).
- Value: The data stored inside the object.
- Python stores values in objects, and variables are names that reference these objects.
- Assigning a value to a variable binds the name to an object.
x = 56 # x refers to an integer object with value 56 p = 'Hello' # p refers to a string object
- Variables act as object references, storing memory locations rather than values themselves.
- Assigning one variable to another does not copy the object, both variables point to the same object.
z = x # z now refers to the same object as x
- All variables are bound to the same object, and any of them can be used to access it.
- Using
id(variable)
confirms this. - Variables can be reassigned to new objects.
x = 25 # Now x refers to a new object z = z + 3 # z is rebound to a new object with value 59 y = 3.6 # y now refers to a float object
- If no variable references an object, Python's garbage collector removes it.
- Multiple assignment assigns the same value to multiple variables simultaneously.
variable1 = variable2 = variable3 = value
- Pairwise assignment assigns different values to multiple variables in a specific order.
x, y, z = 1, 2.5, 3 # x gets 1, y gets 2.5, z gets 3
- The number of variables on the left must match the number of values on the right in pairwise assignment.
- Python is dynamically typed, variables do not have fixed types.
Deleting a Name
- The
del
statement removes a variable reference.x = 50 del x # print(x) # This will cause an error since x no longer exists
Operators
- Arithmetic operators:
+
,-
,*
,/
,//
(floor division),%
(modulo),**
(exponentiation) - Result Type:
/
always returns a float.//
returns an integer if both operands are integers, otherwise a float. /
preserves decimal precision,//
discards the decimal part.- Comparison:
==
,!=
,<
,>
,<=
,>=
- Logical:
and
,or
,not
- Identity:
is
,is not
(compare object identities)a = [1, 2] b = a print(a is b) # True
- Membership:
in
,not in
(check if a value is in a sequence)fruits = ["apple", "banana"] print("apple" in fruits) # True
Python Operator Precedence and Associativity
- Operator precedence dictates the order of operations:
- Parentheses
()
- Exponentiation
**
(Right-to-Left) - Positive, Negative, Bitwise NOT
+x, -x, ~x
(Right-to-Left) - Multiplication, Division, Floor Division, Remainder
*, /, //, %
(Left-to-Right) - Addition, Subtraction
+, -
(Left-to-Right) - Bitwise Shift
<<, >>
(Left-to-Right) - Bitwise AND
&
(Left-to-Right) - Bitwise XOR
^
(Left-to-Right) - Bitwise OR
|
(Left-to-Right) - Membership, Identity tests, Comparisons
in, not in, is, is not, <, <=, >, >=, !=, ==
(Left-to-Right) - Boolean NOT
not
(Left-to-Right) - Boolean AND
and
(Left-to-Right) - Boolean OR
or
(Left-to-Right)
- Parentheses
- Associativity determines the evaluation direction when operators have the same precedence. Most operators are left-to-right.
- The exponentiation operator
**
is right-to-left.
Mutable/Immutable
- Every Python object has a type, ID, and value.
- Immutable Types: Value can't be changed after creation (e.g.,
int
,float
,bool
,str
,tuple
,frozenset
). - Mutable Types: Value can be modified in-place (e.g.,
lists
,sets
,dictionaries
). - Mutability applies to objects, not variable names. Variables can be rebound to a new object.
- Rebinding a variable means making it reference a new object and applies to both mutable and immutable types.
- Example:
a = 56 # a refers to an int object with value 56 a = a + 3 # a now refers to a new int object with value 59
- Int is immutable.
a + 3
doesn't modify the original object but creates a new one.x = [1, 2, 3] # 'x' refers to a list object x = [4, 5, 6] # 'x' is now rebound to a new list object
- When
x = [4, 5, 6]
is executed, a new list object is created, discarding the reference to the original. - Mutating an object changes the content of a mutable object in-place.
x = [1, 2, 3] # x refers to a list object x.append(4) # The list object itself is modified
- Changes to a mutable object affect all references.
Functions/Methods
- Functions are reusable blocks of code that perform specific tasks.
- Built-in Functions: Always available in Python (e.g.,
print()
,input()
,type()
,id()
). - Methods are functions associated with a specific data type and use dot notation.
'hello'.upper() list1.append(10)
dir(typename)
lists all methods for a type.help(typename.methodname)
provides details about a method.
Modules and Importing
- Standard Library: Pre-written modules with functions and tools.
- Modules: Python files that organize related functions and definitions.
- Importing makes module functions available.
from math import sqrt, trunc # Imports specific functions sqrt(34) # Use functions directly
import math # Imports the entire module math.sqrt(34) # Prefix functions with module name
help(modulename)
shows module documentation.dir(modulename)
lists names defined in a module.
Indentation
- Indentation defines code blocks.
- Use the same indentation consistently, typically four spaces.
- It enhances readability and prevents errors.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.