Programming in Python - the basics
Date: 28/10/2020
Time: 09:30-11:30
Syntax in Python
Variables
Some good practises for naming a variable:
thisIsMyVariable
) or underscore to separate words (this_is_my_variable
)count = 10
rather than c = 10
Punctuation and indentation
b = 3
if a > 1:
print(a)
a = 2
# a comment to describe the if condition
if a > 1:
print(a)
Data types
Numbers
a = int(5)
# Floating point numbers
a = float(5.0)
# Complex numbers
a = complex(5+2j)
Strings
s = str(25)
Lists
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
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
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
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
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
x = 5
print(x)
# with "+="
x += 5
print(x)
# with "-="
x -= 2
print(x)
# Try with other arithmetic operands ...
Membership operators
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
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 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".
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.
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!".
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.
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
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".
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"), andpoints
.
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
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.
update_house_score("Hufflepuff","positive",7)
update_house_score("Slytherin","negative",3)
update_house_score("Slytherin","positive",5)
print(houses)
print(scores)