[Python] Basic Syntax

Language Feature

Compared to Java Same:

  1. Everything is an object design and excellent cross-platform support
  2. Relatively standard libraries
  3. Run on virtual machines, python does this automatically at runtime

Difference:

  1. Python is strongly dynamically typed. Make it very easy to write and not hard to read.
  2. A lot machine learning resources

Variables

Built-in Atomic Data Types int, float, bool.

Built-in Collection Data Types:

  • Ordered Collection: list, string, tuple

  • Integers in Python3 are unbounded

  • Unlike integers, floats are not infinite precision, and it’s convenient to refer to infinite as float('inf') and float('-inf')
  • Random methods random.randrange(28), random.randint(8,16), ranodm.random(), random.shuffle(A), random.choice(A)
  • Unordered Collection: set, dictionary

Exception Handler

1
2
3
4
5
6
7
8
9
try:
print(math.sqrt(anumber))
except:
print("Bad Value for square root")

if anumber < 0:
raise RuntimeError("You can't use a negative number") # Create more explicit error message
else:
print(math.sqrt(anumber))

all and any

all(): checks if all the values in that iterable are non-False
any(): checks if any of the values in that iterable are non-False

Usage:

1
2
3
4
5
6
7
8
9
"""
Check if list1 contains all elements in list2
"""
result = all(elem in list1 for elem in list2)

"""
Check if list1 contains any of the elements in list2
"""
result = any(elem in list1 for elem in list2)

Efficiency

  • list in python is much slower than set()
  • xrange takes less space than range, because xrange returns an object and range returns a list