Python in one page
Published: 2023-06-23 12:34:24

### What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

To focus on the language itself this guide not includes any [built-in modules](https://docs.python.org/3/py-modindex.html) like `math`, `random`, `datetime`, `json`, `re`, `random`, etc
### Getting Started

### Coding
Make a simple hello world
```py
print('Hello, World!') # Hello, World!
```

### Help
```py
help(print)
# Prints the values to a stream, or to sys.stdout by default.
```

User Input
```py
name = input("Enter your name:")
print("Your name is: " + name)
```

Run a python file
`python helloworld.py`

### Comments

```py
#This is a comment
print('Hello, World!')
```
### Variables

```py
name = 'John'
age = 42

x, y, z = 1, 2, 3

print('Name: ' + name) # Name: John
```

### Data Types
```py
# Text
string = 'Hello World'

# Numeric
integer = 20
float = 20.5
complex = 1j

# Sequence
list = ['apple', 'banana', 'cherry']
tuple = ('apple', 'banana', 'cherry') # Unchangeable
range = range(6)

# Mapping
dictionary = {'name' : 'John', 'age' : 36}

# Set - No duplicate members
set_value = {"apple", "banana", "cherry"}
frozenset_value = frozenset({"apple", "banana", "cherry"})

# Boolean
boolean = True

# Binary
bytes = b"Hello"
bytearray = bytearray(5)
memoryview = memoryview(bytes(5))

print(type(string)) # <class 'str'>
print(int('1')) # constructs an integer number

# Represents a null value
x = None
print(x) # None
```

### Strings
```py
hello = 'Hello, World! '
print(hello[0]) # H
print(hello[-1]) # !
print(hello[2:5]) # llo
print(len(hello)) # '13' get string length
print(hello.strip()) # 'Hello, World!' removes whitespaces
print(hello.lower()) # hello, world!
print(hello.upper()) # HELLO, WORLD!
print(hello.replace("H", "A")) # Aello, World!
print(hello.split(",")) # ['Hello', ' World!']

# Membership Operators
print("Hello" in hello) # True
print("Hello" not in hello) # False

print('Hello, ' + 'World!') # Hello, World!
print("{0}, World!".format('Hello')) # Hello, World! 
```

### Arithmetic
```py
x, y = 1, 2
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x % y) # Modulus
print(x ** y) # Exponentiation
print(x // y) # Floor division

x += 3 # Same as x = x + 3
```

### Comparison
```py
x, y = 1, 2
print(x == y) # Equal
print(x != y) # Not equal
print(x > y) # Greater than
print(x < y) # Less than
print(x >= y) # Greater than or equal to
print(x <= y) # Less than or equal to

if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

# Assert is used when debugging code
assert x == 2 # AssertionError is raised
```

### Logical
```py
x = 2
print(x == 2 and x > 42) # True
print(x == 2 or x > 42) # True
print(not(True)) # False
print(not(False)) # True
```

### Identity
```py
x = 'Hello'
z = x
y = 'World'

print(x is z) # True
print(x is y) # False
print(x == y) # False
```

### Collections (Arrays)
```py
list = ['hello', 'world']
print(list)
print(list[1])
print(list[-1])
print(list[2:5])
print(list[:4])
print(list[2:])
list[1] = "!"
print(thislist)

for x in thislist:
  print(x)

if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

print(len(thislist))

list.append("orange") # Adds an element
list.clear() # Removes all the elements
mylist = list.copy() # Returns a copy of the list
list.count() # Number of elements
list.extend(['apple']) # Add the elements of a list
list.index() # Returns the index
list.insert(1, "orange") # Adds an element at 
# the specified position
thislist.pop() # Removes the element
thislist.remove("banana") # Removes the first item
list.reverse() # Reverses the order
list.sort() # Sorts the list
del thislist[0]

mylist = thislist.copy()
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
thislist = list(("apple", "banana", "cherry"))
```

### Sets
```py
thisset = {"apple", "banana", "cherry"}
thisset.add("orange") # Add an item
thisset.update(["orange", "mango"]) # Add multiple items
print(len(thisset))
thisset.remove("banana")
set3 = set1.union(set2)
set1.update(set2)
```

### Dictionaries
```py
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
print(thisdict)
thisdict["year"] = 2018

for x in thisdict.values():
  print(x)

for x, y in thisdict.items():
  print(x, y)

if "model" in thisdict:
  print("Yes")

thisdict["color"] = "red" # Adding an item
thisdict.pop("model") # Removes the item
thisdict.popitem()
```

### If ... Else
```py
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

# Short Hand
if a > b: print("a is greater than b")
print("A") if a > b else print("B")
```

### Loops
```py
# While
while i < 6:
  print(i)
  i += 1
  # break - can stop a loop
  # continue - continue with the next

# For
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

for x in range(6):
  print(x)

# Function continues execution immediately 
# after the last yield run
def number_generator(): 
    yield 1
    yield 2
  
for number in number_generator():  
    print(number)

# Output: 1 2
```

### Functions
```py
def my_function():
  print("Hello from a function")

my_function()

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
my_function(child1 = "Emil", 
            child2 = "Tobias", 
            child3 = "Linus")

# Default Parameter Value
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function()

def my_function(x):
  return 5 * x

print(my_function(3))
```
### Lambda
```py
# lambda arguments : expression
x = lambda a : a + 10
print(x(5))
```

### Classes and Objects
```py
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
p1.age = 40 # Modify Object Properties

# Inheritance
class Student(Person):
  pass # a statement that will do nothing

# Now the Student class has the same properties 
# and methods as the Person class
x = Student("Mike", "Olsen")
x.printname()
```

### Iterators
```py
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)

# Create an Iterator
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
```
### Scope
```py
# Global variable
def myfunction():
  global x = "hello"

myfunction()

print(x) # can be accessed outside the function

# Non Local Variable
def myfunc1():
  x = "John"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2()
  return x

print(myfunc1())
```

### Modules
Save this code in a file named `mymodule.py`
```py
def greeting(name):
  print("Hello, " + name)
```
```py
import mymodule
# import mymodule from greeting 
# (import specific parts of a module)

mymodule.greeting("Jonathan")

# Create an alias for mymodule called mx
import mymodule as mx

a = mx.greeting("Jonathan")
```

### Math
```py
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)

print(abs(-7.25))
print(pow(4, 3))
```

### Try Except
```py
try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")
```

### File Handling
```py
file = open("hello.txt", "r")
# r - Read
# a - Append
# w - Write
# x - Create

print(file.read())
print(file.readline())
file.close()

# Using with statement 
with open('hello.txt', 'w') as file: 
    file.write('hello world !')

# no need to call file.close() when using with
```

### All keywords
```py
import keyword
keyword.kwlist
[ 'False', 'None', 'True', 'and', 'as', 'assert',
 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'finally', 'for', 'from', 'global',
 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
 'with','yield' ]
```