Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views

Python Flash Cards

Uploaded by

Good Anony7
Copyright
© © All Rights Reserved
Available Formats
Download as ODS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Python Flash Cards

Uploaded by

Good Anony7
Copyright
© © All Rights Reserved
Available Formats
Download as ODS, PDF, TXT or read online on Scribd
You are on page 1/ 11

Sheet1

Operator
Type Operator Description Syntax/Example

Arithmetic + Addition of two numbers. result = a + b

Subtraction of one number


Arithmetic - from another. result = a - b

Arithmetic * Multiplication of two numbers. result = a * b

Division of one number by


Arithmetic / another (returns float). result = a / b

Floor Division, returns the


largest integer less than or
Arithmetic // equal to the result. result = a // b
Modulus, returns the remainder
Arithmetic % of the division. result = a % b
Exponentiation, raises a
number to the power of
Arithmetic ** another. result = a ** b

Comparison Err:520 Checks if two values are equal. if a == b:


Checks if two values are not
Comparison != equal. if a != b:

Checks if the left operand is


Comparison > greater than the right. if a > b:
Checks if the left operand is
Comparison < less than the right. if a < b:
Checks if the left operand is
greater than or equal to the
Comparison >= right. if a >= b:
Checks if the left operand is
Comparison <= less than or equal to the right. if a <= b:

Logical AND operator. Both


Logical and conditions must be true. if a and b:

Page 1
Sheet1

Logical OR operator. At least


Logical or one condition must be true. if a or b:
Logical NOT operator.
Logical not Reverses the truth value. if not a:

Page 2
Sheet1

Edge
Case/Best
Explanation Practice
Ensure both
are numbers;
otherwise, it
will
concatenate
Adds a and b. strings.
Negative
numbers
should be
handled
Subtracts b from a. correctly.
Multiplying by
zero results in
Multiplies a by b. zero.
Division by
zero raises a
ZeroDivisionE
Divides a by b, result is a float. rror.
Useful for
integer
division but be
cautious with
negative
Floors the division. numbers.
Returns the remainder of a Check for zero
divided by b. to avoid errors.
Large powers
can cause
Raises a to the power of b. overflow.
Use is for
identity
Evaluates to True if a is equal comparison
to b. (same object).
Evaluates to True if a is not
equal to b.
Type
comparison
Evaluates to True if a is greater should be
than b. consistent.
Evaluates to True if a is less
than b.

Evaluates to True if a is greater


than or equal to b.
Evaluates to True if a is less
than or equal to b.
Short-circuits;
if a is false, b
Evaluates to True if both a and is not
b are true. evaluated.

Page 3
Sheet1

Short-circuits;
Evaluates to True if either a or if a is true, b is
b is true. not evaluated.

not a: Evaluates to True if a is false.

Page 4
Sheet2

Edge
Syntax/ Case/Best
Function Description Example Explanation Practice
Reads a line of Prompts the Always
input from the user for input validate the
user as a and stores it in input to avoid
input() string. input(prompt) a variable. type errors.
Converts a Takes input as Use try-except
string or a string and for error
number to an converts it to handling on
int() integer. int(value) an integer. conversion.
Converts a
string or Takes input as Same as
number to a a string and above; handle
floating-point converts it to a exceptions for
float() number. float(value) float. invalid input.
Converts a Converts a
value to a number to a
str() string. str(value) string.

Evaluates the Avoid using


Evaluates a input as a eval on
string as a Python untrusted input
Python eval(expressio expression (use to prevent
eval() expression. n) cautiously!). security issues.

Page 5
Sheet3

Edge
Syntax/ Case/Best
Operation Description Example Explanation Practice
Be mindful of
Joins two or memory usage
more strings Combines the with large
Concatenation together. str1 + str2 two strings. strings.
Repeats a
string a
specified Ensure n is a
number of Repeats str n non-negative
Repetition times. str * n times. integer.
Be cautious
Extracts with index
Extracts a characters values; out-of-
portion of a from start to range raises an
Slicing string. str[start:end] end-1. error.
Returns the
number of Returns the
characters in a length of the
Length string. len(str) string.

Converts all Converts string


characters to to uppercase
Uppercase uppercase. str.upper() letters.

Converts all Converts string


characters to to lowercase
Lowercase lowercase. str.lower() letters.

Converts the Capitalizes the Check for edge


first character first letter of cases with
of each word each word in punctuation
Title Case to uppercase. str.title() the string. and spaces.
Removes
whitespace Trims
from the whitespace
beginning and from both ends
Stripping end of a string. str.strip() of the string.
Returns the
index of the
Finds the first first
occurrence of a str.find(substri occurrence; -1
Finding substring. ng) if not found.
Be aware of
Replaces replacing
occurrences of Replaces all substrings
a substring str.replace(old, occurrences of within longer
Replacing with another. new) old with new. strings.

Splits a string Check for edge


into a list Divides the cases with
based on a str.split(delimit string into a consecutive
Splitting delimiter. er) list. delimiters.

Page 6
Sheet3

Concatenates
Joins elements elements of a Ensure the list
of a list into a delimiter.join(l list into a is not empty to
Joining single string. ist) string. avoid errors.
Checks if a
substring Returns True if
Checking exists within a substring is
Substring string. substring in str found.
Allows
dynamic Use f-strings
Formats f"{value}" or insertion of for better
strings with "{} values into readability and
Formatting placeholders. {}".format() strings. performance.

Page 7
Sheet4

Edge
Syntax/ Case/Best
Concept Description Example Explanation Practice
Declaring a Creates a Keep variable
variable and variable x and names
Variable assigning a assigns it the descriptive for
Declaration value. x = 10 value 10. readability.
Must start with
a letter or
underscore,
can include Avoid using
Rules for letters, reserved
Variable naming numbers, and keywords (e.g.,
Naming variables. variable_name underscores. class, def).
A variable can
change its
Python uses type; here, x Ensure type
dynamic first holds an consistency
Dynamic typing for x = 5; x = integer and where
Typing variables. "Hello" then a string. necessary.
Suggesting a Use type hints
variable's type Indicates that a to improve
for clarity def add(a: int, and b should code
Type Hinting (optional). b: int) -> int: be integers. readability.
Naming
convention for Constants are Document the
constants usually named purpose of
(convention in uppercase constants in
Constants only). PI = 3.14 letters. comments.
Ensure the
Assigning number of
values to variables
multiple Assigns 1 to a, matches the
Multiple variables in 2 to b, and 3 to number of
Assignment one line. a, b, c = 1, 2, 3 c. values.

Can be Avoid global


accessed variables when
Variables throughout the possible; they
Global defined outside module or can cause hard-
Variables any function. global_var = 5 script. to-track bugs.
Local variables
can't be
Variables def accessed
Local defined inside my_function(): x is local to outside their
Variables a function. x = 10 my_function. function.
The context in Variables can Understand
which a be global, scope to avoid
variable can be local, or unintended
Variable Scope accessed. N/A nonlocal. side effects.
Differentiating list_var = [1, 2, Choose the
between 3] (mutable), Lists can be appropriate
mutable and tuple_var = (1, modified, type based on
Mutable vs immutable 2, 3) while tuples the required
Immutable types. (immutable) cannot. functionality.

Page 8
Sheet5

Edge
Control Syntax/ Case/Best
Structure Description Example Explanation Practice
Executes the
Allows block if the Keep
branching condition conditions
Conditional logic based on evaluates to simple for
Statements conditions. if condition: True. readability.
Executes if the
previous Use elif to
elif conditions are avoid deeply
another_condit False and this nested if
ion: one is True. statements.
Executes if
none of the Ensure else is
previous only used
conditions are when
else: True. applicable.

Used to Be careful with


Comparison evaluate Checks if a is data types; 1
Operators conditions. if a == b: equal to b. == '1' is False.

Validate inputs
to avoid
Checks if a is unexpected
if a < b: less than b. comparisons.
Short-circuit
behavior can
Combine Evaluates to save
Logical multiple True if both a computation
Operators conditions. if a and b: and b are True. time.
Can be used to
check for
Evaluates to multiple
True if either a conditions
if a or b: or b is True. efficiently.
Evaluates to Keep logic
True if a is clear to avoid
if not a: False. confusion.
Repeatedly
executes a Use break to
block of code Iterates over exit and
until a each item in an continue to
condition is for item in iterable (like a skip to the next
Loops met. iterable: list or string). iteration.
Continues Avoid infinite
looping as long loops by
as the ensuring the
while condition is loop condition
condition: True. changes.

Page 9
Sheet5

Stops the Use


nearest judiciously; it
enclosing loop can make code
Break Exits a loop and exits out of harder to
Statement prematurely. break it. follow.
Skips the Ensure that
current Jumps to the skipping is
iteration and next iteration necessary to
Continue continues with of the nearest avoid logical
Statement the next. continue enclosing loop. errors.
Used where a
statement is
syntactically Useful in
Acts as a required but no defining empty
Pass placeholder for action is functions or
Statement future code. pass needed. classes.

Page 10
Sheet6

Edge
Syntax/ Case/Best
Concept Description Example Explanation Practice
Creates a
Defines a def function that Use descriptive
Function reusable block function_name can be called names for
Definition of code. (parameters): later. clarity.
Ensure
Inputs to the def Takes name as parameters are
Parameters function. greet(name): an input. documented.

Ends the Functions


Sends a value function and without return
Return back to the optionally implicitly
Statement caller. return value returns a value. return None.
Allows If no value is
parameters to def passed, name Be cautious
Default have default greet(name="G defaults to with mutable
Parameters values. uest"): "Guest". defaults.
Specify
arguments by Makes the Ensure
name when function call parameters can
Keyword calling a greet(name="A clearer and be matched
Arguments function. lice") more flexible. correctly.
Accepts an def func(*args, Document how
Variable- arbitrary **kwargs): many
Length number of *args and allows flexible arguments are
Arguments arguments. **kwargs input. expected.
The inner
function can
access
Functions variables from Be cautious of
defined within the outer scope and
Nested other def outer(): def function's closure
Functions functions. inner(): scope. behavior.
Functions that Can accept a Ensure the
take other function as an passed
functions as def argument or function meets
Higher-Order arguments or apply_function return a expected
Functions return them. (f, x): function. signatures.
Anonymous Creates small, Use for simple
functions unnamed functions;
Lambda defined with lambda x: x * functions for avoid
Functions lambda. 2 short tasks. complexity.
Functions that A syntactic
modify the sugar for
behavior of wrapping a Use for
other @decorator_na function in logging, access
Decorators functions. me another. control, etc.
Describes what
the function
does, placed Keep it concise
Documentation """This is a right after the and
Docstrings for a function. docstring.""" definition. informative.

Page 11

You might also like