Programming in Python - the basics

Date: 28/10/2020
Time: 09:30-11:30

Syntax in Python

Variables

Python does not require you to define the type of variables, just declare them
a = 2
  • Some keywords cannot be used for naming variables.
  • Can not start with a digit or contain a special symbol (|£$%@# etc.)
  • False | class | finally | is | return | None | continue | for | lambda | try | True | def | from | nonlocal | while | and | del | global | not | with | as | elif | if | or | yield | assert | else | import | pass | break | except | in | raise
    Python is case sensitive
    variable != Variable

    Some good practises for naming a variable:

  • Combine lowercase letters (a-z) uppercase letters (A-Z), digits (1-9) and underscore (_)
  • Use camelCase(thisIsMyVariable) or underscore to separate words (this_is_my_variable)
  • Use names that make sense count = 10 rather than c = 10
  • Punctuation and indentation

    You don't need to add punctuation at the end of lines.
    a = 2
    b = 3
    Use semicolons in case you want to put multiple statements in a single line
    a = 2 ; b = 3
    Use indentation to separate code blocks (use tabs or 4 whitespaces)
    a = 2
    if a > 1:
        print(a)
    Document your code using comments
    # a comment to describe the variable assignment
    a = 2
    # a comment to describe the if condition
    if a > 1:
        print(a)

    Data types

    Numbers

    # Integers
    a = int(5)

    # Floating point numbers
    a = float(5.0)

    # Complex numbers
    a = complex(5+2j)

    Strings

    s = "This is a string"
    s = str(25)

    Lists

    # This is a list
    myList = ['three', 'two', 'one']


    # To print the value 'two'
    print(myList[1])


    # To sort the list
    myList = sorted(myList)
    # Now myList = ['one', 'three', 'two']
    print(myList)


    # Add a new item to the list
    myList.append('star')
    # Now myList = ['one', 'three', 'two', 'star']
    print(myList)


    # Count how many elements we have in a list
    myList_length = len(myList)
    # the value of myList_length is 4
    print(myList_length)

    The Print command

    x = 5
    print(x)


    print("The value of x is ",x)


    print("The value of x is "+str(x))


    y = 2
    print("The value of x is {} and the value of y is {}".format(str(x),str(y)))

    Operators

    Arithmetic operators

    x = 5
    y = 2


    # + Add two operands or unary plus
    print(x+y)


    # - Subtract right operand from the left or unary minus
    print(x-y)


    # * Multiply two operands
    print(x*y)


    # / Divide left operand by the right one (always results into float)
    print(x/y)


    # % Modulus - remainder of the division of left operand by the right (remainder of x/y)
    print(x%y)


    # // Floor division - division that results into whole number adjusted to the left in the number line
    print(x//y)


    # ** Exponent - left operand raised to the power of right (x to the power y)
    print(x**y)

    Comparison operators

    x = 5
    y = 2


    # > Greater than - True if left operand is greater than the right
    print(x > y)


    # < Less than - True if left operand is less than the right
    print(x < y)


    # == Equal to - True if both operands are equal
    print(x == y)


    # != Not equal to - True if operands are not equal
    print(x != y)


    # >= Greater than or equal to - True if left operand is greater than or equal to the right
    print(x >= y)


    # <= Less than or equal to - True if left operand is less than or equal to the right
    print(x <= y)

    Logic operators

    x = True
    y = False


    # "and": True if both the operands are true
    print(x and y)


    # "or": True if either of the operands is true x or y
    print(x or y)


    # "not": True if operand is false (complements the operand)
    print(not x)

    Assignment operators

    # with "="
    x = 5
    print(x)


    # with "+="
    x += 5
    print(x)


    # with "-="
    x -= 2
    print(x)


    # Try with other arithmetic operands ...

    Membership operators

    my_list = [5,2,4,2]
    x = 4


    # "in": True if value/variable is found in the sequence
    print(x in my_list)


    # "not in": True if value/variable is not found in the sequence
    print(x not in my_list)


    Conditional statement

    A decision might be taken only when a specific condition is satisfied

    num = 3
    if num >= 0:
        print("Positive or Zero")
    else:
        print("Negative number")

    Functions

    A block of code which defines a specific algorithm and runs only when it is called.

    # def {func_name}({parameter_1}, {parameter_2}, ...)
    def add(num1, num2):
        return num1 + num2


    my_sum = add(5,4)
    print(my_sum)

    Exercises

    (check the exercises on the github repository)

    1st Exercise

    Define a function is_friend_of_harry() which returns a True value if a given name (String) is one of the friends of Harry Potter, otherwise the function must return False. Lets pretend the friends of Harry Potter are: "Ron", "Hermione", "Hagrid", and "Dumbledore".

    Example:
    Calling the function this way: is_friend_of_harry("Malfoy") should return a False value
    • a) Check if the following people are friends of Harry: "Hagrid", "Voldemort", and "Bellatrix". Print True/False for each check.
    Mark the box to see the solution
    def is_friend_of_harry(p_name):
        friends_list = ["Ron", "Hermione", "Hagrid", "Dumbledore"]
        if p_name in friends_list:
            return True
        else:
            return False

    print(is_friend_of_harry("Hagrid"))
    print(is_friend_of_harry("Voldemort"))
    print(is_friend_of_harry("Bellatrix"))
    • b) Print "Harry has a friend!" if at least one of the previous characters is friend of Harry, otherwise print "Harry has no friends!".
    Mark the box to see the solution
    a = is_friend_of_harry("Hagrid")
    b = is_friend_of_harry("Voldemort")
    c = is_friend_of_harry("Bellatrix")

    if a or b or c:
        print("Harry has a friend!")
    else:
        print("Harry has no friends!!")
    • c) Lets make our function is_friend_of_harry() a bit more powerful. Such that if I type a name in lowercase (e.g. "ron") or if I use spaces at the end of the name (e.g. "Ron "), or even if I do both the things, the function should work the same.
    Hint:
    On python {string}.lower() transforms a string to its lowercase form; {string}.strip() removes the starting and ending whitespaces (if any); and {string}.capitalize() capitalizes the first letter of a string
    Mark the box to see the solution
    def is_friend_of_harry(p_name):
        friends_list = ["Ron", "Hermione", "Hagrid", "Dumbledore"]
        p_name = p_name.lower()
        p_name = p_name.strip()
        p_name = p_name.capitalize()
        if p_name in friends_list:
            return True
        else:
            return False

    • d) Define another is_prof_friend_of_harry() which returns a True value if a given name is a professor and a friend of Harry, otherwise the function must return False. Lets pretend the professors of Harry Potter are: "Snape", "Lupin", "Hagrid", and "Dumbledore".
    Mark the box to see the solution
    def is_prof_friend_of_harry(p_name):
        prof_list = ["Snape", "Lupin", "Hagrid", "Dumbledore"]
        if p_name in prof_list:
            if is_friend_of_harry(p_name):
                return True
            else:
                return False
        else:
            return False

    print(is_friend_of_harry("Hagrid"))
    print(is_friend_of_harry("Voldemort"))
    print(is_friend_of_harry("Bellatrix"))

    2nd Exercise

    Each house of Hogwarts has a score which is updated based on actions such as performance in class and rule violations. Lets pretend we have a list of the houses houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"] and another list containing the score of each house scores = [0,0,0,0], such that the score value in position N of the scores list belongs to the house in position N of the houses list .

    • a) Define a update_house_score() function which increments/decrements the score of a specific house with a given points. The function takes three parameters: house_name, action (string value "positive"/"negative"), and points.
    Example:
    Calling the function this way: update_house_score("Gryffindor","positive",5) should increment the score of house Gryffindor by 5 points.

    Hint:
    The function {list}.index({value}) returns the index of an element in the list, e.g. houses.index("Hufflepuff") equals 1
    Mark the box to see the solution
    houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
    scores = [0,0,0,0]


    def update_house_score(house_name,action,points):
        index = houses.index(house_name)
        if action == "positive":
            scores[index] += points
        else:
            scores[index] -= points
    • b) After the Quidditch cup the Houses has incresed/decresed their scores as follow: +10 Gryffindor, +7 Hufflepuff, -3 Slytherin. After the game a member of house "Slytherin" made a good action and the house gained back 5 points. Update the houses points following these actions, and print the two lists.
    Mark the box to see the solution
    update_house_score("Gryffindor","positive",10)
    update_house_score("Hufflepuff","positive",7)
    update_house_score("Slytherin","negative",3)
    update_house_score("Slytherin","positive",5)
    print(houses)
    print(scores)