Constants and Variables
- Variables do not require type declaration
- Python uses
=for variable assignment and==to compare two values, returningTrueif equal andFalseotherwise. - Variables must be assigned before use (unlike C). A variable is created only after assignment.
- Undefined variable exception:
>>> age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
Constants — Immutable Variables
Python has no mechanism to ensure variables won’t change objects. No error is raised if altered, unlike C’s const. Extreme caution is advised.
Assignment Methods
The assignment operator = is right-associative.
- Single assignment:
age = 18
- Batch assignment:
a = b = c = 1- Unthinkable in C/C++ :(
- Compute then assign:
age = 17 + 1
- Separate assignment:
a, b, c = 1, 2, 3a == 1,b == 2,c == 3
When we write a = "Jack", the Python interpreter does two things:
- Creates a string object
'Jack'in memory (constant). - Creates a variable
ain memory and points it to'Jack'.
When you assign variable a to another variable b, this operation points b to the data a points to, as shown below:
>>> a = "Jack"
>>> a
'Jack'
>>> b = a
>>> b
'Jack'
>>> id(a)
4332916664
>>> id(b)
4332916664
The id() function checks a variable’s memory address.
[[Basic Functions#id()]]
- If another value is assigned to
a,id(a)changes whileid(b)remains the same:
>>> a = "Ross"
>>> a
'Ross'
>>> id(a)
Another number (different from 4332916664)
Variables and Objects
In Python, everything is an object: numbers, lists, functions—everything. Variables are references (or labels/names) to objects, and all operations on objects are performed through these references.
For example:
>>> a = 1
- Here, the number
1is the object, andais the variable (name). - The assignment
=binds a name to an object (labels the object1witha). - An object can have multiple labels (variables), but a variable can only bind to one object.
- Variables themselves have no type; the type is stored in the object and determined by the object’s type.
- Thus, Python doesn’t require variable type declarations upfront, as it automatically infers the object’s data type—a major difference from C/C++.
Strings
- Python does not distinguish between single characters and strings.
- Strings can be created with single
''or double""quotes (but not mixed!). - Triple single or double quotes create multi-line strings:
>>> name_1 = 'Jack'
>>> name_2 = "Rose"
>>> sentence_1 = '''Rose,
Jack,
You jump,
I jump!'''
>>> sentence_2 = """Life is short,
you need Python."""
# Works perfectly!
- To include quotes, use the escape character
\.
[[Basic Functions#String Functions]]
String Formatting
% Method
print('My wife is %c, she is %d.' % (name, age))
%is followed by a tuple or dict to pass formatted values.- Placeholder types:
![[Pasted image 20230628233506.png]]
>>> name = 'Bronya'
>>> age = 18
>>> print('My wife`s name is %s, she is %d years old.' % (name, age)) # % corresponds to the order in %()
My wife`s name is Bronya, she is 18 years old.
- Advanced
%[data name][alignment flag][width].[precision][type]- Data name is used for dict assignment; omit for arrays.
- Alignment flags:
+: Show sign.-: Left-align.space: Add a space before positive numbers to align with negatives.0: Add a zero before positive numbers to align with negatives.
- Width: Total length of the formatted string, padded with 0 or space if shorter.
- Precision: Decimal places.
- Type: Placeholder type.
format
- Use
{}as placeholders in the string, then append.format()with the variables to fill.
>>> name = 'Kiana'
>>> age = 18
>>> print('My wife is {}, she is {}.'.format(name, age)) # Fill in order
>>> print('My wife is {1}, she is {0}.'.format(age, name))
'''
Indices can be used inside {}.
Numbers inside {} correspond to .format() tuple/dict indices.
'''
>>> print('My wife is {name}, she is {age}.'.format(name=name, age=age)) # Or use variable names (mapped by object attributes)
>>> print('My wife is {name}, she is {age}.'.format(name='Kiana', age=18)) # Keyword mapping
>>> list1 = ['Kiana', 18]
>>> print("My wife is {0[0]}, she is {0[1]}.".format(list1)) # Dict index mapping
- Advanced
{:[fill char][alignment][sign flag][#][width][,][.precision][type]}- Fill char: Defaults to space if omitted.
- Alignment:
^: Center.<: Left-align.>: Right-align.
- Sign flags:
+: Show sign.space: Add a space before positive numbers to align with negatives.
#: Show0b,0o, or0xprefixes for binary, octal, or hexadecimal.- Width: Total string width.
,: Enable thousand separators.- Precision: Decimal places.
- Type: Placeholder type.
f-string
Formatted String Literals (f-strings), supported only in Python 3.6+.
Prefix the string with f to enable f-strings, allowing direct variable use inside {}.
>>> print(f'My wife is {name}, she is {age}.')
- f-strings also support
formatcontrol parameters:{variable:[fill char][alignment][sign flag][#][width][,][.precision][type]}
⭐ Slicing
- Sliceable objects: strings, tuples, lists.
name[a:b:c]
- The interval is
[a, b), includingabut excludingb. Omittingastarts from 0; omittingbgoes to the end. cis the step size (defaults to 1 if omitted).
==Whencis negative, slicing goes backward.==
>>> name = "polaris"
>>> print(name[1:3])
'ol'
>>> print(name[::-3])
'sap'
'''
'ris' takes 's', 'ola' takes 'a', 'p' takes 'p'
'''
>>> print(name[::-1])
'siralop'
# String reversal
- Slicing doesn’t modify the original object. Use slicing to create copies:
>>> x = [2, 3, 6, 2, 5]
>>> y = x[:]
>>> y.sort()
>>> print(x)
[2, 3, 6, 2, 5]
>>> print(y)
[2, 2, 3, 5, 6]
Integers, Floats, Complex Numbers
Integers (Int)
0xfor hexadecimal.0ofor octal.
Floats (Float)
- Decimal form.
- Scientific notation, where
10is replaced bye.- e.g.,
1.23e-6.
- e.g.,
Complex Numbers (Complex)
- Real part + imaginary part:
a + bj. complex(a, b).- Both
aandbare floats.
- Real part + imaginary part:
[[Basic Functions#type()]]
Floor Division (integer part of division):
a // bModulo:
a % bAbsolute value:
>>> a = 10
>>> b = 3
>>> a // b
3
>>> a % b
1
Boolean Values and None
True: Truthy (non-zero values, defaults to1).False: Falsy (= 0, defaults to0).None: Null value, not0(integer), and not a Boolean type butNoneType.
- Notes:
- Capitalize the first letter.
- Any computation or expression returning
TrueorFalseis a Boolean operation, e.g., comparison.
- The following evaluate to
False:0,0.0,-0.0None- Empty strings, lists, tuples, dictionaries.
- The following evaluate to
True:-1,1, or any non-zero value.- All non-empty strings, including
"False". - All non-empty dictionaries, lists, sets, tuples.
- Boolean values can be used in arithmetic:
True == 1,False == 0.
Boolean Operations
- AND (
and):- Only returns
Trueif all operands areTrue.
- Only returns
- OR (
or):- Returns
Trueif at least one operand isTrue.
- Returns
- NOT (
not):- Unary operator: Converts
TruetoFalseand vice versa. - ==Right-associative==.
- Unary operator: Converts
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> True and 0 + 3
3
>>> True or False
True
>>> 0 or True
True
>>> 0 or 0
0
>>> False or 31
31
>>> not 3
False
Operators
Python supports the following operators:
- Arithmetic
- Comparison (Relational)
- Assignment
- Logical
- Bitwise
- Membership
- Identity
- Operator Precedence
Arithmetic Operators
**: Exponentiation,x ** yreturnsxraised toy.
==Right-associative==.
>>> 2 ** 2 ** 3
256
>>> (2 ** 2) ** 3
64
>>> 2 ** (2 ** 3)
256
//: Floor division (returns the integer part of the quotient).- When mixing integers and floats, integers are converted to floats.
Comparison Operators
==: Checks if two objects are equal.
==Python allows chaining comparison operators.==a > b == cis equivalent toa > b and b == c.
Assignment Operators
**=: Exponentiation assignment,c **= aisc = c ** a.//=: Floor division assignment,c //= aisc = c // a.<<=: Left shift assignment,a <<= 2isa = a << 2.>>=: Right shift assignment.&=: Bitwise AND assignment,a &= bisa = a & b.|=: Bitwise OR assignment.^=: Bitwise XOR assignment.
Bitwise Operators
&: Bitwise AND (right-associative).|: Bitwise OR.^: Bitwise XOR.~: Bitwise NOT (right-associative).<<: Left shift.>>: Right shift.
Logical Operators
and: Boolean AND.x and y: ReturnsFalseifxisFalse; otherwise, returnsy’s evaluated value.
or: Boolean OR.x or y: Returnsxif non-zero; otherwise, returnsy’s evaluated value.
not: Boolean NOT.not x: ReturnsFalseifxisTrue, and vice versa.- ==Right-associative==.
Membership Operators
in:x in Y(xis an object/variable,Yis a string/dict/tuple). ReturnsTrueifxis found inY.not in:x not in Y. ReturnsTrueifxis not found.
Identity Operators
is: Checks if two identifiers reference the same object (i.e., identical in essence).x is y: ReturnsTrueifid(x) == id(y).
is not: ReturnsTrueifid(x) != id(y).
⭐ Operator Precedence
(): Parentheses.[]: Indexing.x.attribute: Attribute access.**: Exponentiation.~: Bitwise NOT.+@,-@: Unary plus/minus (sign).+@,-@are right-associative unary operators.
*,/,%,//: Multiplication, division, modulo, floor division.+,-: Binary addition/subtraction.<<,>>: Bitwise shifts.&: Bitwise AND.^: Bitwise XOR.|: Bitwise OR.<,<=,>,>=,==,!=: Comparison.=,+=,-=, etc.: Assignment.is,is not: Identity.in,not in: Membership.not: Logical NOT.and: Logical AND.or: Logical OR.,: Comma operator.
When will I have a drink and discuss the details again?