CC3_Final_Term

Subdecks (2)

Cards (94)

  • Function
    A block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
  • How to create a function
    1. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )
    2. Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses
    3. The code block within every function starts with a colon (:) and is indented
    4. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None
  • Defining and calling a function
    • def greet():
    • print("Hello! This is a Function")
    • greet();
  • Parameter
    The variable listed inside the parentheses in the function definition
  • Argument
    The value that is sent to the function when it is called
  • Function with parameters
    • def greet(name): #name is the parameter
    • print("hi" + name)
    • greet('John'); #arguments
  • Function with default value parameters

    • def greet(name="John Doe"):
    • print("hi" + name)
    • greet();
    • greet("Ana");
  • Function with return
    • def add(x,y):
    • return x+y
    • print(add(7,10))
  • Arbitrary Arguments, *args

    If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments.
  • Arbitrary Arguments, *args

    • def myshoes(*shoes):
    • print("My favorite shoe is: " + shoes[2])
    • myshoes("J1", "J2", "J3","J4")
  • Arbitrary Keyword Arguments, **kwargs
    If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments.
  • Arbitrary Keyword Arguments, **kwargs
    • def names(**kiddos):
    • print("Hi " + kiddos["fname"] + " " + kiddos["lname"])
    • names(fname = "Michael", lname = "Jordan")
  • Recursion
    Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
  • Recursion
    • factorial(3) # 1st call with 3
    • 3 * factorial(2) # 2nd call with 2
    • 3 * 2 * factorial(1) # 3rd call with 1
    • 3 * 2 * 1 # return from 3rd call as number=1
    • 3 * 2 # return from 2nd call
    • 6 # return from 1st call
  • List
    • A data structure that's built into Python and holds a collection of items. Lists have a number of important characteristics:
    • List items are enclosed in square brackets, like this [item1, item2, item3].
    • Lists are ordered – i.e. the items in the list appear in a specific order. This enables us to use an index to access to any item.
    • Lists are mutable, which means you can add or remove items after a list's creation.
    • List elements do not need to be unique. Item duplication is possible, as each element has its own distinct place and can be accessed separately through the index.
    • Elements can be of different data types: you can combine strings, integers, and objects in the same list.
  • List
    • numbers= [1, 2, 3, 4, 5 ]
    • food = ["cake", "burger", "fries"]
    • print(numbers[index number])
    • print(numbers[0]) #1
    • print(food[1]) #burger
  • Changing value in a list
    1. male = ['John','Mike']
    2. print(male[0])
    3. male[0] = "Frank"
    4. print(male[0])
  • Adding object to a list
    1. Using append()
    2. numList = [1, 2, 3, 4, 5]
    3. numList.append(99)
    4. print(numList)
    5. Using insert()
    6. male = ['John','Mike']
    7. male.insert(1,"Jake")
    8. print(male)
  • Removing object to a list
    1. Using remove()
    2. male = ['John','Mike','Jake']
    3. male.remove("Jake")
    4. print(male)
    5. Using pop()
    6. male = ['John','Mike','Jake']
    7. male.pop(1)
    8. print(male)
  • Arranging object in a list
    1. Using sort()
    2. numList = [20, 2, 33, 42, 25]
    3. numList.sort()
    4. print(numList)
    5. Using reverse()
    6. numList = [20, 2, 33, 42, 25]
    7. numList.reverse()
    8. print(numList)
  • Counting object Checking object index
    1. Using count()
    2. numList = [25, 2, 33, 42, 25]
    3. counter = numList.count(25)
    4. print(counter)
    5. print(len(numList))
    6. Using index()
    7. numList = [11, 2, 33, 42, 25]
    8. indexPosition = numList.index(42)
    9. print(indexPosition)
  • Combining lists
    1. male = ['Bien','John']
    2. female = ['Jayde','Ana']
    3. male.extend(female)
    4. print(male)
    5. print(male[3])
  • Tuple
    • A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
    • Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
    • Allow duplicate value
  • Tuple
    • tup1 = ('physics', 'chemistry', 1997, 2000);
    • tup2 = (1, 2, 3, 4, 5 );
    • tup3 = "a", "b", "c", "d";
  • Accessing tuple
    1. tup1 = ('physics', 'chemistry', 1997, 2000)
    2. tup2 = (1, 2, 3, 4, 5, 6, 7 )
    3. print ("tup1[0]: ", tup1[0])
    4. print ("tup2[1:5]: ", tup2[1:5])
  • Dictionary
    • Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
    • Keys are unique within a dictionary while values may not be.
  • Dictionary
    • dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    • KEY = NAME
    • VALUE = Zara
  • Accessing dictionary
    1. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    2. print ("dict['Name']: ", dict['Name'])
    3. print ("dict['Age']: ", dict['Age'])
  • Adding item to dictionary
    1. country_capitals = {
    2. "Germany": "Berlin",
    3. "Canada": "Ottawa",
    4. }
    5. # add an item with "Italy" as key and "Rome" as its value
    6. country_capitals["Italy"] = "Rome"
    7. print(country_capitals)
  • Updating dictionary
    1. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    2. dict['Age'] = 8; # update existing entry
    3. dict['School'] = "DPS School"; # Add new entry
    4. print ("dict['Age']: ", dict['Age'])
    5. print ("dict['School']: ", dict['School'])
  • Deleting dictionary elements
    1. You can either remove individual dictionary elements or clear the entire contents of a dictionary.
    2. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement.
    3. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    4. del dict['Name']; # remove entry with key 'Name'
    5. dict.clear(); # remove all entries in dict
    6. del dict ; # delete entire dictionary
    7. print ("dict['Age']: ", dict['Age'])
    8. print ("dict['School']: ", dict['School'])
  • Iterating through a dictionary
    1. student = {
    2. "name": "JHONG TAN",
    3. "age": "48" ,
    4. "gender":"Male"
    5. }
    6. # print dictionary keys one by one
    7. for key in student:
    8. print(key)
    9. # print dictionary values one by one
    10. for data in student:
    11. dataVals = student[data]
    12. print(dataVals)
  • Dictionary methods
    • pop()
    • update()
    • clear()
    • keys()
    • values()
    • get()
    • popitem()
    • copy()
    • len()
    • in
    • items()
    • Adding item to a dictionary
  • Set
    A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.
  • Set
    • fruits= {"apple", "banana", "cherry"}
    • print(fruits)
  • Accessing set
    1. A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.
    2. fruits= {"apple", "banana", "cherry"}
    3. print(fruits)
  • Adding item to a set
    1. fruits= {"apple", "banana", "cherry"}
    2. fruits.add("Guyabano")
    3. print(fruits)
    4. prog = {"C", "C#", "Java"}
    5. prog.update(["PHP", "JS"])
    6. print(prog)
  • Removing item to a set
    1. To remove an item in a set, use the remove(), or the discard() method.
    2. fruits= {"apple", "banana", "cherry"}
    3. fruits.remove("banana")
    4. print(fruits)
    5. prog = {"C", "C#", "Java"}
    6. prog.discard("C")
    7. print(prog)
  • List, Tuple, Set and Dictionary
    • List is a collection which is ordered and changeable. Allows duplicate members.
    • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
    • Set is a collection which is unordered and unindexed. No duplicate members.
    • Dictionary is a collection which is ordered* and changeable. No duplicate members.