FinishedTheBasics

This commit is contained in:
2024-09-13 15:12:25 +02:00
parent c931aee263
commit b4fa51980a
12 changed files with 510 additions and 0 deletions

View File

@ -0,0 +1,65 @@
#A very basic class would look something like this:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
#We'll explain why you have to include that "self" as a parameter a little bit later. First, to assign the above class(template) to an object you would do the following:
class MyClass2:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass2()
#To access a function inside of an object you use notation similar to accessing a variable:
myobjectx.function()
#To access the variable inside of the newly created object "myobjectx" you would do the following:
x = myobjectx.variable
print(x)
#The __init__() function, is a special function that is called when the class is being initiated. It's used for assigning values in a class.
class NumberHolder:
def __init__(self, number):
self.number = number
def returnNumber(self):
return self.number
var = NumberHolder(7)
print(var.returnNumber()) #Prints '7'
# Exercise
# We have a class defined for vehicles. Create two new vehicles called car1 and car2. Set car1 to be a red convertible worth $60,000.00 with a name of Fer, and car2 to be a blue van named Jump worth $10,000.00.
# define the Vehicle class
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
# your code goes here
car1 = Vehicle()
car1.name = "Fer"
car1.value = 60000.00
car1.kind = "convertible"
car1.color = "red"
car2 = Vehicle()
car2.name = "Jump"
car2.kind = "van"
car2.color = "blue"
car2.value = 10000.00
# test code
print(car1.description())
print(car2.description())

View File

@ -0,0 +1,49 @@
# A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.
# For example, a database of phone numbers could be stored using a dictionary like this:
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
#Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook)
#Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
#To remove a specified index, use either one of the following notations:
del phonebook["John"]
print(phonebook)
phonebook["John"] = 938477566 #To add it back in
#alternative solution:
phonebook.pop("John")
print(phonebook)
# Exercise
# Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# your code goes here
phonebook["Jake"] = 938273443
del phonebook["Jill"]
# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.")

View File

@ -0,0 +1,48 @@
# Modules in Python are just Python files with a .py extension. The name of the module is the same as the file name. A Python module can have a set of functions, classes, or variables defined and implemented. The example above includes two files:
# mygame/
# mygame/game.py
# mygame/draw.py
# The Python script game.py implements the game. It uses the function draw_game from the file draw.py, or in other words, the draw module that implements the logic for drawing the game on the screen.
# Modules are imported from other modules using the import command. In this example, the game.py script may look something like this:
# game.py
# import the draw module
import draw
def play_game():
pass
def main():
result = play_game()
draw.draw_game(result)
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main()
# A namespace is a system where every object is named and can be accessed in Python. We import the function draw_game into the main script's namespace by using the from command.
# game.py
# import the draw module
from draw import draw_game #To import all objects instead of "draw_game" write '*'
def main():
result = play_game()
draw_game(result)
# Exercise
# In this exercise, print an alphabetically sorted list of all the functions in the re module containing the word find.
import re
# Your code goes here
import re
# Your code goes here
find_members = []
for member in dir(re):
if "find" in member:
find_members.append(member)
print(sorted(find_members))

View File

@ -0,0 +1,47 @@
numbers = 1 + 1 + 2 * 3 / 4.0
print(numbers)
#Another operator available is the modulo (%) operator, which returns the integer remainder of the division. dividend % divisor = remainder.
remainder = 5 % 6
print(remainder)
#square
square = 6 ** 2
print(square)
helloworld = "hello" + " " + "world"
print(helloworld)
#Python also supports multiplying strings to form a string with a repeating sequence:
lotsofhellos = "hello" * 10
print(lotsofhellos)
#Lists can be joined with the addition operators:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
print([1,2,3] * 3)
# Exercise
# The target of this exercise is to create two lists called x_list and y_list, which contain 10 instances of the variables x and y, respectively. You are also required to create a list called big_list, which contains the variables x and y, 10 times each, by concatenating the two lists you have created.
x = object()
y = object()
# TODO: change this code
x_list = [x] * 10
y_list = [y] * 10
big_list = x_list + y_list
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")

View File

@ -0,0 +1,29 @@
#Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a greeting to that user.)
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
# Here are some basic argument specifiers you should know:
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
# %x/%X - Integers in hex representation (lowercase/uppercase)
# Exercise
# You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.
data = ("John", "Doe", 53.44)
format_string = "Hello"
print(format_string, "%s, %s, %f" % data)

View File

@ -0,0 +1,70 @@
#Strings are bits of text. They can be defined as anything between quotes:
astring = "Hello world!"
astring2 = 'Hello world!'
astring = "Hello world!"
print("single quotes are ' '")
print(len(astring))
print(f"Location of the letter 'o' in '{astring}':",astring.index("o")) #First instance of the letter o
print(f"Location of the letter 'l' in '{astring}':",astring.index("l"), "\n") #First instance of the letter o
print(f"Amount of letter 'l' in '{astring}':",astring.count("l")) #amount of letters
print(f"Amount of letter 'o' in '{astring}':",astring.count("o"), "\n") #amount of letters
#specified characters ofa string:
print(f"specific characters '[3:7]' in '{astring}':",astring[3:7])
print(f"specific characters '[3:7:2]' in '{astring}':",astring[3:7:2]) #This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].
print(f"specific characters '[::-1]' in '{astring}':",astring[::-1], "\n")
print(f"Capitalised version of '{astring}':",astring.upper())
print(f"Lowercase version of '{astring}':",astring.lower())
#true false values
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
#plitting the texts into a list
afewwords = astring.split(" ")
print(afewwords)
# Exercise
# Try to fix the code to print out the correct information by changing the string.
s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))

View File

@ -0,0 +1,78 @@
x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True
#The "and" and "or" boolean operators allow building complex boolean expressions, for example:
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
if name == "John" or name == "Rick":
print("Your name is either John or Rick.")
#The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:
name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")
#Here is an example for using Python's "if" statement using code blocks:
statement = False
another_statement = True
if statement is True:
# do something
pass
elif another_statement is True: # else if
# do something else
pass
else:
# do another thing
pass
x = 2
if x == 2:
print("x equals two!")
else:
print("x does not equal to two.")
#Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. For example:
x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False
#Using "not" before a boolean expression inverts it:
print(not False) # Prints out True
print((not False) == (False)) # Prints out False
# Exercise
# Change the variables in the first section, so that each if statement resolves as True.
# change this code
number = 16
second_number = False
first_array = [True, True, True]
second_array = [True,2]
if number > 15:
print("1")
if first_array:
print("2")
if len(second_array) == 2:
print("3")
if len(first_array) + len(second_array) == 5:
print("4")
if first_array and first_array[0] == 1:
print("5")
if not second_number:
print("6")

78
LearnTheBasics/8_Loops.py Normal file
View File

@ -0,0 +1,78 @@
#For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
# Prints out 3,4,5
for x in range(3, 6):
print(x)
# Prints out 3,5,7
for x in range(3, 8, 2):
print(x)
#While loops repeat as long as a certain boolean condition is met. For example:
# Prints out 0,1,2,3,4
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
#break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples:
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
#Unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If a break statement is executed inside the for loop then the "else" part is skipped. Note that the "else" part is executed even if there is a continue statement.
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")
# Exercise
# Loop through and print out all even numbers from the numbers list in the same order they are received. Don't print any numbers that come after 237 in the sequence.
numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,
743, 527
]
# your code goes here
for number in numbers:
if number == 237:
break
if number%2 == 0:
print(number)

View File

@ -0,0 +1,46 @@
#As we have seen on previous tutorials, Python makes use of blocks.
# A block is a area of code of written in the format of:
#Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
def my_function():
print("Hello From My Function!")
#Functions may also receive arguments (variables passed from the caller to the function). For example:
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
#Functions may return a value to the caller, using the keyword- 'return' . For example:
def sum_two_numbers(a, b):
return a + b
#Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
# print(a simple greeting)
my_function()
#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")
# after this line x will hold the value 3!
x = sum_two_numbers(1,2)
print(x)
# Exercise
# In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
# Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
# Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"
# Run and see all the functions work together!
# Modify this function to return a list of strings as defined above
def list_benefits():
return ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
return benefit + " is a benefit of functions!"
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()