1.Functions
-We use keyword 'def' to define our functions.
-Our functions can receive arguments from the caller.
-Our functions can return a value to the caller.
Just as follows
-And how do we call functions in Python ? (In this place, we just use the definitions above)//Function without arguments and return def myFunction1(): print("Hello World") //Function with arguments def myFunction2(username, greeting): print("Hello, %s ,From My Function!, I wish you %s" % (username, greeting) //Function with arguments and return def myFunction3(a, b): return a + b
myFunction1() myFunction2("Sharon","all the best") myFunction3(1,2)
2.Classes and Objects
-Objects are an encapsulation of variables and functions into a single entity.
-Objects get their variables and functions from classes.
-Classes are essentially a template to create your objects.
-A basic class would look like this
-And to assign the class aboveclass Myclass: variable = "blalalala" def function(self): print("This is a message inside the class")
-To access the variable / function inside of the newly created object.myObject1 = Myclass()
-As we already know that the variable in the class has been defined as "blalala" , we can actually change the variables of the object if you create a new object. Pleace pay attention that the variable we change is the variable which belongs to the object , not the class. We can do the change as follows.myObject1.variable or print(myObject1.variable) myObject2.function()
myObject2 = Myclass() myObject2.variable = "newly changed one "
3.Dictionaries
-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 numner, a list , etc.) instead of using its index to address it.
-Pleace pay attention that we use { } to define dictionaries as follows.
-And we can add the key and value as follows.phonebook = {"John":1111,"Sharon":2222} print(phonebook) //{'John':1111,'Sharon':2222}
phonebook["Aaron"] = 3333 print(phonebook) //{'John':1111,'Sharon':2222,'Aaron':3333}
-To interate over dictionaries.
-Does not keep the order of the values stored in it.
-To iterate over key value pairs, use the following syntax:
-How to remove a pair of key and value ?for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number))
-To know if "John" is in the dictionary ? Use "if"del phonebook["John"] print(phonebook) or phonebook.pop("John") print(phonebook)
if "John" in phonebook: print("John is listed in the phonebook") if "John" not in phonebook: print("John is not listed in the phonebook")