Basics
Comments
Comments in Python start with a #
. There isn't a "true" mutli-line comment like /**/
in JavaScript.
# This is a comment
# You need multi-line comments?
# Start each line with hash
haiku
Primitive Data Types
Python has four primitive data types
String
Integer
Float
Boolean
type('spam, spam, and spam')
type(3)
type(3.14)
type(True)
type(False)
isinstance('spam, spam, and spam', str)
isinstance(3, int)
isinstance(3.14, float)
isinstance(True, bool)
Everything is an object in Python
isinstance('spam, spam, and spam', object)
isinstance(3, object)
isinstance(3.14, object)
isinstance(True, object)
Variables
To define a variable in Python, type
eggs_ive_eaten = 3
print(eggs_ive_eaten)
In Python, variable names:
must start with a letter or underscore
cannot start with a number
contains only alpha-numeric characters and underscors
are case-sensitive
NOTE: The convention for multi-word variable names in Python is snake_case
Variables can be reassigned
eggs_ive_eaten = 4
print(eggs_ive_eaten)
Unlike JavaScript, you cannot declare a variable without initialising it with a value. The closest equivalent would be assigning None
let spam
console.log(spam) // -> undefined
spam = None
print(spam) # -> None
String Operators
+
Concatenation
*
Replication
print('spam, ' * 3 + 'and eggs')
Arithmetic Operators
+
Addition
-
Subtraction
*
Multiplication
/
Division
//
Integer Division
%
Modulus
**
Exponent
print(4 + 2 * 3) # -> 10
print((4 + 2) * 3) # -> 18
print(7 / 3) # -> 2.3333333333333335
print(7 // 3) # -> 2
print(4 ** 3) # -> 64
Compound Assignment Operators
+=
eggs += 2
eggs = eggs + 2
-=
eggs -= 2
eggs = eggs - 2
*=
eggs *= 2
eggs = eggs * 2
/=
eggs /= 2
eggs = eggs / 2
//=
eggs //= 3
eggs = eggs // 2
%=
eggs %= 2
eggs = eggs % 2
**=
eggs **= 2
eggs = eggs ** 2
Relational/Comparison Operators
==
Equal to
!=
Not equal to
<
Less than
>
Greater than
<=
Less than or equal to
>=
Greater than or equal to
print(42 == 42) # -> True
print(42 == 42.0) # -> False
print('spam' == 'Spam') # -> False
print('spam' != 'Spam') # -> True
print(42 == '42') # -> False
In Python, you can "chain" conditions
n = 3
print(1 < n < 5) # -> True
Logical Operators
and
or
not
n = '3'
print(1 < n < 5) # -> TypeError
print(type(n) == 'int' and 1 < n < 5) # -> False
Last updated
Was this helpful?