Python

Python is a general-purpose, high-level programming language.It is used for a wide variety of applications, including web development, data science and machine learning.Here is Python cheatsheet for beginners.

#Getting Started

#About Python

#Python is a

  • high-level programming language, This makes it easy to learn and use.
  • object-oriented programming language
  • dynamically typed language, which means that the type of a variable is not checked at compile time.
  • interpreted language, which means that it is not compiled into machine code before it is executed. This makes it very portable and easy to debug
  • free and open source language,

#Variables

full_name = "John Doe"
age = 25
married = False

  • Python is a dynamically typed language, so you don't need to specify the type of the variable when you declare it. The type is inferred from the value you assign to it.
  • Variables are case sensitive, so age and Age are two different variables.
  • Variable names can only contain letters, numbers and underscores. They can't start with a number.
  • Variable names should be descriptive, so you can understand what they are used for.
  • Variable names should be in snake_case format, so each word is separated by an underscore.

#Data Types

str Text
int, float, complex Numeric
list, tuple, range Sequence
dict Mapping
set, frozenset Set
bool Boolean
bytes, bytearray, memoryview Binary
None NoneType

#Comments

  • Single-line comments in Python start with the hash symbol (#).
#single line comment.
  • Multi-line comments can be created by adding a multiline string (""" or ''') before and after the comment.
""" Multiline comment
"""

''' Multiline comment 2
'''

  • Comments should be written in plain English (or the language of the code's audience) and follow standard conventions for spelling, grammar, and punctuation.

  • Code should be organized into logical blocks with descriptive names and headers. Comments can be used to introduce and summarize these blocks.

  • Comments can also be used to temporarily disable lines of code during testing or debugging. However, this should be used sparingly and documented clearly.

  • The print() function takes one or more arguments, separated by commas. These can be strings or variables
print("Hello, World!")
Hello, World!

print("Hello", "World!")
Hello World!

print(x, y) # you can use one or more variables
  • You can change the separator between arguments using the sep keyword argument.
    print("Hello", "World!", sep=", ")
    Hello, World!
  • You can prevent the print() function from adding a newline character at the end using the end keyword argument.

        print("Hello, World!", end=" ")
        print("Hello, World!")
        Hello, World! Hello, World!
    
  • You can format the output using string formatting techniques, such as f-strings, format strings, or the % operator.

        name = "John"
        age = 25
        print(f"{name} is {age} years old.")
        John is 25 years old.
    
  • You can redirect the output of the print() function to a file using the file keyword argument.

    with open("output.txt", "w") as f:
        print("Hello, World!", file=f)

#Strings in Python

#Basic Strings

  • A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable.
string_1 = "string with double quotes"
string_2 = 'string with single quotes'

multi_string_1 = """Multiline Strings
can be written like this by 
wrapping inside three double quotes"""

multi_string_2 = '''Multiline Strings
can be written like this by
wrapping inside three single quotes'''

#String Concatenation

  • Strings can be concatenated (joined) with the + operator, and repeated with *.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe

print("Hello " * 5) # Hello Hello Hello Hello Hello

#String Methods

  • Strings have many built-in methods for manipulating them.
name = "john Doe"
print(name.upper()) # JOHN DOE
print(name.lower()) # john doe
print(name.title()) # John Doe # Make the first letter in each word upper case:
print(name.strip()) # John Doe # remove leading and trailing whitespaces
print(name.replace("Doe", "Smith")) # John Smith
print(name.split(" ")) # ["John", "Doe"]

#String Indexing

  • You can access individual characters in a string using indexing.
name = "John Doe"
print(name[0]) # J
print(name[1]) # o
print(name[-1]) # e
print(name[-2]) # o

#String Slicing

  • You can access a substring from a string using slicing.
name = "John Doe"
print(name[1:4]) # ohn
print(name[:4]) # John
print(name[5:]) # Doe
print(name[1:7:2]) # oh o
print(name[::-1]) # eoD nhoJ

#String Formatting

  • You can format strings using f-strings, format strings, or the % operator.
name = "John"
age = 25
print(f"{name} is {age} years old.") # John is 25 years old.
print("{} is {} years old.".format(name, age)) # John is 25 years old.
print("%s is %d years old." % (name, age)) # John is 25 years old.

#String Escape Sequences

  • You can use escape sequences to insert special characters in strings.
print("Hello\nWorld!") # Hello
                        # World!
print("Hello\tWorld!") # Hello   World!
print("\"Hello World!\"") # "Hello World!"
print("Hello\\World!") # Hello\World!

#String Encoding

  • Strings can be encoded using different character encodings such as ASCII, UTF-8, and UTF-16.
name = "John"
print(name.encode("ascii")) # b'John'
print(name.encode("utf-8")) # b'John'
print(name.encode("utf-16")) # b'\xff\xfeJ\x00o\x00h\x00n\x00'

#Python Numbers

#numbers

  • Python has three numeric types: int, float, and complex.
age = 25    # int
radius = 8.3  # float
rec = 8j   # complex

#convert

  • You can convert between numeric types using the int(), float(), and complex() methods.
age = 25    
print(float(age)) # 25.0
print(complex(age)) # (25+0j)

#addition

  • You can add two numbers using the + operator.
x = 5
y = 3
print(x + y) # 8

#subtraction

  • You can subtract two numbers using the - operator.
x = 5
y = 3
print(x - y) # 2

#multiplication

  • You can multiply two numbers using the * operator.
x = 5
y = 3
print(x * y) # 15

#division

  • You can divide two numbers using the / operator.
x = 5
y = 3
print(x / y) # 1.6666666666666667

#modulus

  • You can get the remainder of two numbers using the % operator.
x = 5
y = 3
print(x % y) # 2

#exponentiation

  • You can raise a number to the power of another number using the ** operator.
x = 5
y = 3
print(x ** y) # 125

#floor division

  • You can get the integer part of a division using the // operator.
x = 5
y = 3
print(x // y) # 1

#math

  • Python has a built-in module called math, which extends the list of mathematical functions.
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) # 5.0
print(math.pow(2, 3)) # 8.0
print(math.floor(2.9)) # 2
print(math.ceil(2.1)) # 3

#random

  • Python has a built-in module called random, which can be used to make random numbers.
import random
print(random.randrange(1, 10)) # 7
print(random.random()) # 0.4283688941880216
print(random.choice([1, 2, 3, 4])) # 3

#round

  • You can round a number using the round() method.
print(round(2.1)) # 2
print(round(2.9)) # 3

#abs

  • You can get the absolute value of a number using the abs() method.
print(abs(-2.9)) # 2.9

#complex

  • You can create a complex number using the complex() method.
print(complex(2, 3)) # (2+3j)

#max

  • You can get the largest number in a list using the max() method.
print(max([1, 2, 3, 4])) # 4

#min

  • You can get the smallest number in a list using the min() method.
print(min([1, 2, 3, 4])) # 1

#sum

  • You can get the sum of all numbers in a list using the sum() method.
print(sum([1, 2, 3, 4])) # 10

#Booleans in Python

#booleans

  • Booleans represent one of two values: True or False.
x = True
y = False

#is

  • You can use the is keyword to check if two variables are the same object.
x = ["apple", "banana", "cherry"]
y = ["apple", "banana", "cherry"]
z = x
print(x is z) # True
print(x is y) # False
print(x == y) # True

#not

  • You can use the not keyword to invert a boolean.
print(not True) # False
print(not False) # True

#and

  • You can use the and keyword to combine two booleans.
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False

#or

  • You can use the or keyword to combine two booleans.
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False

#bool

  • You can convert a value to a boolean using the bool() method.
print(bool("Hello")) # True
print(bool(15)) # True
print(bool(["apple", "banana", "cherry"])) # True
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False 0 is always false
print(bool("")) # False empty string is always false
print(bool(())) # False empty tuple is always false
print(bool([])) # False empty list is always false
print(bool({})) # False empty dictionary is always false

#Lists in Python

#lists

  • Lists are used to store multiple items in a single variable.
fruits = ["apple", "banana", "cherry"]
  • You can also use the list() method to create a list.
fruits = list(("apple", "banana", "cherry"))

#access items

  • You can access items in a list by referring to the index number.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry

#negative indexing

  • You can access items in reverser order by referring to the negative index numbers.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
print(fruits[-3]) # apple

#range of indexes

  • You can specify a range of indexes by specifying where to start and where to end the range.
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5]) # ['cherry', 'orange', 'kiwi']
print(fruits[:4]) # ['apple', 'banana', 'cherry', 'orange']
print(fruits[2:]) # ['cherry', 'orange', 'kiwi', 'melon', 'mango']
print(fruits[-4:-1]) # ['orange', 'kiwi', 'melon']

#change item value

  • You can change the value of a specific item by referring to its index number.
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
print(fruits) # ['kiwi', 'banana', 'cherry']

#loop lists

  • You can loop through a list using a for loop.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

#check if item exists

  • You can check if an item exists in a list by using the in keyword.
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
  print("Yes, 'apple' is in the fruits list")

#list length

  • You can get the length of a list by using the len() method.
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3

#add items

  • You can add an item to the end of a list by using the append() method.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']

#insert items

  • You can insert an item into a list by specifying where to insert it.
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']

#remove items by value

  • You can remove an item from a list by referring to its value.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry']

#remove items by index

  • You can remove an item from a list by referring to its index number.
fruits = ["apple", "banana", "cherry"]
del fruits[0]
print(fruits) # ['banana', 'cherry']

#pop items by index

  • You can seperate an item from a list by referring to its index number.
fruits = ["apple", "banana", "cherry"]
seperated_fruit = fruits.pop(1)
print(fruits) # ['apple', 'cherry']
print(seperated_fruit) # banana

#delete list

  • You can delete a list by using the del keyword.
fruits = ["apple", "banana", "cherry"]
del fruits
print(fruits) # NameError: name 'fruits' is not defined

#clear items

  • You can empty a list by using the clear() method.
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits) # []

#copy a list

  • You can copy a list by using the copy() method.
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x) # ['apple', 'banana', 'cherry']

#join lists

  • You can join two lists by using the + operator.
fruits = ["apple", "banana", "cherry"]
cars = ["Ford", "BMW", "Volvo"]
x = fruits + cars
print(x) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

#join lists (extend())

  • You can use the extend() method to add the elements of one list to another list.
fruits = ["apple", "banana", "cherry"]
cars = ["Ford", "BMW", "Volvo"]
fruits.extend(cars)
print(fruits) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

#count()

  • The count() method returns the number of elements with the specified value.
fruits = ["apple", "banana", "cherry", "mango", "cherry"]
x = fruits.count("cherry")
print(x) # 2

#index()

  • The index() method returns the position at the first occurrence of the specified value.
fruits = ["apple", "banana", "cherry", "mango", "cherry"]
x = fruits.index("cherry")
print(x) # 2

#list comprehension

  • List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
newlist = [expression for item in iterable if condition == True]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist) # ['apple', 'banana', 'mango']

#reverse()

  • The reverse() method reverses the sorting order of the elements.
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']

#sort()

  • The sort() method sorts the list ascending by default.
fruits = ["apple", "banana", "cherry"]
fruits.sort()
print(fruits) # ['apple', 'banana', 'cherry']
  • The sort() method takes a reverse parameter.
fruits = ["apple", "banana", "cherry"]
fruits.sort(reverse = True)
print(fruits) # ['cherry', 'banana', 'apple']
  • The sort() method takes a key parameter.
def myFunc(e):
  return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars) # ['VW', 'BMW', 'Ford', 'Mitsubishi']
  • By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars) # ['BMW', 'Ford', 'Volvo']

#Tuples in Python

#Intorduction

  • A tuple is a collection which is ordered and unchangeable.

  • In Python tuples are written with round brackets.

  • Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

  • Tuples are used to store multiple items in a single variable. `

#create tuple

fruits = ("apple", "banana", "cherry")
print(fruits) # ('apple', 'banana', 'cherry')
  • It is also possible to use the tuple() constructor to make a tuple.
fruits = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(fruits) # ('apple', 'banana', 'cherry')

#access tuple items

  • You can access tuple items by referring to the index number, inside square brackets.
fruits = ("apple", "banana", "cherry")
print(fruits[1]) # banana

#range of indexes

  • You can specify a range of indexes by specifying where to start and where to end the range.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(fruits[2:5]) # ('cherry', 'orange', 'kiwi')

#negative indexing

  • Negative indexing means start from the end.
fruits = ("apple", "banana", "cherry")
print(fruits[-1]) # cherry

#range of negative indexes

  • Specify negative indexes if you want to start the search from the end of the tuple.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(fruits[-4:-1]) # ('orange', 'kiwi', 'melon')

#tuple length

  • To determine how many items a tuple has, use the len() method.
fruits = ("apple", "banana", "cherry")
print(len(fruits)) # 3

#check if item exists

  • To determine if a specified item is present in a tuple use the in keyword.
fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
  print("Yes, 'apple' is in the fruits tuple") # Yes, 'apple' is in the fruits tuple

#remove items

  • You cannot remove items in a tuple.

#add items

  • Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
fruits = ("apple", "banana", "cherry")
fruits[3] = "orange" # TypeError: 'tuple' object does not support item assignment

#join tuples

  • To join two or more tuples you can use the + operator.
fruits = ("apple", "banana", "cherry","mango")
vegetables = ("carrots","tomato","potato")
mytuple = fruits + vegetables
print(mytuple) # ('apple', 'banana', 'cherry', 'mango', 'carrots', 'tomato', 'potato')

#Sets in Python

#Intoduction

  • Sets cannot have two items with the same value.

  • A set is a collection which is unordered and unindexed.

  • In Python sets are written with curly brackets.

  • Sets are unordered, so you cannot be sure in which order the items will appear.

  • Sets are unchangeable, meaning that we cannot change the items after the set has been created.

  • Set items can be of any data type.

  • sets are mutable

#set

fruits = {"apple", "banana", "cherry", "apple", "banana"}
print(fruits) # {'cherry', 'apple', 'banana'}

#access items

  • You cannot access items in a set by referring to an index, since sets are unordered the items has no index.

#add items

  • To add one item to a set use the add() method.
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits) # {'cherry', 'apple', 'banana', 'orange'}

#clear set

  • The clear() method empties the set.
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits) # set()

#add sets

  • To add items from another set into the current set, use the update() method.
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
fruits.update(more_fruits)
print(fruits) # {'cherry', 'apple', 'banana', 'orange', 'mango', 'grapes'}

#remove item

  • To remove an item in a set, use the remove(), or the discard() method.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # {'cherry', 'apple'}

#delete set

  • The del keyword will delete the set completely.
fruits = {"apple", "banana", "cherry"}
del fruits
print(fruits) # NameError: name 'fruits' is not defined

#remove last item

  • The pop() method removes the last item.
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits) # {'apple', 'banana'}

#Dictionaries in Python

#Introduction

  • A dictionary is a collection of key-value pairs, where each key is unique and associated with a value.

  • Dictionaries are written with curly brackets, and have keys and values.

  • Dictionaries are unordered, so you cannot be sure in which order the items will appear.

  • Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

  • Dictionaries cannot have two items with the same key.

  • Dictionaries can be of any data type (int, float, string, boolean, list, tuple, None, etc.).

  • Dictionaries are mutable

#Dictionary

empty_dict = {}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
book_ino = {"name": "limitless", "price": 1.54, "ISBN": "16161IJ"}

#dictionary constructor

  • It is also possible to use the dict() constructor to make a new dictionary.
school_marks = dict(name="John", age=18, marks=90)
print(school_marks) # {'name': 'John', 'age': 18, 'marks': 90}

#access items

  • You can access the items of a dictionary by referring to its key name, inside square brackets.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(school_marks["maths"]) # 72

#get method

  • There is also a method called get() that will give you the same result.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(school_marks.get("maths")) # 72

#change values

  • You can change the value of a specific item by referring to its key name.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks["maths"] = 90
print(school_marks) # {'maths': 90, 'chemistry': 65, 'physics': 68}

#loop through a dictionary

  • You can loop through a dictionary by using a for loop.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
for key, value in school_marks.items():
    print(key) # maths chemistry physics

#check if key exists

  • To determine if a specified key is present in a dictionary use the in keyword.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
if "maths" in school_marks:
    print("yes") # yes

#dictionary length

  • To determine how many items (key-value pairs) a dictionary has, use the len() method.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(len(school_marks)) # 3

#add items

  • Adding an item to the dictionary is done by using a new index key and assigning a value to it.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks["english"] = 70
print(school_marks) # {'maths': 72, 'chemistry': 65, 'physics': 68, 'english': 70}

#remove items

  • The pop() method removes the item with the specified key name.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
maths = school_marks.pop("maths")
print(school_marks) # {'chemistry': 65, 'physics': 68}
print(maths) # 72

#remove last item

  • The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead).
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks.popitem()
print(school_marks) # {'maths': 72, 'chemistry': 65}

#delete item

  • The del keyword removes the item with the specified key name.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
del school_marks["maths"]
print(school_marks) # {'chemistry': 65, 'physics': 68}

#delete dictionary

  • The del keyword can also delete the dictionary completely.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
del school_marks
print(school_marks) # NameError: name 'school_marks' is not defined

#clear dictionary

  • The clear() keyword empties the dictionary.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks.clear()
print(school_marks) # {}

#copy dictionary

  • You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks_copy = school_marks.copy()
print(school_marks_copy) # {'maths': 72, 'chemistry': 65, 'physics': 68}

#nested dictionaries

  • A dictionary can also contain many dictionaries, this is called nested dictionaries.
school_marks = {
    "student1": {
        "name": "John",
        "age": 18,
        "marks": 90
    },
    "student2": {
        "name": "Jane",
        "age": 17,
        "marks": 80
    }
}
print(school_marks) # {'student1': {'name': 'John', 'age': 18, 'marks': 90}, 'student2': {'name': 'Jane', 'age': 17, 'marks': 80}}

#Operators in Python

#Inroduction

  • Operators are used to perform operations on variables and values.
  • Python divides the operators in the following groups:
    • Arithmetic operators
    • Assignment operators
    • Comparison operators
    • Logical operators
    • Identity operators
    • Membership operators
    • Bitwise operators

#assignment operators

  • Assignment operators are used to assign values to variables.
x = 5
x += 3 # x = x + 3
x -= 3 # x = x - 3
x *= 3 # x = x * 3
x /= 3 # x = x / 3
x %= 3 # x = x % 3
x //= 3 # x = x // 3
x **= 3 # x = x ** 3

#comparison operators

  • Comparison operators are used to compare two values.
x = 5
y = 3
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False

#logical operators

  • Logical operators are used to combine conditional statements.
x = 5
print(x > 3 and x < 10) # True
print(x > 3 or x < 4) # True
print(not(x > 3 and x < 10)) # False

#identity operators

  • Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True
print(x is y) # False
print(x == y) # True
print(x is not z) # False
print(x is not y) # True

#membership operators

  • Membership operators are used to test if a sequence is presented in an object.
x = ["apple", "banana"]
print("banana" in x) # True
print("pineapple" not in x) # True

#bitwise operators

  • Bitwise operators are used to compare (binary) numbers.
x = 5
y = 3
print(x & y) # 1
print(x | y) # 7
print(x ^ y) # 6
print(x >> 2) # 1
print(x << 2) # 20

#Python If Else

#basic if else

if condition:
    # do something
else:
    # do something else

#if elif else

if condition:
    # do something
elif condition:
    # do something else
else:
    # do something else

#Ternary operator

if_true if condition else if_false
print("cheap") if price <50 else print("expensive")

#nested if else

if condition1:
    if condition2:
        # Code to execute if both condition1 and condition2 are True
    else:
        # Code to execute if condition1 is True and condition2 is False
else:
    # Code to execute if condition1 is False

#Ternary operator

if_true if condition else if_false
print("cheap") if price <50 else print("expensive")

#multiple conditions

if condition1 and condition2 and condition3:
    # do something
if condition1 or condition2 or condition3:
    # do something
if condition1 and condition2 or condition3:
    # do something

#Python Loops

#for loop

for i in range(10):
    print(i)

#while loop

i = 0
while i < 10:
    print(i)
    i += 1

#nested loops

for i in range(10):
    for j in range(10):
        print(i, j)

#break

  • break: used to exit a loop prematurely when a certain condition is met.
for i in range(10):
    if i == 5:
        break
    print(i)

#continue

  • continue: used to skip the current iteration of a loop when a certain condition is met, but the loop will continue iterating until all the elements in the sequence have been iterated.
for i in range(10):
    if i == 5:
        continue
    print(i)

#else

  • else: used to execute a block of code when the condition of a loop is false.
for i in range(10):
    print(i)
else:
    print("Done")

#pass

  • pass: used to do nothing when a certain condition is met.
for i in range(10):
    if i == 5:
        pass
    print(i)

#Functions in Python

#Introduction

  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.

#Creating a Function

  • In Python a function is defined using the def keyword:
def my_function():
    print("Hello from a function")

#Calling a Function

  • To call a function, use the function name followed by parenthesis:
def my_function():
    print("Hello from a function")

my_function()

#Arguments

  • Information can be passed into functions as arguments.
  • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
    print(fname + " Refsnes")

my_function("Emil")

#lambda function

  • A lambda function is a small anonymous function.
  • A lambda function can take any number of arguments, but can only have one expression.
x = lambda a : a + 10
print(x(5))

#return statement

  • To let a function return a value, use the return statement:
def my_function(x):
    return 5 * x

print(my_function(3))

#Files in Python

#Introduction

  • The key function for working with files in Python is the open() function.
  • The open() function takes two parameters; filename, and mode.
  • There are four different methods (modes) for opening a file:
    • "r" - Read - Default value. Opens a file for reading, error if the file does not exist
    • "a" - Append - Opens a file for appending, creates the file if it does not exist
    • "w" - Write - Opens a file for writing, creates the file if it does not exist
    • "x" - Create - Creates the specified file, returns an error if the file exists

#Read Only Parts of the File

  • By default the read() method returns the whole text, but you can also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))

#Read Lines

  • You can return one line by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline())
  • By calling readline() two times, you can read the two first lines:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
  • By looping through the lines of the file, you can read the whole file, line by line:
f = open("demofile.txt", "r")
for x in f:
  print(x)

#Close Files

  • It is a good practice to always close the file when you are done with it.
f = open("demofile.txt", "r")
print(f.readline())
f.close()

#Write to an Existing File

  • To write to an existing file, you must add a parameter to the open() function:
    • "a" - Append - will append to the end of the file
    • "w" - Write - will overwrite any existing content
f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read())

#Create a New File

  • To create a new file in Python, use the open() method, with one of the following parameters:
    • "x" - Create - will create a file, returns an error if the file exist
    • "a" - Append - will create a file if the specified file does not exist
    • "w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", "x")

#Delete a File

  • To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")

#Check if File exist:

  • To avoid getting an error, you might want to check if the file exists before you try to delete it:
import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

#Delete Folder

  • To delete an entire folder, use the os.rmdir() method:
import os
os.rmdir("myfolder")

#with context manager

  • It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
with open('workfile') as f:
    read_data = f.read()

#Exception Handling

#Introduction

  • When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

  • There are several types of exceptions in Python. Common ones are:

    • ImportError: an import fails;
    • IndexError: a list is indexed with an out-of-range number;
    • NameError: an unknown variable is used;
    • SyntaxError: the code can't be parsed properly;
    • TypeError: a function is called on a value of an inappropriate type;
    • ValueError: a function is called on a value of the correct type, but with an inappropriate value.
  • full exception list (docs.python.org)

#The try and except Block:

try:
    print(x)
except:
    print("An exception occurred")

#Many Exceptions

try:
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

#Else

try:
    print("Hello")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")

#Finally

try:
    print(x)
except:
    print("Something went wrong")
finally:
    print("The 'try except' is finished")

#Raise an exception

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

#with context

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)