diff --git a/python/functions b/python/functions new file mode 100644 index 0000000..3d5a666 --- /dev/null +++ b/python/functions @@ -0,0 +1,16 @@ +#the def keyword is used to make a function in python. +#code that is part of the function needs to be indented four spaces + +def first_hello(): + name = str(input("What is your name? ")) + print("Hello {}".format(name)) + +#functions can take arguments as well. +def second_hello(name): + print("Hello {}".format(name)) + +#to call a function simply simply type the name of the function +#followed by its parameter(s) (if it takes any). + +first_hello() +second_hello("Samuel") # since we have to pass a string for the name argument diff --git a/python/loops b/python/loops new file mode 100644 index 0000000..e33c4b8 --- /dev/null +++ b/python/loops @@ -0,0 +1,23 @@ +#loops are used to repeat parts of your code. +#There are two main ways to loop in Python, +#Using a FOR loop and a WHILE loop + +#a for loop is written like this, the spaces are mandatory +for i in range(1,10): + print(i) + +#make sure to add a comma in between your numbers and a colon at the end of the initial line. +#the range function is exclusive therefore the output would be numbers 1 through 9 not including 10. + +#a while loop is written as follows +x = 10 +y = 0 +while x > y: # once again, indentation is required + print("while loop example") + y += 1 #this iterates variable y every time the loop is runned (same as writing y = y + 1) + +#the result would be outputting "while loop example" ten times, +#until x is no longer greater than y + +#be sure to familiarize yourself with the BREAK and CONTINUE statements as well, +#as they are vital for mastering python's loop control flow. diff --git a/python/objects b/python/objects new file mode 100644 index 0000000..666fea0 --- /dev/null +++ b/python/objects @@ -0,0 +1,31 @@ +#Everything in python is considered an object. +#To create your own objects you first need to create a class +#which can be done as follows. Remember to indent! + +class Fruit: # class names should always be capitalized + bio = "fruit" # this is a class attribute + + def ready(self, color): # All methods in a class need the self argument + self.color = color + if self.color == "green": + return "The fruit is ripe." + else: + return "The fruit isn't ready yet" + +class Watermelon(Fruit): # The new class inherits everything from the Fruit class + bio = "watermelon" # overwrite the bio attribute for the watermelon class + +#To make objects simply assign the class to a variable. + +fruit = Fruit() +watermelon = Watermelon() + +#Access object attributes as follows + +print(fruit.bio) # prints out "fruit" +print(watermelon.bio) # prints out "watermelon" + +#To call object methods do + +print(watermelon.ready("green")) # should print out "The fruit is ripe". + # remember Watermelon inherited the ready method from Fruit.