2 + 4
6
2 + 4
6
6
.+
, -
, *
, /
, **
(power), //
(floor division), %
(modulus)59 + 73 + 2) / 3 (
44.666666666666664
10**(3+1) # exponentiation (** is power, not ^)
10000
3**2 # 3 squared
9
10 // 3 # floor division (integer quotient)
3
10 % 3 # remainder (modulus)
1
=
) binds the name (left) to the object (right).= 48 x
= 7, 5, 8, 4
a, b, c, d print(a, b, c, d)
7 5 8 4
= b, a
a, b 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"
)= 10 # int
x = 3.5 # float
y = "Rasel" # str
name = True # bool
is_ready print(type(x), type(y), type(name), type(is_ready))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
'
or double "
quotes.= 'one way of writing a string'
a = "another way" b
= """
c This is a longer string that
spans multiple lines
"""
print(c)
This is a longer string that
spans multiple lines
17 + 4.3
21.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:= '3.14159'
s = float(s) # string → float
fval type(fval)
float
= int(fval) # float → int (truncates toward zero)
ival print(ival)
3
= bool(ival) # non-zero → True; zero → False
bval 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 R= None
a is None, a == None a
(True, True)
None
.==
checks value equality; is
checks object identity (same memory address).= 3000
x = 3000
y = x
z == y, x is y, x is z # equal values x
(True, False, True)
print()
to display values intentionally.= "Rasel"
name = 83.4567
score print(f"Hello, {name}! Your score is {round(score, 0)}.")
Hello, Rasel! Your score is 83.0.
= 10
n += 5 # same as n = n + 5
n *= 2
n n
30
= 0.1 + 0.2
a == 0.3, a a
(False, 0.30000000000000004)
math.isclose()
import math
0.3) math.isclose(a,
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 <= 15
True
14 != 16
True
= 3
x 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.
Comments & Help
# this is a comment