Python Basics
Python Basics
Math Operators
From Highest to Lowest precedence:
** Exponent 2 ** 3 = 8
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
Examples of expressions:
>>> 2 + 3 * 6
# 20
>>> (2 + 3) * 6
# 30
>>> 2 ** 8
#256
>>> 23 // 7
# 3
>>> 23 % 7
# 2
>>> number = 1
>>> number += 1
>>> number
# 2
Data Types
Data Type Examples
String Replication:
>>> 'Alice' * 5
# 'AliceAliceAliceAliceAlice'
Variables
You can name a variable anything as long as it obeys the following rules:
>>> # bad
>>> my variable = 'Hello'
>>> # good
>>> var = 'Hello'
>>> # good
>>> my_var = 'Hello'
>>> # good
>>> my_var_2 = 'Hello'
Comments
Inline comment:
# This is a comment
Multiline comment:
# This is a
# multiline comment
a = 1 # initialization
Function docstring:
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""
>>> a = 1
>>> print('Hello world!', a)
# Hello world! 1
>>> len('hello')
# 5
>>> len(['cat', 3, 'dog'])
# 3
>>> a = [1, 2, 3]
# bad
>>> if len(a) > 0: # evaluates to True
... print("the list is not empty!")
...
# the list is not empty!
# good
>>> if a: # evaluates to True
... print("the list is not empty!")
...
# the list is not empty!
>>> str(29)
# '29'
>>> str(-3.14)
# '-3.14'
>>> int('11')
# 11
>>> float('3.14')
# 3.14