You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

337 lines
11 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# [SECTION] Lists
# Lists are similar to arrays in JavaScript in the sense that they can contain a collection of data.
# To create a list, square brackets ([]) are used.
names = ["John", "Paul", "George", "Ringo"] # String list
programs = ['developer career', 'pi-shape', 'tech career package']
durations = [260, 180, 20] # Number list
truth_values = [True, False, True, True, False] # Boolean list
# A list can contain elements of different data types:
sample_list = ["Apple", 3, False, "Potato", 4, True]
# Problems may arise if you try to use lists with multiple types for something that expects them to be all the same type.
# Problems may arise if you try to use lists with multiple types for something that expects them to be all the same type.
print("Lists:")
# Getting list size
# The number of elements in a list can be counted using the len() function.
print(len(programs))
# Result: 3
# Accessing values in lists
# List elements can be accessed by providing their index number.
# Indexing in lists starts at 0 and goes up to n - 1, where n is the number of elements.
print(names[0])
# Result: John
# Accessing the last item in the lists
print(names[-1])
# Result: Ringo
# Accesing the whole list
print(durations)
# Result: [260, 180, 20]
# Accessing a range of values
# SYNTAX: list[start index : end index]
print(programs[0:2])
# Result: ['developer career', 'pi-shape']
# Mini Exercise 1:
# Create a list of names of 5 students
# Create a list of grades for the 5 students
# Use a loop to iterate through the lists, printing in the following format: "The grade of <student> is <grade>".
# Solution:
students = ["Mary", "Matthew", "Tom", "Anna", "Thomas"]
grades = [100, 85, 88, 90, 75]
count = 0
while count < len(students):
print(f"The grade of {students[count]} is {grades[count]}")
count += 1
# Result:
# The grade of Mary is 100
# The grade of Matthew is 85
# The grade of Tom is 88
# The grade of Anna is 90
# The grade of Thomas is 75
# Updating List Elements
# Print the current value
print(f'Current value: {programs[2]}')
# Result: Current value: tech career package
# Update the value
programs[2] = 'short courses'
# Print the new value
print(f'New value: {programs[2]}')
# Result: New value: short courses
# [SECTION] List Manipulation
# Lists have methods that can be used to manipulate their elements.
# Adding list items the append() method allows you to insert items at the end of the list.
programs.append('global')
print(programs)
# Result: ['developer career', 'pi-shape', 'Short Courses', 'global']
# Deleting list items the "del" keyword can be used to delete elements from the list.
# Add a new item to the durations list
durations.append(360)
print(durations)
# Result: [260, 180, 20, 360]
# Delete the last item on the list
del durations[-1]
print(durations)
# Result: [260, 180, 20]
# Membership Checks The "in" keyword checks if an element is in the list and returns True or False.
print(20 in durations)
# Result: True
print(500 in durations)
# Result: False
# Sorting lists - the sort() method sorts the list alphanumerically, ascending, by default.
names.sort()
print(names)
# Result: ['George', 'John', 'Paul', 'Ringo']
# Emptying the list - the clear() method is used to empty the contents of the list.
test_list = [1, 3, 5, 7, 9]
print(test_list)
test_list.clear()
print(test_list)
# Result: []
# [SECTION] Dictionaries
# Dictionaries are used to store data values in key:value pairs. This is similar to objects in JavaScript.
# A dictionary is a collection that is ordered, changeable, and does not allow duplicates.
# Ordered means that the items have a defined order, and that order will not change.
# Changeable means that values can be modified.
# To create a dictionary, curly braces ({}) are used, and key-value pairs are written as key: value.
print("Dictionaries:")
person1 = {
"name" : "Brandon",
"age" : 28,
"occupation" : "student",
"is_enrolled" : True,
"subjects" : ["Python", "SQL", "Django"]
}
# To get the number of key-pairs in the dictionary, the len() method can be used.
print(len(person1))
# Result: 5
# To get a value from the dictionary, you can refer to its key using square brackets ([]).
print(person1["name"])
# Result: Brandon
# The keys() method returns a view object containing all the keys in the dictionary.
print(person1.keys())
# Result: dict_keys(['name', 'age', 'occupation', 'is_enrolled', 'subjects'])
# The values() method returns a view object containing all the values in the dictionary.
print(person1.values())
# Result: dict_values(['Brandon', 28, 'student', True, ['Python', 'SQL', 'Django']])
# The items() method returns each item in the dictionary as key-value pairs in a view object.
print(person1.items())
# Result: dict_items([('name', 'Brandon'), ('age', 28), ('occupation', 'student'), ('is_enrolled', True), ('subjects', ['Python', 'SQL', 'Django'])])
# Adding key-value pairs can be done either by assigning a new key using square brackets, or by using the update() method.
# Using new index
person1["nationality"] = "Filipino"
print(person1)
# Result: {'name': 'Brandon', 'age': 28, 'occupation': 'student', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django'], 'nationality': 'Filipino'}
# Using update() method
person1.update({"fav_food" : "Sinigang"})
print(person1)
# Result: {'name': 'Brandon', 'age': 28, 'occupation': 'student', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django'], 'nationality': 'Filipino', 'fav_food': 'Sinigang'}
# Deleting entries can be done using the pop() method or the del keyword
# Using pop() method
person1.pop("fav_food")
print(person1)
# Result: {'name': 'Brandon', 'age': 28, 'occupation': 'student', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django'], 'nationality': 'Filipino'}
# Using del keyword
del person1["nationality"]
print(person1)
# Result: {'name': 'Brandon', 'age': 28, 'occupation': 'student', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django']}
# Emptying the Dictionary
person2 = {
"name" : "John",
"age" : 18
}
print(person2)
# Result: {'name': 'John', 'age': 18}
# The clear() method empties the dictionary
person2.clear()
print(person2)
# Result: {}
# Looping through dictionaries
print("Looping through dictionaries:")
for key in person1:
print(f"The value of {key} is {person1[key]}")
# Result:
# The value of name is Brandon
# The value of age is 28
# The value of occupation is student
# The value of is_enrolled is True
# The value of subjects is ['Python', 'SQL', 'Django']
# Nested dictionaries - dictionaries can be nested inside each other
person3 = {
"name": "Monika",
"age": 20,
"occupation": "poet",
"is_enrolled": True,
"subjects": ["Python", "SQL", "Django"]
}
classroom = {
"student1" : person1,
"student2" : person3
}
print(classroom)
# Result: {'student1': {'name': 'Brandon', 'age': 28, 'occupation': 'student', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django']}, 'student2': {'name': 'Monika', 'age': 20, 'occupation': 'poet', 'is_enrolled': True, 'subjects': ['Python', 'SQL', 'Django']}}
# [SECTION] Functions
# Functions are blocks of code that run when called.
# The "def" keyword is used to create a function.
# SYNTAX: def function_name():
def my_greeting():
# Code to be run when my_greeting is called
print('Hello User!')
print("Functions:")
# Calling/invoking a function
my_greeting()
# Result: Hello User!
# Parameters in functions allow you to specify what inputs the function expects and provide more control over how the function behaves.
def greet_user(username):
# prints out the value of the username parameter
print(f'Hello, {username}!')
# Arguments are the actual values that are passed into the function when it is called.
greet_user("Bob")
# Result: Hello, Bob!
greet_user("Amy")
# Result: Hello, Amy!
# The "return" keyword allows a function to return values.
def addition(num1, num2):
return num1 + num2
sum = addition(5, 10)
print(f"The sum is {sum}")
# Result: The sum is 15
# A lambda function is a small, anonymous function that can be used for callbacks or short, throwaway operations.
# It works like any regular Python function, but it has no name and is defined using a single line of code.
# A lambda function can take any number of arguments but can only contain one expression.
greeting = lambda person : f'Hello {person}!'
print(greeting("Jane"))
# Result: Hello Jane!
multiplication = lambda a, b : a * b
print(multiplication(3, 5))
# Result: 15
# Mini Exercise 2:
# Create a function that returns the square of a number.
# Use 5 as argument, result should be 25.
# Print "The square is {result}."
# Solution:
def sqr(num):
return num * num # or return num ** 2
result = sqr(5)
print(f"The square is {result}.")
# Result: The square is 25.
# [SECTION] Classes
# Classes serve as blueprints that describe the concept of objects.
# Each object has characteristics (called properties) and behaviors (called methods).
# Imagine the concept of a car: a car has a brand, model, and year of make, and it can drive, brake, and turn.
# To create a class, use the "class" keyword followed by a class name that starts with an uppercase letter.
# SYNTAX: class ClassName():
class Car():
# The properties that all Car objects must have are defined in a method called __init__.
# Any number of parameters can be passed to __init__(), but the first parameter should always be self.
# self refers to the current instance of the class
# When a Car instance is created, that instance is automatically passed to the self parameter.
def __init__(self, brand, model, year_of_make):
self.brand = brand
self.model = model
self.year_of_make = year_of_make
# Other properties can be added and assigned hard-coded values.
self.fuel = "Gasoline"
self.fuel_level = 0
# Methods are functions defined inside a class.
# Method to simulate filling the fuel tank
def fill_fuel(self):
print(f'Current fuel level: {self.fuel_level}')
print('filling up the fuel tank...')
self.fuel_level = 100
print(f'New fuel level: {self.fuel_level}')
# Mini Exercise solution
def drive(self, distance):
print(f"The car has driven {distance} kilometers")
print(f"The fuel level left: {self.fuel_level - distance}")
# Creating a new instance is done by calling the class and providing the required arguments
new_car = Car("Nissan", "GT-R", "2019")
print("Classes:")
# Displaying attributes can be done using dot notation
print(f"My car is a {new_car.brand} {new_car.model}")
# Result: My car is a Nissan GT-R
# Calling methods on the instance
new_car.fill_fuel()
# Result:
# Current fuel level: 0
# filling up the fuel tank...
# New fuel level: 100
# Mini Exercise solution
new_car.drive(50)
# Result:
# The car has driven 50 kilometers
# The fuel level left: 50