ICTC - Python Programming.pdf
Document Details
Uploaded by ProminentBowenite4083
Tags
Related
- CC102 - Computer Programming 1 (Python).pptx
- Introduction to Computer Science Using Python PDF
- Introduction to Python Programming PDF
- Computer Science Class XI Past Paper PDF 2023-24
- Computer Science PYTHON Book PDF for Class 12
- Introduction to Computation and Programming Using Python (2nd Edition) PDF
Full Transcript
Python 3 Programming Fundamental Concepts of Programming ‣ Programming involves using variables to store and manipulate data along with operators to perform actions on that data. Constant values stored in variables are referred...
Python 3 Programming Fundamental Concepts of Programming ‣ Programming involves using variables to store and manipulate data along with operators to perform actions on that data. Constant values stored in variables are referred to as Literals. ‣ Decision making is a crucial part of programming logic and typically comes into play after data handling and before implementing algorithms or executing actions based on conditions. ‣ Looping is another fundamental concept in programming that enables efficient and flexible execution of code, making it an indispensable tool for developers. Programming Fundamental Concepts of Programming ‣ Functions encapsulate a block of code that can be reused and called multiple times within a program, promoting code organization, readability, and reusability. ‣ Functions help break down complex tasks into smaller, more manageable pieces, enhancing modularity and maintainability. ‣ Additionally, functions allow for parameterization, enabling customization and flexibility in code execution. Python Programming Language An Introduction to Python Programming Python 1. Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. 2. Python was created by Guido van Rossum during 1985- 1990. 3. Like Perl, Python source code is also available under the GNU General Public License (GPL). 4. Python is designed to be highly readable. Python uses English keywords frequently whereas other languages use punctuation, and Python has fewer syntactical constructions than other languages. 5. Python is a great language for beginner-level programmers Python 1. Python is Interpreted − Python is processed at runtime by the interpreter. Programmers do not need to compile Python program before executing them. This is similar to PERL and PHP. 2. Python is Interactive − Programmers can actually sit at a Python prompt and interact with the interpreter directly to write Python programs. 3. Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. 4. Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to web browsers. Python - Features 1. Easy-to-learn − Python has few keywords, a simple structure, and clearly defined syntax. This allows students to pick up the language quickly. 2. Easy-to-read − Python code is more clearly defined and visible. 3. Easy-to-maintain − Python's source code is fairly easy-to-maintain. 4. A broad standard library − Python's library is extensive and highly portable compatible with UNIX, Windows, and Macintosh platforms. 5. Interactive Mode − Python supports an interactive mode, allowing for interactive testing and debugging of code snippets. 6. Portable − Python can run on a wide variety of hardware platforms and maintains the same interface across all platforms. Python - Features 7. Extendable − Programmers can add low-level modules to the Python interpreter, enabling them to enhance or customize their tools for greater efficiency. 8. Databases − Python provides interfaces to all major databases. 9. GUI Programming − Python supports the creation and porting of GUI applications to various system calls, libraries and windows systems, including Windows MFC, Macintosh, and the X Window system of Unix. 10. Scalable − Python offers better structure and support for large programs compared to shell scripting. Python - Features 11. Python programming language supports functional and structured programming methods as well as OOP. 12. Python can be used as a scripting language or can be compiled to bytecode for building large applications. 13. Python provides very high-level dynamic data types and supports dynamic type checking. 14. Python supports automatic garbage collection. 15. Python can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Python - Installation Setting up Python Python - Installation 1. Open a Web browser and go to https://www.python.org/downloads/. 2. Follow the link to download Windows installer, named python-XYZ.exe, where XYZ is the version required for installation. 3. Save the installer file to the local machine and then run it. 4. This will launch the Python installation wizard, which is easy to use. 5. Check the box labeled "Add to Path". Simply accept the default settings, wait until the installation is finished, and it is done. 6. To verify if python is installed on a Windows PC, run the following in the Command Prompt : python --version Python – Quick Start 1. Python is an interpreted programming language. This means developers write Python (.py) files in any text editor and then put those files into the python interpreter to be executed. 2. Let us write "helloworld.py" file, which can be done in any text editor print("Hello, World !") 3. Save the file. To run the python file on the command line: C:\Users\Desktop>python helloworld.py 4. The output should read Hello, World ! 5. Congratulations the first program executed successfully. Python - Syntax Indentations and Comments In other programming languages indentation, is for readability. In Python, however indentation is important. Python uses indentation to indicate a block of code. if (5 > 2): print ("Five is greater than two !") Python has commenting capability. Comments start with a #, and Python will render the rest of the line as a comment: # This is a comment print ("Hello World !") Python - Syntax The semicolon ( ; ) allows multiple statements on the single line, provided that neither statement starts a new code block. import sys; x = 'foo’; print(x + '\n’) A group of individual statements that form a single code block are called suites in Python. Compound statements such as if, while, def, and class require a header line and a suite. Header lines begin the statement and terminate with a colon ( : ) if expression: suite else: suite Python – Interpreter 1. To quickly test a short piece of Python code, sometimes it is easiest to run Python directly from the command line instead of writing the code in a file. 2. You can do this by typing the following in the windows command line C:\Users\Desktop>python C:\Users\Your Name>python Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello, World!") Hello, World ! >>> exit() Literals / Variables Understanding Literals / Variables with Examples Literals Literal is a notation for representing a fixed value. In python, literals represent the actual data values used in the program. For example, 5 is a numeric literal representing the integer 5, and "hello" is a string literal representing the string "hello". Types of literals in Python: 1. Numeric literals: Integers, floating-point numbers, complex numbers. 2. String literals: Sequences of characters enclosed within quotes. 3. Boolean literals: True or False. 4. None literal: Represents the absence of value. 5. Special literals: True, False and None Variable Declaration Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. homerun = 6 The above statement creates a variable named "homerun" and assigns it the value 6. Python stores the value 6 in the memory and then makes the variable "homerun" refer to it. The important thing to note is that the variable "homerun" doesn’t contain the value directly. It only refers to a memory location which contains the actual value. Variable Names A variable can have a short name (like x and y) or a more descriptive name (such as age, car_name, total_volume). Here are the rules for Python variables: 1. A variable name must start with a letter or the underscore character 2. A variable name cannot start with a number 3. A variable name can only contain alphanumeric characters and underscores (A-z, 0- 9, and _ ) 4. Variable names are case-sensitive (age, Age and AGE are three different variables) Output The Python "print" function is often used to output variables. To combine both text and a variable, Python uses the "+" character. The process is called string concatenation. >>> description = "awesome“ >>> print("Python is " + description) >>> total = 5 >>> print("Total : " + str(total)) For numbers, the "+" character works as a mathematical operator: >>> x = 5 >>> y = 10 >>> print (x + y) Data Types 1. Variables themselves don't have an inherent data type. 2. Python is dynamically typed, meaning that the data type of a variable is determined by the type of value it currently holds. 3. This means that values of different types can be assigned to the same variable during the execution of the program. x = 5 # Here, x is an integer variable print(type(x)) # Output: x = "hello" # Now, x is a string variable print(type(x)) # Output: x = True # Now, x is a boolean variable print(type(x)) # Output: Instance 1. Instance refers to a specific realization or occurrence of a class in memory. 2. An instance is an object created from a class. Instances can have attributes and methods defined by their class. 3. The "isinstance()" function is used to check if an object is an instance of a particular class. x = 5 print(isinstance(x, int)) print(isinstance(x, float)) Variables hold References 1. Variables hold references to objects rather than the actual data itself. 2. These references essentially point to memory addresses where the data is stored. 3. When you assign a value to a variable, you're essentially creating an object (if it doesn't already exist) and storing it in memory. 4. The variable then holds a reference to that memory address where the object is stored. x = 5 print(id(x)) # Output: 140714183147984 y = 5 print(id(y)) # Output: 140714183147984 Data Type Casting Data type casting refers to the process of converting a value from one data type to another. Python provides several built-in functions for type casting, allowing to convert between different data types as needed. Function Description Example int() Converts a value to an integer. x = int(5.6) # x will be 5 y = int("10") # y will be 10 float() Converts a value to a x = float(5) # x will be 5.0 floating point number. y = float("3.14") # y will be 3.14 str() Converts a value to a string. x = str(5) # x will be "5" y = str(3.14) # y will be "3.14" bool() Converts a value to a boolean. x = bool(5) # x will be True y = bool(0) # y will be False Input The "input()" function is used to take user input from the console during runtime. user_input = input("Enter something: ") print("You entered:", user_input) Input provided by the user is always treated as a string. If you need the input to be treated as a different data type, you can use type casting functions num_str = input("Enter a number: ") num = int(num_str) result = num * 2 Input function is a powerful tool for creating interactive programs and scripts. Handling Multiple Values In Python, you can assign multiple values to a single variable using various data structures such as lists, tuples, or sets. Let us use square brackets [] to create a list # Assigning multiple values to a single variable using a list quantities = [1, 2, 3, 4, 5] prices = [1.1, 2.2, 3.3, 4.4, 5.5] fruits = ["apple", "orange", "mango", "banana", "grapes"] available = [True, True, True, False, False] To find the number of items in the list, use the "len()" function. fruits = ["apple", "orange", "mango", "banana", "grapes"] print(len(fruits)) Operators Python Operators with Examples Arithmetic Operators Operator Description + Addition - Subtraction * Multiplication / Division % Modulus ** Exponentiation // Floor division Arithmetic Operators Start the interpreter and wait for the primary prompt >>> >>> 2 + 2 # 4 >>> 50 – 5 * 6 # 20 >>> 50 – 5 * 6 / 4 # 42.5 => Multiplication, Division first minus next >>> (50 – (5 * 6)) / 4 # 5 => Brackets >>> 17 / 3 # classic division returns a float Division >>> 17 // 3 # floor division discards the fractional part >>> 17 % 3 # the % operator returns the remainder of the division Exponent >>> 5 ** 2 # 25 >>> 2 ** 7 # 128 Assignment Operators Operator Description Example Same As = Assignment x=5 x=5 += Addition Assignment x += 3 x=x+3 -= Subtraction Assignment x -= 3 x=x–3 *= Multiplication Assignment x *= 3 x=x*3 /= Division Assignment x /= 3 x=x/3 %= Modulus Assignment x %= 3 x=x%3 //= Floor Division Assignment x //= 3 x = x // 3 **= Exponentiation Assignment x **= 3 x = x ** 3 Assigning Values 1. Python variables do not need explicit declaration to reserve memory space. Declaration happens when assign a value to a variable. 2. The equal sign (=) is used to assign values to variables. >>> counter = 100 # An integer assignment >>> miles = 1000.0 # A floating point >>> name = "John" # A string Multiple Assignment >>> a = b = c = 1 >>> a, b, c = 1, 2, "John" Assigning Values Shorthand assignment operators >>> x = 5 # 5 >>> x += 3 # 8 >>> x -= 3 # 5 Multiple Assignment >>> x *= 3 # 15 >>> x /= 3 # 5 >>> x %= 3 # 2 >>> x = 10 >>> x //= 3 # 3 >>> x **= 3 # 27 Comparison Operators Operator Description == Equal to != Not Equal > Greater than < Less than >= Greater than or equal to >> 2 == 5 # FALSE >>> 2 == 2 # TRUE >>> 2 != 2 # FALSE Multiple Assignment >>> 2 == 2 # TRUE >>> 2 > 3 # FALSE >>> 2 < 3 # TRUE >>> 2 >= 2 # TRUE >>> 5 >= 2 # TRUE >>> 3 5 Returns True if one of the statements is or true x < 5 or x > 10 Reverse the result, returns False if the not result is true not (x < 10 and x > 5) Bitwise Operators Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits > Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off Bitwise Operators Test the bitwise operators in the Interpreter >>> 5 & 1 # 0101 & 0001 => 0001 => 1 [both bits must be 1 to result 1] >>> 5 | 1 # 0101 | 0001 => 0101 => 5 [either one bit is 1 the result is 1] >>> 3 ^ 2 # 0011 ^ 0010 => 0001 => 1 [0-1 yields 1, 1-0 yields 1, 1-1 yields 0, 0-0 yields 0] >>> ~3 # 0011 => 1100 => -4 Shift Operators >>> 3 1100 => 12 >>> 3 >> 2 # 0011 shift right 2 times => 0000 => 0 Bitwise Assignment Operators Operator Example Same As &= x &= 3 x=x&3 |= x |= 3 x=x|3 ^= x ^= 3 x=x^3 >>= x >>= 3 x = x >> 3 > price = 100.50 >>> price * tax # 12.5625 >>> price + _ # 113.0625 >>> round(_, 2) # 113.06 This _ variable should be treated as read-only by the user. The user don't explicitly assign a value to the variable _ IF ELIF ELSE / Nested If IF ELIF ELSE / Nested If in Python with Examples If Statement An "if statement" is written by using the if keyword, followed by a condition, and then a block of code that executes if the condition evaluates to true. x = 50 if x > 0: print(“x is positive number") Indentation In Python, indentation (whitespace at the beginning of lines) is used to define the scope of code blocks. This is different from many other programming languages, which often use curly brackets {} to denote scope. x = 33 if x > 0: print(“x is positive number") Error because no indentation If Else Statement An "else" statement in Python can be combined with an if statement to provide an alternative block of code that executes when the conditional expression in the if statement resolves to "False". The else statement is optional and there can be at most one else statement following an if statement. x = 33 if x > 100: print("x Is a positive number") else: print("x is a negative number") Nested If In Python, you can nest if statements inside other if statements to create more complex conditional logic. This allows you to execute different code blocks based on multiple conditions. x = 10 y = 5 if x > 5: print("x is greater than 5") if y > 3: print("y is greater than 3") else: print("y is not greater than 3") else: print("x is not greater than 5") If Elif Else Statement The elif keyword is a way of saying "if the previous conditions were not true, then try this condition". a = 33 b = 33 if a > b: print("a is greater than b") elif a == b: print("a is equals to b") else: print("a is less than b") In this example a is equals to b so the first condition fails. The second condition is true so it prints "a is equals to b" Single-line if statement If only one statement to execute a = 33 b = 200 if a > b: print("a is greater than b") If one for if and one for else print("a is greater than b") if a > b else print("a is less than b") If have multiple statements print("a is greater than b") if a > b else print("a equals to b") if a == b else print("a is less than b") Logical Operator The and keyword is a logical operator a = 5 b = 30 c = 50 print("TRUE") if b > a and b < c else print("FALSE") The or keyword is a logical operator a = 40 b = 30 c = 50 print("TRUE") if b > a or b < c else print("FALSE") More on Conditions Operators 'in' and 'not in' check whether a value occurs in a sequence. >>> 3 not in [2, 3, 4] # False >>> 3 not in [4, 5, 6] # True >>> (2, 3) not in [(2, 3), (5, 6), (9, 1)] # False >>> (2, 3) not in [(2, 7), (7, 3), "hi"] # True Operators 'is' and 'is not' used to compare two objects. This operators is to test for object identity: x is y is true if and only if x and y are the same object. >>> x = 'abc' # id(x) >>> y = 'abc' # id(y) >>> x is y # True Comparisons can be chained. For example, 'a < b == c' tests whether a is less than b and more over b equals c. While / For Loops While / For Loops in Python with Examples While Else Statement A while loop is written by using the "while" keyword. counter = 1 while counter < 11: print (counter) counter += 1 If else statement is used with a while, it gets executed when condition is false. counter = 1 while counter < 11: print (counter) counter += 1 else: print("All numbers printed") Break Continue Statement Break Statement counter = 1 while counter < 11: print (counter) if counter == 5: break counter += 1 Continue Statement counter = 0 while counter < 11: counter += 1 if counter == 5: continue print (counter) While Else Break Statement If the else statement is used with the while, it gets executed when the condition is false. counter = 1 while counter < 11: print (counter) if counter == 5: break counter += 1 else: print("All numbers printed") In the above example the print statement inside else does not gets executed, since the counter never gets greater than 11. For Statement A for loop is used for iterating over a sequence such as list. In python the for loop does not require an indexing variable to set beforehand. fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) Looping through a String. String is sequence of characters. for x in "banana": print(x) For Else Statement If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. Let us use for else to generate prime numbers between 1 to 100 for numbers in range(1, 100): for number in range(2, numbers): if numbers % number == 0: break else: print (number + " is a prime number") For Statement with Break With the break statement we can stop the loop before it has looped through all the items: Banana gets printed and then exit Banana never gets printed but exit the the loop: loop: fruits = ["apple", "banana", fruits = ["apple", "banana", "cherry"] "cherry"] for x in fruits: for x in fruits: print(x) print(x) if x == "banana": break For Statement with Continue The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues with the next iteration. for number in range(2, 100): if number % 2 == 0: print("Found an even number " + str(number)) continue print ("Found an odd number " + str(number)) For Statement using Index Enumerate() method adds a counter to an Iterable and returns it in a form of enumerate object which can then be used directly in for loops. fruits = ["apple", "banana", "cherry"] for index, value in enumerate(fruits): print(index + ". " + value) An alternative way of iterating through each item is by index offset. fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ("Current fruit :" + fruits[index]) Short Hand List comprehensions are lists that generate themselves with an internal for loop. Syntax newlist = [thing for thing in list_of_things] Double each element in the list mylist = [21, 22, 23, 24, 25] doublelist = [number * 2 for number in mylist] Everything is conditional mycars = ["Proton", "Volvo", "Mazda", "Mercedes"] fivelettercars = [mycar for mycar in mycars if len(mycar) == 5] Short Hand Iterate through multiple lists [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] Calculate pi values from math import pi [str(round(pi, i)) for i in range(1, 6)] # output # ['3.1', '3.14', '3.142', '3.1416', '3.14159'] Functions Functions in Python Introduction A user-defined function is a block of organized, reusable code that is used to perform a single, related action. Rules to define a function 1. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). 2. Any parameters should be placed within 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 Functions – Syntax / Example Syntax def functionname( parameters ): function_suite return [expression] Example def sayHello( str ): str = "Hello, " + str return str Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the function is declared it can be called from another function or directly from the Python prompt. def sayHello( str ): str = "Hello, " + str return str print(sayHello("Jegan")) Passing Parameters Pass by Value Pass by Reference def sayHello( name ): def changeValue( values ): name = "Kannan" Values = 25 return return name = "Jegan" values = [10, 20, 30, 40, 50] sayHello(name) print(values) print(name) changeValues(values) print(values) Function Arguments Required arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. def addition( a, b ): total = a + b return total print(addition(10, 20)) print(addition(10)) Addition() takes exactly 2 arguments (1 given) Function Arguments Keyword arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. def printinfo ( name, age ): print ("Name : " + name) print ("Age : " + age) return printinfo ( age = 20, name = "John" ) Function Arguments Default arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example prints default age if it is not passed. def printinfo ( name, age = 35 ): print ("Name : " + name) print ("Age : " + age) return printinfo ( age = 20, name = "John" ) printinfo ( name = "David") Function Arguments Variable-length arguments Sometime to process a function, the programmers need to pass more than one argument than you specified while defining the function. Assigns the optional positional arguments to a tuple named mynumbers. def sum ( message, *mynumbers ): total = 0 for mynumber in mynumbers: total = total + mynumber return message + " " + str(total) print ( sum ("Total : ", 10, 20, 30, 40, 50) ) Function Arguments Variable-length arguments Sometime to process a function, the programmers need to pass more than one argument than you specified while defining the function. def intro ( **data ): for key, value in data.items(): print("{} is {}".format(key, value)) intro ( FirstName="Sita", LastName="Sharma", Age=22, Phone=0168652259" ) intro ( FirstName="John", LastName="Wood", Email="[email protected]", Country="Italy" ) Nested Functions Python allows to define a function within a function which is known as nested function. To define a nested function, just use the keyword def and define a function as normal. def average (a, b, c): def total (a, b, c): return a + b + c return total (a, b, c) / 3 print(average(1, 2, 3)) Assign Functions to Variables In Python, functions are first class citizens, they are objects and that means it can be assigned to a variable. def greet(name): return "hello "+name greet_someone = greet Assign function to a variable print(greet_someone("John")) Call function assigned to a variable # Outputs: hello John Function inside Function Python allows defining functions inside another function def greet(name): def get_message(): Function inside another function return "Hello " result = get_message() + name Calling inner function return result print(greet("John")) Calling the main function # Outputs: Hello John Function can be passed In Python, functions can be passed as parameters to other functions. def greet(name): return "Hello " + name def call_func(func): Function is passed as a parameter to another function other_name = "John" return func(other_name) print(call_func(greet)) Calling a function by passing another function # Outputs: Hello John Function can be returned In Python, a function can return another function. In other words, function generating other function. def compose_greet_func(): def get_message(): return "Hello there!" return get_message greet = compose_greet_func() Return function is assign to a variable print(greet()) Call the function assigned to a variable # Outputs: Hello there! Closure Inner functions have access to the enclosing scope. Another thing to note, Python only allows read access to the outer scope and not assignment. def compose_greet_func(name): def get_message(): Inner function can access the return "Hello there "+name+"!" name argument return get_message Function returns a function greet = compose_greet_func("John") print(greet()) # Outputs: Hello there John! Anonymous Functions Anonymous functions are not declared using the def keyword. They are declared using lambda keyword. 1. Lambda forms can take any number of arguments but return just one value. They cannot contain multiple expressions. 2. An anonymous function cannot be a direct call to print because lambda requires an expression 3. Lambda functions cannot access variables other than those in their parameter list and those in the global namespace. 4. The lambda's are a one-line version of a function. The lambda’s are slightly faster than def functions. Lambda Functions Syntax lambda arguments: expression Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Example # A Lambda expression that always multiply the parameter by 2 double = lambda x: x * 2 print(double(5)) Use of Lambda Function Lambda functions are used as an argument to a higher-order function (a function that takes in other functions as arguments). The following code filter only the even numbers in the list. my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) The following code uses map to multiply every item in the list with 2. my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2, my_list)) print(new_list) Use of Lambda Function Power of lambda is better shown when they are used inside another function. def multiplier(n): return lambda a : a * n Let us make a function that always doubles the number mydoubler = multiplier(2) print(mydoubler(11)) Let us make a function that always triples the number mytripler = multiplier(3) print(mydoubler(11)) Function – map() Advantage of the lambda operator can be seen when it is used in combination with the map() function. The map() is a function with two arguments: r = map(func, seq) def fahrenheit(temp): return ((float(9) / 5) * temp + 32) def celsius(temp): return (float(5) / 9) * (temp - 32) temp = (36.5, 37, 37.5,39) F = map(fahrenheit, temp) C = map(celsius, F) Function – filter() The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function returns True. >>> fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> result = filter(lambda x: x % 2, fib) >>> print result >>> result = filter(lambda x: x % 2 == 0, fib) >>> print result [0, 2, 8, 34] Function – reduce() The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value. Note: Import reduce function from functools import reduce >>> reduce(lambda x, y: x + y, [47,11,42,13]) Fancier Output Fancier Output Formatting in Python Print using % Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d". name = "John" print("Hello, %s!" % name) age = 23 print("%s is %d years old." % (name, age)) %s - String (or any object with a string representation, like numbers) %d - Integers %f - Floating point numbers Print using format Pythonic way – The string format() method formats the given string into a nicer output in Python. "Art: {0:5d}, Price: {1:8.2f}".format(453, 59.058) Positional "Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058) Keyword Alignment (left, right and centre) "{0:20s} {1:6.2f}".format('Spam & Eggs:', 6.99) Alignment Right "{0:^20s} {1:6.2f}".format('Spam & Eggs:', 6.99) Alignment Centre "{0:*^20s} {1:6.2f}".format('Spam & Eggs:', 6.99) Alignment Centre with padding character * Print using format Zero Padding x = 378 print("The value is {:06d}".format(x)) x = -378 print("The value is {:06d}".format(x)) Thousands Separator x = 78962324245 print("The value is {:,}".format(x)) print("The value is {0:6,d}".format(x)) x = 5897653423.89676 print("The value is {0:12,.3f}".format(x)) Print using format Using dictionaries in "format" print ("Capital of {0:s} is {1:s}".format("Ontario","Toronto")) print ("Capital of {state} is {capital}".format(state=“Perak",capital="Ipoh")) data = dict(province="Ontario",capital="Toronto") print("The capital of {province} is {capital}".format(**data)) Iterate through the dictionary and print all the values capital_country = {"US" : "Washington", "Canada" : "Ottawa", "MY" : "Malaysia"} for c in capital_country: format_string = c + ": {" + c + "}" print(format_string.format(**capital_country)) Print using f-strings Python 3.6 introduces formatted string literals. The formatted string literals are prefixed with an 'f'. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol. price = 11.23 f"Price in Euro: {price}" f"Price in Swiss Franks: {price * 1.086}" f"Price in Swiss Franks: {price * 1.086:5.2f}" Iterate through the list and print using f-string for article in ["bread", "butter", "tea"]: print(f"{article:>10}:") Print using Template String Template Strings: Instead of using the normal % based substitutions, template strings support the $ based substitutions. Templates have some methods such as substitute() and safe_substitute(). from string import Template money = dict(who = 'You', to_whom = 'baker') Template('$who owe the $to_whom a total of $$100').substitute(money) Template('$who owe the $to_whom a total of $$100’).safe_substitute(money) Note: The usual syntax is $identifier, but can also code as ${identifier} Format using methods Other string methods for Formatting s = "Python" s.center(20) s.center(20, "*") s.ljust(20) s.ljust(20, "*") s.rjust(20) s.rjust(20, "*") account_number = 43447879 str(account_number).zfill(12) Data Types Data Types in Python Standard Data Types Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Python has six standard data types 1. Numbers 2. String 3. List 4. Tuple 5. Set 6. Dictionary Numbers Number data types store numeric values. Number objects are created when a value is assigned to the variable. For example, 1. quantity = 3 2. price = 10.5 Python supports three different numerical types 1. int (signed integers) 2. float (floating point real values) 3. complex (complex numbers) Python 2 has long which has been removed in Python 3 1. long (long integers, can be represented in octal and hexadecimal) Numbers Some examples of numbers int float Complex 10 0.0 3+14j 100 15.20 45j [equals to 0+45j] -786 -21.9 -67+15j 080 32.3e+18 5-26j 0x10 70.2e-12 101+15j >>> x = 3+14j >>> y = 7+96j >>> x.real >>> x.imag >>> x + y String – Enclosing Character String enclosed in single quotes ('…') and double quotes ("…") breakfast = 'spam eggs’ # single quotes message = "I doesn't like the food" #...or use double quotes instead message = 'I doesn\’t like the food’ # use \' to escape the single quote... The print() function produces a more readable output, by omitting the enclosing quotes print('"Isn\'t," she said.') s = 'First line.\nSecond line.' # \n means newline print(s) # with print(), \n produces a new line String – Enclosing Character The character \ is interpreted as escape sequence. Strings can be printed as raw strings by adding an r before the string: print('C:\some\name') # here \n means newline! print(r'C:\some\name') # note the r before the quote Multiline strings are enclosed with triple-quotes """… """ or '''…''' message = """As I am not feeling well I am not able to come to office Regards""" Print(message) String - Operators Strings are concatenated with + operator, and repeated with *: 'b' + 2 * 'o' + 2 * 'k' + 2 * 'e' + 'per' # bookkeeper language = "Python" 'Welcome to ' + language Two or more string literals next to each other are automatically concatenated. 'Welcome to ' 'Python’ # Welcome to Python Put several strings within parentheses text = ('Welcome ' 'to ' 'Python') # Welcome to Python String concatenation works only with two literals. greeting = 'Welcome to ‘ language = 'Python’ greeting + language String In Python Strings are nothing but array of characters >>> word = 'Python' >>> word # character in position 0 >>> word # character in position 5 >>> word[-1] # last character >>> word[-2] # second-last character >>> word[0:2] # characters from position 0 (included) to 2 (excluded) >>> word[:2] + word[2:] >>> word[4:] String Methods Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position format() Formats specified values in a string format_map() Formats specified values in a string String Methods Method Description index() Searches the string for a specified value and returns the position isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces String Methods Method Description istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() Converts a string into lower case lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts Returns a string where a specified value is replaced with a replace() specified value String Methods Method Description Searches the string for a specified value and returns the last rfind() position of where it was found Searches the string for a specified value and returns the last rindex() position of where it was found rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value String Methods Method Description swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case Fills the string with a specified number of 0 values at the zfill() beginning Python - Casting Casting in python is therefore done using constructor functions: 1. int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number) 2. float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) 3. str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals Python - Casting Convert to Integer x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3 Convert to Float x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 w = float("4.2") # w will be 4.2 Convert to String x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0' List A list is a collection which is ordered and changeable. In Python lists are written with square brackets. fruits = ["apple", "banana", "cherry"] print(fruits) Access Items fruits = ["apple", "banana", "cherry"] print(fruits) Change Items fruits = "blackcurrant" print(fruits) List Loop Through a List fruits = ["apple", "banana", "cherry"] Access Items for fruit in fruits: print(fruit) Check if Item Exits fruits = ["apple", "banana", "cherry"] if "apple" in fruits: print("Yes, apple is in the fruits list") else: print("No, apple is not in the fruits list") List List Length fruits = ["apple", "banana", "cherry"] print(len(fruits)) Append Item fruits = ["apple", "banana", "cherry"] fruits.append ("orange") Insert Item fruits.insert (1, "durian") print(fruits) List Remove Item fruits = ["apple", "banana", "cherry"] fruits.remove("banana") The pop() removes specified index, (or last item if index is not specified) fruits = ["apple", "banana", "cherry"] fruits.pop() The del keyword removes the specified index: fruits = ["apple", "banana", "cherry"] del fruits print(fruits) List The list() Constructor fruits = list(("apple", "banana", "cherry")) List Methods Method Description clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the element of a list to the end of the current list index() Returns index of the first element with the specified value reverse() Reverses the order of the list sort() Sorts the list Tuple A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. fruits = ("apple", "banana", "cherry") print(fruits) Access Items fruits = ("apple", "banana", "cherry") print(fruits) Change Items fruits = "blackcurrant" #value will remain the same as banana print(fruits) Tuple Loop Through a Tuple fruits = ("apple", "banana", "cherry") for fruit in fruits: Access Items print(fruit) Check if Item Exits fruits = ("apple", "banana", "cherry") if "apple" in fruits: print("Yes, apple is in the fruits list") else: print("No, apple is not in the fruits list") Tuple List Length fruits = ("apple", "banana", "cherry") print(len(fruits)) Add Item fruits = ("apple", "banana", "cherry") fruits = "orange" # This will raise an error Remove Item fruits = ("apple", "banana", "cherry") del fruits # This will raise an error Tuple The tuple() Constructor fruits = tuple(("apple", "banana", "cherry")) Tuple Methods Method Description count() Returns the number of elements with the specified value index() Returns index of the first element with the specified value Set A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. fruits = {"apple", "banana", "cherry"} print(fruits) Access Items fruits = ("apple", "banana", "cherry") print(fruits) # object is not subscriptable Change Items fruits = "blackcurrant" # Once a set is created the items cannot be changed. # But new items can be added Set Loop Through a Set fruits = {"apple", "banana", "cherry"} Access Items for fruit in fruits: print(fruit) Check if Item Exits fruits = {"apple", "banana", "cherry"} if "apple" in fruits: print("Yes, apple is in the fruits list") else: print("No, apple is not in the fruits list") Set List Length fruits = {"apple", "banana", "cherry"} print(len(fruits)) Add Item fruits = {"apple", "banana", "cherry"} fruits.add("orange") Add Multiple Items fruits = {"apple", "banana", "cherry"} fruits.update(["orange", "mango", "grapes"]) print(fruits) Set Remove Item fruits = {"apple", "banana", "cherry"} fruits.remove("banana") # If item to remove does not exist, this will raise an error. The pop() removes the last item fruits = {"apple", "banana", "cherry"} fruits.pop() # sets are unordered, so which item that gets removed is not known The discard() keyword removes the specified item: fruits = {"apple", "banana", "cherry"} fruits.discard("banana") # If item to remove does not exist, the discard method will NOT raise an error. Set Clear fruits = {"apple", "banana", "cherry"} fruits.clear() print(fruits) The del keyword will delete the set completely fruits = {"apple", "banana", "cherry"} del fruits print(fruits) Set The set() Constructor fruits = set(("apple", "banana", "cherry")) Set Methods Method Description copy() Returns a copy of the list difference() Difference between two or more sets intersection() Intersection of two other sets union() Returns a set containing the union of sets symmetric_difference() Returns a set with symmetric differences of two sets isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not Set - Difference fruits.difference(companies) companies.difference(fruits) fruits = {"orange", "apple"} companies = {"microsoft", "apple"} fruits.difference(companies) # {'orange'} companies.difference(fruits) # {'microsoft'} Set - Intersection fruits.intersection(companies) companies.intersection(fruits) fruits = {"orange", "apple"} companies = {"microsoft", "apple"} fruits.intersection(companies) # {'apple’} companies.intersection(fruits) # {'apple'} Set - Union fruits.union(companies) companies.union(fruits) fruits = {"orange", "apple"} companies = {"microsoft", "apple"} fruits.union(companies) # {'orange', 'apple', 'microsoft'} companies.union(fruits) # {'orange', 'apple', 'microsoft'} Set – Symmetric Difference fruits.symmetric_difference(companies) companies.symmetric_difference(fruits) fruits = {"orange", "apple"} companies = {"microsoft", "apple"} fruits.symmetric_difference(companies) # {'orange', 'microsoft'} companies. symmetric_difference(fruits) # {'orange', 'microsoft'} Dictionaries A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets. They have keys and values. mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } print(mycar) Change Item mycar["year"] = "2013" Accessing Items mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } print(mycar["model"]) print(mycar.get("model")) Dictionaries Loop through a Dictionary and print keys for key in mycar: print(key) Loop through a Dictionary and print values for key in mycar: print(mycar[key]) Loop through a Dictionary to return values and items for value in mycar.values(): print(value) for key, value in mycar.items(): print(key, value) Dictionaries Check if Item Exits mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } if "model" in mycar: print("Yes, model property is in the mycar") else: print("No, model property is not in the mycar") List length mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } print(len(mycar)) Dictionaries Add Item mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } mycar["color"] = "red" Remove Item mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } mycar.pop("model") Pop Item removes the lastly inserted value mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } mycar.popitem() Dictionaries The del keyword removes the item with the specified key name mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } del mycar["color"] The clear keyword empties the dictionary mycar = { "brand":"Proton", "model":"Saga", "year":"2012" } mycar.clear() Dictionaries can also be created using the constructor mycar = dict( {brand="Proton", model="Saga", year="2012"} ) print (mycar) Dictionaries Dictionaries Method Method Description copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and values get() Returns the value of the specified key Returns the value of the specified key. If the key does not setdefault() exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs Object Oriented Programming Object-Oriented Programming (OOP) in Python Introduction 1. Object-oriented Programming, or OOP for short, is a programming paradigm which provides a means of structuring programs so that properties and behaviors are bundled into individual objects. 2. For instance, an object could represent a person with a name property, age, address, etc., with behaviors like walking, talking, breathing, and running. 3. The key takeaway is that objects are at the center of the object-oriented programming paradigm, not only representing the data, as in procedural programming, but in the overall structure of the program as well. Class 1. Classes are used to create user-defined data structures that contains attributes such as class variables and class methods. class Person: first_name = "" Public class variable __ic_number = "" Private class variable def setIcNumber(number): Public class method Person.__ic_number = number Access private class variable def getIcNumber(): Public class method return Person.__ic_number Access private class variable Person.first_name = "Thayanithy" print (Person.first_name) Access class variables Person.setIcNumber(97409) Access class methods print (Person.getIcNumber()) Class The first string is called docstring and has a brief description about the class. There are special attributes such as __doc__ , __name__ , __dict__ class Person: """Person class contains first_name and ic_number""" first_name = "" ic_number = "" def display(): print(Person.first_name) print(Person.ic_number) print(Person.__doc__) print(Person.__name__) print(Person.__dict__) Object Class can be used to create objects. While class is the blueprint, an instance is a copy of the class with actual values. Every object belongs to a specific class. person = Person() This will create a new instance an object named person. Attributes of an object can be accessed using the object name prefix. class Person: def set_first_name (self, first_name): Instance method self.first_name = first_name Instance variable person = Person() print(person.first_name) Object 1. Unlike class variables, instance variables should be defined within methods. Just as instance variables, there are instance methods. These methods are to set and get instance variables of relevant instance. 2. Every single instance method takes self (self is not the keyword) as first parameter which represents the instance of the class. The instance methods access the instance variables using the "self" keyword. 3. However, when calling the instance method no need pass anything for the self as arguments. 4. When a new object is created it does not create a new set of instance methods. Instance methods lie within the class object — nice way to save up memory. In python a class is also an object. So it lives within memory. Class & Object class Person: first_name = "" def set_first_name(self): self.first_name = "Instance First Name" def modify_first_name(): Person.first_name = "Class variable First Name" print(Person.first_name) Print empty Person.modify_first_name() print(Person.first_name) Class variable First Name person = Person() print(person.first_name) Instance variable First Name person.set_first_name() print(person.first_name) Instance First Name Class & Object class Product: class Product: 1. AttributeError are def add_price(self): price related to properties. If a property is not found self.price = self.price + 5 def add_price(): then it raises attribute Product.price = Product.price + 5 error. product = Product() Name Error 2. NameError are related to variables. If a product.add_price() Attribute Error variable is not found class Product: product.price = 10 Attribute Created then it raises name price = 10 error. product.add_price() def add_price(): print(product.price) Result 15 Product.price = Product.price + 5 print (Product.price) Result 10 Product.add_price() print (Product.price) Result 15 Constructor 1. Class functions that begins with double underscore (__) are called special functions as they have special meaning. 2. This special function __init__() gets called whenever a new object of that class is instantiated. 3. This type of function is also called constructors in Object Oriented Programming (OOP) normally used it to initialize all the variables. class ComplexNumber: def __init__(self, real = 0, imaginary =0): self.real = real self.imaginary = imaginary def getData(self): print("{0}+{1}j".format(self.real, self.imaginary)) Encapsulation Encapsulation is restricting access to methods and variables from direct modification. The private attribute is denoted using underscore as prefix. class Computer: def __init__(self): self.maxPrice = 900 def getMaxPrice(self): return self.__maxPrice def setMaxPrice(self, price): self.__maxPrice = price maxPrice = property(getMaxPrice, setMaxPrice) computer = Computer() computer.setMaxPrice(1000) or computer.maxPrice = 1000 print(computer.getMaxPrice()) or print(computer.maxPrice) Method Overloading Like other programming languages, python does not support method overloading. If a program has methods with same name, the latest defined method only can be used. def product(a, b): p = a * b print (p) def product(a, b, c): p = a * b * c print (p) product (4, 5) Python throws error, latest defined method takes 3 parameters product (4, 5, 6) Type Error: missing 1 required positional argument Method Overloading In python the method overloading can be achieved using default parameters. Depending on the function definition, it can be called with zero, one, two or more parameters. class Product: def __init__(self, quantity = 1, price = 100, tax = 6): self.quantity = quantity self.price = price self.tax = tax def do_calculate (self): return (self.quantity * self.price) + self.tax product1 = Product (10, 1000, 5) product2 = Product (10, 1000) product3 = Product (10) product4 = Product () Operator Overloading To overload the arithmetic operator's python has special functions as follows Operator Expression Internally Addition my_obj1 + my_obj2 my_obj1.__add__(my_obj2) Subtraction my_obj1 - my_obj2 my_obj1.__sub__(my_obj2) Multiplication my_obj1 * my_obj2 my_obj1.__mul__(my_obj2) Power my_obj1 ** my_obj2 my_obj1.__pow__(my_obj2) Division my_obj1 / my_obj2 my_obj1.__truediv__(my_obj2) Floor Division my_obj1 // my_obj2 my_obj1.__floordiv__(my_obj2) Remainder my_obj1 % my_obj2 my_obj1.__mod__(my_obj2) Operator Overloading To overload the Bitwise operators python has special functions as follows Operator Expression Internally Bitwise Left Shift my_obj1 > my_obj2 my_obj1.__rshift__(my_obj2) Bitwise AND my_obj1 & my_obj2 my_obj1.__and__(my_obj2) Bitwise OR my_obj1 | my_obj2 my_obj1.__or__(my_obj2) Bitwise XOR my_obj1 ^ my_obj2 my_obj1.__xor__(my_obj2) Bitwise NOT ~my_obj1 my_obj1.__invert__() Operator Overloading To overload the Comparison operators python has special functions as follows Operator Expression Internally Less than my_obj1 < my_obj2 my_obj1.__lt__(my_obj2) Less than or equal to my_obj1 my_obj2 my_obj1.__gt__(my_obj2) Greater than or equal to my_obj1 >= my_obj2 my_obj1.__ge__() Operator Overloading class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __add__(self, point): return Point((self.x + point.x), (self.y + point.y)) def __eq__(self, point): return (self.x == point.x and self.y == point.y) point1 = Point (10, 10) point2 = Point (10, 10) newpoint = point1 + point2 print (newpoint.x) print (newpoint.y) if (point1 == point2): print("point1 equals to point2") Inheritance 1. Classes can inherit from other classes. 2. A class can inherit attributes and behavior methods from another class, called the superclass. 3. A class which inherits from a superclass is called the subclass or child class. 4. For example, program can implement a vehicle class in Python, which might have methods like accelerate and brake. Cars, Buses, Trucks and Bikes can be implemented as subclasses which inherit these methods from vehicle. Single Inheritance Employee class inherits the properties and methods from the Person class. Constructor in Person class is called using the super keyword from Employee. # parent class class Person( object ): def __init__(self, name): self.name = name def say_name(self): print(self.name) # child class class Employee( Person ): def __init__(self, name, salary): self.salary = salary # invoking the __init__ of the parent class super().__init__(name) employee = Employee('Jegan', 1200) employee.say_name() Multi-Level Inheritance Python supports Multi-Level Inheritance, that allows a class to be derived from a sub class. Constructor in Employee class is called from Director and constructor in Person class is called using the super keyword from Employee. # parent class # child class class Person(): class Director( Employee ): def __init__(self, name): def __init__(self, name, salary, shares): self.name = "Per.: " + name self.shares = shares def say_name(self): # invoking the __init__ of the parent class print(self.name) super().__init__("Dir.: " + name, salary) # child class director = Director('Jegan', 1200, 50) class Employee( Person ): director.say_name() def __init__(self, name, salary): self.salary = salary # invoking __init__ of parent class super().__init__("Emp.: " + name) Multiple Inheritance Python supports Multiple Inheritance, that allows a class to be derived from multiple classes. Payment class is inherited from Credit_Card and Debit_Card classes. Credit_Card (first) __init__ method only gets called during Payment object creation class Credit_Card: class Payment(Credit_Card, Debit_Card): def __init__(self, card_number): def __init__(self, number, name): print("Credit Card") self.name = name self.card_number = card_number super().__init__(number) def say_number(self): def say_number(self): print("CC: " + str(self.card_number)) print("Customer: " + self.name) super().say_number() class Debit_Card: payment = Payment(1200, "Jegan") def __init__(self, debit_number): payment.say_number() print("Debit Card") self.debit_number = debit_number Credit Card def say_number(self): Customer: Jegan print("DC: " + str(self.debit_number)) CC: 1200 Alternative to super() Payment class is inherited from Credit_Card and Debit_Card classes. During the payment object creation, let us say we want to call the __init__ method of Credit_Card and Debit_Card definity cannot use the super() keyword. class Credit_Card: class Payment(Credit_Card, Debit_Card): def __init__(self, card_number): def __init__(self, number, name): print("Credit Card") self.name = name self.card_number = card_number Credit_Card.__init__(number) def say_number(self): Debit_Card.__init__(number) print("CC: " + def say_number(self): str(self.card_number)) print("Customer: " + self.name) Credit_Card.say_number() Debit_Card.say_number() class Debit_Card: def __init__(self, debit_number): print("Debit Card") payment = Payment(1200, "Jegan") self.debit_number = payment.say_number() debit_number def say_number(self): print("DC: " + str(self.debit_number)) Overriding Methods Python allows to override methods in child class declared in the parent class. The reason for overriding parent's methods is to add special feature or have different functionality in the subclass. class Student: # define parent class def __init__(self): self.current_academic_year = 2009 def get_academic(self): print 'Academic Year: ' + self.current_academic_year class Alumni(Student): # define child class def __init__(self): self.latest_academic_year = 2019 def get_academic(self): print 'Graduated Year: ' + self.latest_academic_year alumni = Alumni() # instance of child alumni.get_academic() # child calls overridden method Polymorphism Polymorphism is an ability (in OOP) to use common interface for multiple form (data types). class Executive: def calculate_salary(staff): def __init__(self): return self.exp = 4 staff.calculate_salary( self.bsalary = 1200 ) def calculate_salary(self): return self.exp * self.bsalary #passing executive object executive = Executive() class Manager: calculate_salary(executive) def __init__(self): self.exp = 4 #passing manager object self.bsalary = 1200 manager = Manager() self.grade = 2 calculate_salary(manager) def calculate_salary(self): return self.grade * self.exp * self.bsalary Scope - Local If a variable is defined inside the function or inside a class, it will be a local variable. Only the function or class can access the variable. x = "five" def modify_x(): x = 10 x becomes local variable print(x) print local variable x def innermodify_x(): return x + 5 x refers to local variable defined in the modify_x function print(innermodify_x()) modify_x() print(x) global x gets modified Scope - Global If a variable is defined at the top of the script, it will be a global variable. This means that it is accessible from anywhere in the script, including from within a function. In the following example a is defined globally. x = 5 x = 5 def modify_x(): def print_x(): # access and print the global # x = x + 5 x becomes local variable variable global x x refers to global variable print("Inside: " + str(x)) x = x + 5 global x gets modified print("Outside before calling: " + str(x)) print("Outside before calling: " + str(x)) print_x() modify_x() print("Outside after calling: " + print("Outside after calling: " + str(x)) str(x)) Scope - NonLocal The nonlocal statement indicates that particular variables live in an enclosing scope, contains non-local, but also non-global names. It causes the variable to refer to the previously bound variable in the closest enclosing scope. x = "a" x becomes global variable def outer(): x = "b" x becomes local variable def inner(): nonlocal x x becomes nonlocal variable x = "c" nonlocal variable x gets modified print("inner:", x) refers to nonlocal variable x inner() print("outer:", x) refers to local variable x outer() print("global:", x) refers to global variable x Monkey Patching The term monkey patch refers to dynamic (or run-time) modifications of a class or module. Python actually allows to change the behavior of code during run-time # monk.py import monk class A: def monkey_f(self): def func(self): print "monkey_f() is being called" print "func() is being called" # replacing address of "func" with "monkey_f" monk.A.func = monkey_f obj = monk.A() # calling function "func" whose address got replaced # with function "monkey_f()" obj.func() Iterator / Generator / Decorator Iterator / Generator / Decorator in Python Iterator An iterator is an object that contains a countable number of values. In Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__(). 1. Lists, tuples, dictionaries, and sets are all iterable objects. 2. All these objects have a iter() method which is used to get an iterator. fruits = ("apple", "banana", "cherry") fruit = iter(fruits) print(next(fruit)) print(next(fruit)) print(next(fruit)) Iterator Let us create a class as an iterator and implement the methods __iter__() and __next__() in the class. class PrimeNumber: def __iter__(self): self.mynumber = 1 return self def __next__(self): self.mynumber = self.mynumber + 1 return self.mynumber prime_number = PrimeNumber() iterator = iter(prime_number) print(next(iterator)) print(next(iterator)) print(next(iterator)) Generator 1. Python generators are a simple way of creating iterators. Simply speaking, a generator is a function that returns an object (iterator) which can be iterate over (one value at a time). 2. It is simple to create a generator. It is as easy as defining a normal function with yield statement instead of a return statement. If a function contains at least one yield statement it becomes a generator function. 3. In Generator methods like __iter__() and __next__() are implemented automatically. Once the function yields, the function is paused and the control is transferred to the caller. 4. In Generator function the local variables and their states are remembered between successive calls. Generator # A simple generator function # Returns an object but does not start execution. >>> a = my_gen() def my_gen(): n = 1 # Iterate through the items using next(). >>> next(a) print('This is printed first') This is printed first # Generator contains yield 1 # Once the function yields, the function is paused, and the yield n control is transferred to the caller. # Local variables are remembered between successive calls. n += 1 >>> next(a) print('This is printed second’) This is printed second 2 yield n # When the function terminates, StopIteration is raised automatically on further calls. n += 1 >>> next(a) print('This is printed at last’) Traceback (most recent call last):... yield n StopIteration Decorator Function decorators are wrappers to existing functions. A function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returning the generated function which can be used anywhere in the code. A decorator that adds to any return text. def get_text(name): return "Dear {0}, welcome to Python".format(name) def p_decorate(func): Decorator Function def func_wrapper(name): Inner Function that adds paragraph tag around the text return "{0}".format(func(name)) return func_wrapper my_get_text = p_decorate(get_text) Decorator instance is created by passing custom function print(my_get_text("John")) Decorator is called Decorator Syntax Python makes a cleaner syntactic sugar to decorate get_text. There is a neat shortcut for get_text = p_decorator(get_text), which is to mention the name of the decorating function before the function to be decorated. The name of the decorator should be perpended with an @ symbol. def p_decorate(func): def func_wrapper(name): return "{0}".format(func(name)) return func_wrapper @p_decorate Decorator def get_text(name): return "Dear {0}, welcome to Python".format(name) print(get_text("John")) Multiple Decorators To decorate get_text function by 2 other decorators that wrap with div and strong tag around the string output with p tag. my_get_text = div_decorate(strong_decorate(p_decorate(get_text))) print(my_get_text("John")) With Python's decorator syntax @div_decorate @p_decorate @strong_decorate def get_text(name): return "Dear {0}, welcome to Python".format(name) print(get_text("John")) Decorating Methods In Python, methods are functions that expect their first parameter to be a reference to the current object. Decorators can be created the same way. def p_decorate(func): def func_wrapper(self): Decorator takes self as parameter same as methods return "{0}".format(func(self)) return func_wrapper class Person(object): def __init__(self): self.name = "John" @p_decorate Method Decorator def get_fullname(self): return self.name my_person = Person() print(my_person.get_fullname()) Passing arguments The 3 decorators (div_decorate, p_decorate, strong_decorate) each with the same functionality but wrapping the string with different tags def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "{1}".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("div") @tags("strong") @tags("p") def get_text(name): return "Hello "+name Exception Handling Exception Handling in Python Introduction If an error occurs during program execution, Python will terminate and generate an error message. Exceptions can be handled using try statement: 1. The try block lets to test a block of code for errors. 2. The except block lets to handle the error. 3. The code in the finally block gets executed, regardless of the result of the try- and except blocks. try: print(x) Runtime error because name x is not defined except: print("Error occurred") Since try block raises an error, code in except block will be executed. # Note: Without the try block, the program will crash and raise an error. Many Exceptions Python allow us to define as many exception blocks as the programmer wants, e.g. if the programmer wants to execute a special block of code for a special kind of error: try: print(x) except NameError: print("Variable X is not defined") except TypeError: print("Cannot concatenate str with int") except: print("Something else went wrong”) Else Python allow us to use the else keyword with try block to define a block of code that will be be executed if no errors were raised: try: x = 10 print(x) except NameError: print("Variable X is not defined") except TypeError: print("Cannot concatenate str with int") except: print("Something else went wrong") else: print("Program executed successfully") Finally If code is specified inside the finally block, the code will be executed regardless if the try block raises an error or not. The finally block can be useful to close objects and clean up resources. try: x = 10 print(x) except: print("Something else went wrong") else: print("Program executed successfully") finally: print("Remove the variable x from memory") Custom Exceptions Programmers may name their own exceptions by creating a new exception class. Exceptions need to be derived from the Exception class, either directly or indirectly. Make code more readable with custom exceptions. class NoBalance(Exception): try: # Constructor or Initializer balance_amount = 2000 def __init__(self, value): withdraw_amount = 2500 self.value = value if (balance_amount < withdraw_amount): raise(NoBalance(2000 - 2500)) # __str__ is to print() the value def __str__(self): except NoBalance as error: message = "Balance cannot be : " return(message + repr(self.value)) # Value of Exception is stored in error print('A New Error occured: ', error) Files Files in Python Programming Introduction File handling is an important part of any application development. 1. File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk). 2. Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data. Python has several functions for 1. Creating files 2. Reading files 3. Updating files 4. Deleting files File Handling The key function for working with files in Python is the open() function. The open() function takes two parameters 1. Filename 2. Mode There are four different methods (modes) for opening a file: "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) File Handling Open a File on the Server f = open("demofile.txt", "r") f = open("demofile.txt", "a") f = open("demofile.txt", "w") f = open("demofile.txt", "x") Read data By default, the read() method returns the whole text but can determine how many characters to read. print(f.read()) print(f.read(5)) File Handling Read lines The readline() method reads line by line. print(f.readline()) By calling readline() two times, you can read the two first lines: print(f.readline()) print(f.readline()) Read all the lines f = open("demofile.txt", "r") for x in f: print(x) File Handling Writing to an existing file To write to an existing file, add the parameter to the open method f = open("demofile.txt", "a") # Append - will append to the end of the file f.write("Now the file had one more line") f = open("demofile.txt", "w") # Write - will overwrite any existing content f.write("Existing file content is deleted") Writing to a new file f = open("demofile.txt", "x") # Create - will create a file, returns an error if the file exist f.write("Now the file has a new line") File Handling Delete a File To delete a file, import the OS module and run its os.remove function import os os.remove("demofile.txt") Check if File exist import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist") With statement 1. The "with" statement give better syntax and exceptions handling. 2. The "with" statement simplifies exception handling by encapsulating common preparation and cleanup tasks. 3. It will automatically close the file. The with statement provides 4. a way for ensuring that a clean-up is always used. # Reading file Check if File exist with open("welcome.txt") as file: # Use file to refer to the file object data = file.read() do something with data # Writing file with open("welcome.txt") as file: # Use file to refer to the file object file.read("Hello world") Package and Module Package and Modules in Python Introduction 1. Python has packages for directories and modules for files. 2. As application grows larger with a lot of modules, place similar modules in one package and different modules in different packages. This makes a project easy to manage. 3. Python package can have sub-packages and modules. 4. The directory must have a file named __init__.py in order for Python to consider the directory as a package. The __init__.py file can be left empty but usually the initialization code for the package is placed inside this file. Introduction To develop a game, one possible organization of packages and modules could be as shown in the figure as follows. Importing Module 1. The modules are imported using the dot (.) operator from packages 2. To import the play module in the sound package use the following code import Game.Sound.play 3. To access the function named "increase_volume()", the code must use the full name to reference it Game.Sound.play.increase_volume() 4. The above construct seems lengthy, import the module as follows without the package prefix from Game.Sound import play 5. Once the package is successful imported, the function can be called as follows play.increase_volume(5) 6. Another way to import is from Game.Sound.play import increase_volume now can directly call this function as increase_volume(5) Importing Module 1. Sometime it is not convenient to use the full module name python allow us to import module explicitly by alias as follows import Game.Sound.play as ply ply.increase_volume() 2. Sometimes it is very useful to import the entire module contents into the local namespace. This can be done with the "from … import *" from Game.Sound import * play.increase_volume() Importing Module Let’s assume the folders are root => main models services controllers 1. If the root folder is having the main file it would import the controllers as from controllers.filename import classname 2. Since main file is executing from root folder inside the controller file services can be imported as from services.filename import classname 3. Since main file is executing from root folder inside the service file models can be imported from models.filename import classname Python’s Standard Library Python's standard library contains many useful built-in modules Package Explanation Tools for interfacing with the operating system, including navigating file os and sys directory structures and executing shell commands math and cmath Mathematical functions and operations on real and complex numbers itertools Tools for constructing and interacting with iterators and generators functools Tools that assist with functional programming random Tools for generating pseudorandom numbers pickle Tools for object persistence: saving objects to and loading objects from disk json and csv Tools for reading JSON-formatted and CSV-formatted files. urllib Tools for doing HTTP and other web requests. Standard Library Standard Library in Python OS Module OS module in python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. The OS module include many functions to interact with the file system. 1. os.name: This function gives the name of the operating system dependent module imported. Registered names are 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos’ 2. os.getlogin(): This method is used to get the user who has logged inside the operating system. Example os.getlogin() 3. os.rename(): A file old.txt can be renamed to new.txt, using the function os.rename(). Example os.rename('old.txt', 'new.txt') OS Module - Directory A directory or folder is a collection of files and sub directories. Python has the os module, which provides us with many useful methods to work with directories (and files as well). 1. os.getcwd(): Function os.getcwd(), returns current working directory of the file used to execute the code, this can vary from system to system. 2. os.chdir(): Python’s OS module provides a function to change the current working directory. Forward slash (/) or the backward slash (\) is to separate path elements. Example os.chdir(r"C:\Users\Desktop\Python") 3. os.listdir(): Function os.listdir(), get all files and sub directories inside a directory can be known using the listdir() method. OS Module - Directory 4. os.mkdir(): Function os.mkdir() make a new directory. This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory. 5. os.rename(): The os.rename() method renames a directory. The first argument is the old name and the new name must be supplies as the second argument. os.rename('olddirectoryname', 'newdirectoryname') 6. os.rmdir(): Function os.rmdir(), method is used to remove the empty directory. get all files and sub directories inside a directory can be known using the listdir() method. 7. sys.path(): sys.path list directories in PYTHONPATH environment variable. You can add new modules path using sys.path.append(directoryname) OS Module - Environment Environment variables are global system variables accessible by all the processes running under the Operating System (OS). Environment variables are useful to store system