2 + 46
2 + 46
6.+, -, *, /, ** (power), // (floor division), % (modulus)(59 + 73 + 2) / 3 44.666666666666664
10**(3+1) # exponentiation (** is power, not ^)10000
3**2 # 3 squared9
10 // 3 # floor division (integer quotient)3
10 % 3 # remainder (modulus)1
=) binds the name (left) to the object (right).x = 48a, b, c, d = 7, 5, 8, 4
print(a, b, c, d)7 5 8 4
a, b = b, a
print(a, b)5 7
A–Z, a–z)0–9)_)_ (e.g., _cache), but that implies “internal” by convention.True, False, None, and, class, def, …).snake_case for variables/functions: total_count, is_ready.UPPER_CASE for constants: PI = 3.14159.Every value has a type describing what it represents and how it behaves.
0, -7, 42)3.14, -0.001, 1.0)True, False) — behave like ints (True==1, False==0)"Dhaka", "Data Science")x = 10 # int
y = 3.5 # float
name = "Rasel" # str
is_ready = True # bool
print(type(x), type(y), type(name), type(is_ready))<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
' or double " quotes.a = 'one way of writing a string'
b = "another way"c = """
This is a longer string that
spans multiple lines
"""
print(c)
This is a longer string that
spans multiple lines
17 + 4.321.3
17 + "seventeen" # raises TypeError (number + string)"This" + "That"'ThisThat'
str, bool, int, and float types are also functions that can be used to cast values to those types:s = '3.14159'
fval = float(s) # string → float
type(fval)float
ival = int(fval) # float → int (truncates toward zero)
print(ival)3
bval = bool(ival) # non-zero → True; zero → False
print(bval)True
int("3.5") fails; you must convert to float first, then to int if needed.
None TypeNone that is used to indicate the absence of a value.None is similar to NULL in Ra = None
a is None, a == None(True, True)
None.== checks value equality; is checks object identity (same memory address).x = 3000
y = 3000
z = x
x == y, x is y, x is z # equal values(True, False, True)
print() to display values intentionally.name = "Rasel"
score = 83.4567
print(f"Hello, {name}! Your score is {round(score, 0)}.")Hello, Rasel! Your score is 83.0.
n = 10
n += 5 # same as n = n + 5
n *= 2
n30
a = 0.1 + 0.2
a == 0.3, a(False, 0.30000000000000004)
math.isclose()import math
math.isclose(a, 0.3)True
Used to compare two operands and return a Boolean result (True or False).
Comparison operators (similar to R’s symbols):
| Meaning | Operator |
|---|---|
| equal to | == |
| not equal | != |
| greater / greater-equal | >, >= |
| less / less-equal | <, <= |
10 <= 15True
14 != 16True
x = 3
0 < x < 5, (0 < x and x < 5)(True, True)
and, or, not(2 < 5) and (10 > 3), (2 > 5) or (10 > 3), not False(True, True, True)
** for power, not ^.== vs is.math.isclose for comparisons.
11 Comments & Help
# this is a comment