The document provides an introduction to Python programming. It discusses key concepts like variables, data types, operators, and sequential data types. Python is presented as an interpreted programming language that uses indentation to indicate blocks of code. Comments and documentation are included to explain the code. Various data types are covered, including numbers, strings, booleans, and lists. Operators for arithmetic, comparison, assignment and more are also summarized.
Introduction to the presentation and speaker, Ashwin Kumar Ramaswamy discussing Python.
Examples of technologies reliant on programming: Google Assistant, Ms. Sofia, Cortana; emphasizing the necessity of programming.
Definition and purpose of programming languages; used in computer programming to implement algorithms.
Introduction to Python, benefits, and its uses in web development, software development, and machine learning.
Installing Python IDLE and basic syntax, including an example of code execution in Python.
Differences of indentation in Python and usage of comments for code readability; examples shown.
Definition and examples of data; explanation of data types and how to create variables in Python.
Assigning values to variables, type checking, and examples of legal and illegal variable names.
Introduction to input() methods, casting data types, and outputting data using print statements in Python.
Definition and examples of Python keywords and built-in functions that simplify tasks.
Introduction to various data types in Python, including Numbers and Strings.
Overview of string types in Python, their properties, and examples of string manipulation.
Various operations on strings including slicing, modification, formatting, and concatenation.
Introduction to Boolean values, evaluation of expressions, and types of operators in Python.
Classes of operators including arithmetic, assignment, comparison, logical, identity, membership, and bitwise.
Understanding Lists and their characteristics; covered list creation, indexing, and list methods.
Description of tuples and sets, their definitions, qualities, and differences from lists.
Explanation of dictionaries, their structure of key:value pairs, and characteristics.
Discusses conditional statements including if, elif, and else; introduces nested if statements.
Overview of loops; explanation of while and for loops, including break and continue statements.Definition of functions, how to create and call them, and an explanation of parameters.
Introduction to OOP concepts, including classes, objects, and the significance in Python.
How to create a class and its object, along with an introduction to the init() function.
Description and types of inheritance including single, multilevel, and multiple inheritance.
Explanation of encapsulation, its benefits, and an example demonstrating it with classes.
Definition of polymorphism, including method overriding and operator overloading.
Discussion on recursion vs iteration, with examples for each approach in code.
Definition and examples of variable scope; global, local scopes, and how to use global keyword.Introduction to modules in Python, how to create and use them.
Introduction to datetime module, and built-in math functions for mathematical operations.
Overview of PIP, its purpose, and instructions on checking and installing PIP.
Instructions on importing and utilizing a package in Python.
Introduction to error handling using try and except blocks in Python.Explanation of handling user input in Python through the input() method.
Overview of file handling in Python; methods to read, write, and delete files.
What are Programming and Languages? ⮚A programming language is a formal language comprising a set of instructions that produce various kinds of output. ⮚Programming languages are used in computer programming to implement algorithms.
5.
Here we're goingto see about Python Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: Web development (server-side) Software development System scripting Machine Learning, Data Science This Photo by Unknown author is licensed under CC BY-SA.
6.
1. Installation Install thePython IDLE using this link - https://www.python.org/downloads/ Version - python 3
7.
2. Syntax 1.It isan interpreted language, we can run our code snippets in python shell. 2.File Extension - .py >>> print("Hello, World!") Hello, World!
8.
3. Python Indentation 1.Indentation refers to the spaces at the beginning of a code line. 1. Python uses indentation to indicate a block of code. if 10> 5: print("Ten is greater than five!")
9.
Thank you forwatching ! Next session, 1. Variables 2. Data types 3. Casting and Numbers.
4. Comments 1.Comments canbe used to prevent execution when testing code. 2.Comments can be used to make the code more readable. Single Line Comment - # print("Hello, World!") #This is a comment Multiline Comment - ‘’’ Hello World !!! ‘’’
12.
5. Data Data isdefined as facts or figures, or information that's stored in or used by a computer. Ex: Name: Ashwin R Course: Information Technology
13.
6. Data Types DataType is the type of data Primary Data Types - Number, String, Boolean, Float, Complex Secondary Data Types - Set, List, Dictionary, Tuple. Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool
14.
7. Variables Variables arecontainers for storing data values. Creating Variables 1. Python has no command for declaring a variable. 2. A variable is created the moment you first assign a value to it. X = 5 Y = "python" print(X) print(Y)
15.
7.1 Variable Names 1.Avariable 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 alpha-numeric characters and underscores (A-z, 0-9, and _ ) 4.Variable names are case-sensitive (age, Age and AGE are three different variables)
7.4 Many Valuesto Multiple Variables Python allows you to assign values to multiple variables in one line x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z)
19.
7.5 One Valueto Multiple Variables You can assign the same value to multiple variables in one line: x = y = z = "Orange" print(x) print(y) print(z)
20.
7.6 Type ofvariable Using Type() build in function, we can get the data type of the variable >>>a= 5 >>>Type(a) integer >>> b=”Ashwin234” >>>Type(b) string
21.
Thank you forwatching ! Next session, 1. Input and Outputs 2. Casting 3. Keywords
8. Input Input isthe basic command or signal to the machine to perform several tasks. Getting User Input in python input() is the build in method to get input from user Syntax : input(“Enter the Name:”) int(input(“Enter the Age:”)) 1. Default input data type is String. 2. To get the desired type of input, we need to do casting.
24.
9. Casting orType Casting If you want to specify the data type of variable, this can be done with casting. x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0
25.
10. Output Outputs arethe amount of something that produced due to some operations. The Python print statement is often used to output variables. a=input(“Enter your Name:”) # User Input ---> Ashwin print(a) # Prints---> Ashwin
26.
11. Keywords andBuild in functions Keywords are reserved words that having some specific meaning Ex - print, int, bool, str, float, return, global, import, from etc. Build in functions - These are also predefined functions, which is highly helpful to reduce the complex tasks. Ex - sum(), abs(), type(), def(), etc. (Will see it elaborately in upcoming classes)
13.2 Strings areArrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. a = "Hello, World!" print(a[1])
32.
13.3 Looping Througha String Since strings are arrays, we can loop through the characters in a string, with a for loop. for x in "Ashwin": print(x) 13.3.1 String Length To get the length of a string, use the len() function. a = "Hello, World!" print(len(a))
33.
13.4 Check String Tocheck if a certain phrase or character is present in a string, we can use the keyword in. txt = "The best things in life are free!" if “free in text: print(“Yes free word is present !”)
34.
13.5 Slicing You canreturn a range of characters by using the slice syntax. 1.Specify the start index and the end index, separated by a colon, to return a part of the string. b = "Hello, World!" print(b[2:5]) 2. Slicing from Start 3. Slice To the End b=”Python” c=”Python” print(b[:4]) print(b[2:])
35.
13.5.1 Negative Indexing Usenegative indexes to start the slice from the end of the string: b = “World!" print(b[-3:-1])
36.
Thank you forwatching ! Next session, 1. String Methods (Part 2) 2. Boolean Type 3. Operators
13.6. Modify Strings 1.Upper Case a = "Hello, World!" print(a.upper()) 1. Lower Case a = "Hello, World!" print(a.lower())
39.
13.6.1 Remove Whitespace Whitespaceis the space before and/or after the actual text, and very often you want to remove this space. a = " Hello, World! " print(a.strip())
13.6.3 Split String Thesplit() method returns a list where the text between the specified separator becomes the list items. a = "Hello, World!" print(a.split(","))
42.
13.7 String Concatenation Toconcatenate, or combine, two strings you can use the + operator. a = "Hello" b = "World" c = a + b print(c)
43.
13.7.1 String Format Theformat() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are age = 36 txt = "My name is John, and I am {}" print(txt.format(age))
14.1 Evaluate Valuesand Variables The bool() function allows you to evaluate any value, and give you True or False in return x = "Hello" y = 15 print(bool(x)) print(bool(y))
46.
15. Operators Operators areused to perform operations on variables and values. In the example below, we use the + operator to add together two values a = 1+2 # + is an arithmetic operator print(a) if (2==2) # == is a relational operator if 2>1 # > is a comparison operator etc .
47.
Thank you forwatching ! Next session, 1. Operators part 2 2. Sequential Data Types 3. List (Part 1)
15.2 Arithmetic Operator +Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
51.
15.3 Assignment Operator =x = 5 += x += 3 -= x -= 3 *= x *= 3 /= x /= 3 %= x %= 3 //= x //= 3 **= x **= 3 &= x &= 3
52.
15.4 Comparison Operator ==Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
53.
15.5 Logical Operators andReturns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
54.
15.6 Identity Operators Identityoperators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y
55.
16.7 Membership Operator Membershipoperators are used to test if a sequence is presented in an object in Returns True if a sequence with the specified value is present in the object Ex . x in y not in Returns True if a sequence with the specified value is not present in the object Ex. x not in y
56.
15.8 Bitwise Operator Bitwiseoperators are used to compare (binary) numbers & 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 << Zero fill left shift. Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift. Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
16. Lists Languages= ["Python",”C” , ”Java”] 1.Lists are used to store multiple items in a single variable. 2.Lists are one of 4 built-in data types in Python used to store collections of data
59.
16.1 List items 1.Listitems are ordered, changeable, and allow duplicate values. 2.List items are indexed, the first item has index [0], the second item has index [1] etc
60.
16.2 List length Languages=[“Python”,”C”,”C++”,”Java”] print(len(Languages)) 16.3 List Items - Data Types details=[“Ashwin”,21,”Chennai”,8.3,True]
61.
16.3 List() Constructor Itis also possible to use the list() constructor when creating a new list. details = list((“Ashwin”,21,”Chennai”))
62.
16.4 List Accessing Listitems are indexed and you can access them by referring to the index number Details=[“Ashwin”,21,”Chennai”] print(Details[0]) 16.4.1 Negative Indexing thislist = ["apple", "banana", "cherry"] print(thislist[-1])
63.
Thank you forwatching ! Next session, 1. List Methods (part 2) 2. Tuples 3. Tuples Methods (Part 1)
16.6 List thislist =["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist)
67.
17 Tuples Tuples areused to store multiple items in a single variable. mytuple = ("apple", "banana", "cherry") Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets
68.
18. Sets myset ={"apple", "banana", "cherry"} Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is both unordered and unindexed. Sets are written with curly brackets.
69.
19. Dictionaries thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
19. Conditional Statements:If..elif..else An "if statement" is written by using the if keyword. a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")
72.
19.2 Short handIf..Else a = 2 b = 330 print("A") if a > b else print("B")
73.
19.3 Nested IF x= 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.")
74.
19.4 pass statement ifstatements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. a = 33 b = 200 if b > a: pass
75.
Thank you forwatching ! Next session, 1. Looping Statement 2. OOPs
20.1 While Loop Withthe while loop we can execute a set of statements as long as a condition is true. Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1
79.
20.2 Break Statement Withthe break statement we can stop the loop even if the while condition is true: Example Exit the loop when i is 3: i = 1 while i < 6: print(i) if i == 3: break i += 1
80.
20.3 For Loop Afor loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
81.
20.3.1 Looping throughString Even strings are iterable objects, they contain a sequence of characters: Example Loop through the letters in the word "banana": for x in "banana": print(x)
82.
20.4 Continue Statement Withthe continue statement we can stop the current iteration of the loop, and continue with the next: Example Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
83.
20.5 Range() function Toloop through a set of code a specified number of times, we can use the range() function, range(start,stop,step) for x in range(6): print(x) for x in range(2, 6): print(x) for x in range(2, 30, 3): print(x)
84.
20.6 Nested Loops Anested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop" adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
85.
20.7 pass statement forloops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. for x in [0, 1, 2]: pass
86.
21. Functions A functionis a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Creating Function In Python a function is defined using the def keyword: def my_function(): print("Hello from a function")
87.
21.1 Function Call Tocall a function, use the function name followed by parenthesis: def my_function(): print("Hello from a function") my_function()
88.
21.2 Arguments Information canbe passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus")
89.
Thank you forwatching ! Next session, 1. Functions (part 2) 2. Anonymous Functions 3. OOPs
90.
21.2 Arbitrary Arguments Ifyou do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus"
91.
21.3 keyword arguments Youcan also send arguments with the key = value syntax def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
92.
21.4 Arbitrary KeywordArguments, **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. def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes")
93.
21.5 Default ParameterValue def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")
94.
Lambda Functions A lambdafunction is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. lambda arguments : expression x = lambda a : a + 10 print(x(5))
What is OOP? Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behaviour. Additional benefits of OOP include code reusability, scalability and efficiency.
97.
Pillars of OOP 1.Encapsulation 2. Abstraction 3. Inheritance 4. Polymorphism
98.
Class and Objects Pythonis an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
13. __init__() The examplesabove are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes, we have to understand the built-in __init__() function. All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created
13.1 Object Methods Objectscan also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name)
106.
13.2 The SelfParameter The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class
107.
Ex. class Person: def __init__(mysillyobject,name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc()
108.
14. Inheritance Inheritance allowsus to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
14.2 Single LevelInheritance When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.
112.
14.3 Multilevel Inheritance Multilevelinheritance in java with example. When a class extends a class, which extends anther class then this is called multilevel inheritance. For example class C extends class B and class B extends class A then this type of inheritance is known as multilevel inheritance.
113.
14.4 Multiple Inheritance Multipleinheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class
114.
Thank you forwatching ! Next session, 1. OOP concepts (Part 3)
115.
15. Encapsulation Encapsulation inPython is the process of wrapping up variables and methods into a single entity. In programming, a class is an example that wraps all the variables and methods defined inside it
16.Polymorphism The word polymorphismmeans having many forms. In programming, polymorphism means the same function name (but different signatures) being used for different types.
118.
15.1 Method Overloading Methodoverloading is a form of polymorphism in OOP. One such manner in which the methods behave according to their argument types and number of arguments is method overloading. Overloading happens when you have two methods with the same name but different signatures (or arguments).
119.
class Student(): def __init__(self,a,b): self.a=a self.b=b defsum(self,a=None,b=None,c=None): s=0 if(a!=None and b!=None and c!=None): s=a+b+c elif (a!=None and b!=None): s=a+b else: s=c return s s1=Student(50,30) print(s1.sum(20,30)) print(s1.sum(20,30,10)) print(s1.sum(20))
120.
15.2 Method Overriding Methodoverriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
Operator Overloading Operator overloadingin Python is the ability of a single operator to perform more than one operation based on the class (type) of operands. For example, the + operator can be used to add two numbers, concatenate two strings or merge two lists.
123.
16. Recursion The termRecursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly.
Iteration Iterations are performedthrough 'for' and 'while' loops. Iterations execute a set of instructions repeatedly until some limiting criteria is met. In contrast to recursion, iteration does not require temporary memory to keep on the results of each iteration.
126.
Scopes A variable isonly available from inside the region it is created. This is called scope. Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. def myfunc(): x = 300 print(x) myfunc()
127.
Function Inside Function Asexplained in the example above, the variable x is not available outside the function, but it is available for any function inside the function: def myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc()
128.
Global Scope A variablecreated in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local. x = 300 def myfunc(): print(x) myfunc() print(x)
129.
Global Keyword If youneed to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global def myfunc(): global x x = 300 myfunc() print(x)
130.
Modules Consider a moduleto be the same as a code library. A file containing a set of functions you want to include in your application.
131.
Create a Module Tocreate a module, just save the code you want in a file with the file extension .py def greeting(name): print("Hello, " + name)
132.
Use a module Nowwe can use the module we just created, by using the import statement: import mymodule mymodule.greeting("Jonathan")
133.
Date time A datein Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. import datetime x = datetime.datetime.now() print(x)
134.
Math Python has aset of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers. Build in Math functions The min() and max() functions can be used to find the lowest or highest value in an iterable
The abs() functionreturns the absolute (positive) value of the specified number x = abs(-7.25) print(x) The pow(x, y) function returns the value of x to the power of y (x^y) x = pow(4, 3) print(x)
137.
Math module Python hasalso a built-in module called math, which extends the list of mathematical functions. To use it, you must import the math module import math x = math.sqrt(64) print(x)
138.
PIP (Python Managerfor Packages) PIP is a package manager for Python packages, or modules if you like. What is a Package? A package contains all the files you need for a module. Modules are Python code libraries you can include in your project.
139.
Check if PIPis Installed Navigate your command line to the location of Python's script directory, and type the following C:UsersYour NameAppDataLocalProgramsPythonPython36-32Scripts>pip -- version
140.
Install PIP If youdo not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
141.
Using a Package Oncethe package is installed, it is ready to use. Import the "camelcase" package into your project. import camelcase c = camelcase.CamelCase() txt = "hello world" print(c.hump(txt))
142.
Exception Handling The tryblock lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
143.
try statement When anerror occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement: try: print(x) except: print("An exception occurred")
144.
Many Exceptions You candefine as many exception blocks as you want, e.g. if you want 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: print("Something else went wrong")
145.
User Input Python allowsfor user input. That means we are able to ask the user for input. The method is a bit different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method.
File Handling File handlingis an important part of any web application. Python has several functions for creating, reading, updating, and deleting files. The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:
148.
There are fourdifferent 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
Open a Fileon the Server f = open("demofile.txt", "r") print(f.read())
151.
Write to anExisting File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content
152.
f = open("demofile2.txt","a") f.write("Now the file has more content!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())
153.
Create a NewFile "x" - Create - will create a file, returns an error if the file exist f = open("myfile.txt", "x")
154.
Delete a File Todelete a file, you must import the OS module, and run its os.remove() function: import os os.remove("demofile.txt")