Introduction

Python is a high-level, object-orientated, interpreted, dynamically typed programming language. The syntax is simple to understand, making it a good language for beginners, as well as experienced professionals. The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python web site, https://www.python.org/, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.

Hello world!

To get started with writing Python, open the interpreter and write your first "Hello world" Python code:

print("Hello world!")

Run the code to see Hello world get printed to the output!

White space

Python does not contain any beginning or end block markers. Instead, blocks must be correctly indented (usually 4 spaces) to delineate them.

def function1():     print("Hi")
Variables

Python does not have types of variables. The values that are assigned to have different types, and variables can be assigned different types of values.

x = "hi" x = 90 x = True

The different types of values that a variable can be assigned are:

  • numbers
  • booleans
  • strings
  • ranges
  • tuples
  • lists
  • None
if-else statement

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false, or the elif clause to execute a statement if the condition is false but another is true. An if statement looks as follows:

cheese = "parmesan" if cheese == "mozzarella":     print("The classic Italian cheese.") elif cheese == "cheddar":     print("Orange or white? Sharp or mild?") else:     print("Your cheese is not in our list, please check later.")
for statement

A for statement executes its statements as many times as determined at time of execution. A for statement looks as follows:

for i in range(5):     print(i) for i in range(23, 32, 2):     print(i) for i in 'Greece':     print(i)
while statement

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while x < 10:     x += 3     print(x)
Exception handling

Here are the different keywords used in Python to deal with exceptions.

raise Exception('ErrorNotFound') raise NotImplentedError() try:     raise Exception('TooManyFries') except:     print("Exception found!") try:     raise Exception('Kaput') except ValueNotFound as v:     print('ValueNotFound:', v) finally:     print("Complete")
Functions

Functions can be defined with different names and inputs to be run inside of code. Here are two examples:

def Area(l, w):     return l*w def Fibonacci(x):     if x < 2 and x > -1         return x     return Fibonacci(x - 1) + Fibonacci(x - 2)
Reference