Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Notes

quick notes for python

Uploaded by

vinodgargrdfm
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Notes

quick notes for python

Uploaded by

vinodgargrdfm
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

What is 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
mathematics
system scripting.
Why Python?

• Python works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write
programs with fewer lines than some other programming
languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
Python Syntax compared to other programming languages

• Python was designed for readability, and has some similarities


to the English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to
other programming languages which often use semicolons or
parentheses.
• Python relies on indentation, using whitespace, to define
scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets for
this purpose.
Python Variables
• Variables: Variables are containers for storing data values.
• Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it. Variables do not need to be declared with any
particular type, and can even change type after they have been set. Example

.
Here x is int type and y is of str type

Python - Variable Names


A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Python - Global Variables
• Variables that are created outside of a function (as in all
of the examples above) are known as global variables.
• Global variables can be used by everyone, both inside
of functions and outside.
• Example:Create a variable outside of a function, and use it inside the
function.
Local-Global variable:
• If you create a variable with the same name inside a function, this
variable will be local, and can only be used inside the function. The global
variable with the same name will remain as it was, global and with the original
value.
Python Data Types
• Built-in Data Types: In programming, data type which type of data we
are storing.
• Variables can store data of different types, and different types can do different
things.
Getting and setting Datatype
• You can get the data type of any object by using the type() function.

Setting the Data Type:


Branching Statement:
• Branching in Python enables us to execute different statements based on different conditions.
• We can define multiple conditions using different methods, such as: "if-else" statements, where a
specific block of code is executed if a condition is met and another block of code is executed if the
condition is not met.
• Python Conditions and If statements
Python Loops

• Python has two primitive loop commands:


• while loops
• for loops
The while Loop
• With the while loop we can execute a set of statements
as long as a condition is true.
The break Statement

• With the break statement we can stop the loop even if


the while condition is true:
The continue Statement
• With the continue statement we can stop the current
iteration, and continue with the next:
Python For Loops

• A for loop is used for iterating over a sequence (that is


either a list, a tuple, a dictionary, a set, or a string).
• With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
Contd..
• Looping Through a String
Even strings are iterable objects, they contain a
sequence of characters:
The break Statement in for loop

• With the break statement we can stop the loop before it


has looped through all the items:
Python Arrays

• Python does not have built-in support for Arrays, but


Python Lists can be used instead.
• How to use LISTS as ARRAYS??? However, to work with
arrays in Python you will have to import a library, like
the NumPy library.
• Arrays are used to store multiple values in one single
variable.
What is an Array?
• An array is a special variable, which can hold more than one value at a time.
• If you have a list of items (a list of car names, for example), storing
the cars in single variables could look like this.

• However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is an array!
• An array can hold many values under a single name, and you can access the
values by referring to an index number.
Access the Elements of an Array
• You refer to an array element by referring to the index number.
The Length of an Array
• Use the len() method to return the length of an array (the number of
elements in an array).

Looping Array Elements:


You can use the for in loop to loop through all the elements of an array
Array methods:
•Adding Array Elements
You can use the append() method to add an element to an array.

• Removing Array Elements

You can use the pop() method to remove an element from the array. You can also
used remove () method for the same purpose.The list's remove() method only removes
the first occurrence of the specified value
Array Methods
• Python has a set of built-in methods that you can use
on lists/arrays.
List copy() Method

• The copy() method returns a copy of the specified list.

List count() Method:


The count() method returns the number of elements with the specified value.
List extend() Method

• The extend() method adds the specified list elements (or any iterable)
to the end of the current list.

List index() Method:


The index() method returns the position at the first occurrence of the specified value.
List insert() Method

• The insert() method inserts the specified value at the specified


position.

List reverse() Method:


The reverse() method reverses the sorting order of the elements.
Python Functions

• A function is 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.
• In Python a function is defined using the def keyword.Example-
def my_function():
print("Hello from a function")
• Calling a Function
To call a function, use the function name followed by parenthesis:
Contd..
• Arguments
• Information can be 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.
• The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Number of Arguments

• By default, a function must be called with the correct number of arguments.


Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.

If you try to call the function with 1 or 3 arguments, you will get an error.
Arbitrary Arguments, *args

• If you do not know how many arguments that will be passed into your
function, add * before the parameter name in the function definition.

Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.
Arbitrary Keyword Arguments, **kwargs

• If you do not know how many keyword arguments that will be passed
into your function, add two asterisk: ** before the parameter name in
the function definition.

Default Parameter Value


The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Passing a List as an Argument

• You can send any data types of argument to a function


(string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
The pass Statement

• Function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to
avoid getting an error.
Python Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one
expression.
• Syntx:
lambda arguments : expression
Python Collections (Arrays)
• There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable(add and remove
can be done), and unindexed. No duplicate members.
• Dictionary is a collection which is ordered(python 3.6 dictionary are
unordered) and changeable. No duplicate members.
Python Lists

• Lists are used to store multiple items in a single


variable.
• Lists are one of 4 built-in data types in Python used
to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
• Lists are created using square brackets.
List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1]
etc.
Ordered
• When we say that lists are ordered, it means that the items have
a defined order, and that order will not change.
• If you add new items to a list, the new items will be placed at the
end of the list.
Changeable
• The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.
Allow Duplicates
• Since lists are indexed, lists can have items with the same value.
Contd..
• List Length
To determine how many items a list has, use the len() function:

• List Items - Data Types


List items can be of any data type.
A list can contain different data types.

type()
From Python's perspective, lists are defined as objects with the data type 'list'
The list() Constructor

• It is also possible to use the list() constructor when


creating a new list.
Python - Access List Items
• Access Items
List items are indexed and you can access them by referring to the index
number:

Negative Indexing:
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.

Range of Indexes:
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

Note:The search will start at index 2 (included) and end at index 5 (not included).
Contd..
We can access from starting by leaving out start value.The range will start at the first
item

By leaving out the end value, the range will go on to the end of the list:

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list
Python - Change List Items
• Change Item Value
To change the value of a specific item, refer to the index number.

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:

Note: If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly.
Python - Add List Items
• Append Items
To add an item to the end of the list, use the append() method:

Insert Items
To insert a list item at a specified index, use the insert() method.The insert() method inserts an item at the
specified index.

Extend List
To append elements from another list to the current list, use the extend() method.
Python - Remove List Items
• Remove Specified Item:
The remove() method removes the specified item.

Remove Specified Index


The pop() method removes the specified index.

If you do not specify the index, the pop() method removes the last item.
del keyword:
The del keyword also removes the specified index
Contd..
• The del keyword can also delete the list completely.

• Clear the List


The clear() method empties the list.The list still remains, but it has no content.

Python - Sort Lists:


Sort List Alphanumerically.List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Contd..
• Sort Descending
To sort descending, use the keyword argument reverse = True.
Python Tuples
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item,
otherwise, Python will not recognize it as a tuple.
Contd..
Access Tuple Items
• You can access tuple items by referring to the index number,
inside square bracket
Negative Indexing
• Negative indexing means start from the end.-1 refers to the last item, -2 refers
to the second last item etc.
Range of Indexes
• You can specify a range of indexes by specifying where to start
and where to end the range.
• When specifying a range, the return value will be a new tuple
with the specified items.
Python - Update Tuples
• Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created.
• But there are some workarounds
Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
• But,can convert the tuple into a list, change the list, and convert the list back
into a tuple.
Add Items and Remove Items
Add items:
Since tuples are immutable, they do not have a build-in append() method, but there are other ways
to add items to a tuple.
Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.

Remove Items:
Tuples are unchangeable, so you cannot remove items from it, but you can use the
same workaround as we used for changing and adding tuple items:
Python - Join Tuples

• Join Two Tuples


To join two or more tuples you can use the + operator.

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use the * operator
Python Sets
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Sets are written with curly brackets.
• Note: Set items are unchangeable, but you can remove items and add new
items.Sets are unordered, so you cannot be sure in which order the items will
appear.

Duplicates Not Allowed:


Sets cannot have two items with the same value
Python - Access Set Items
• Access Items
You cannot access items in a set by referring to an index or a key.But you can loop through the set
items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Python - Add Set Items:


Once a set is created, you cannot change its items, but you can add new items.
Add an item to a set, using the add() method.

Add Sets:
To add items from another set into the current set, use the update() method.
Python - Remove Set Items
• Remove Item
• To remove an item in a set, use the remove(), or the discard() method.

Note:
If the item to remove does not exist, remove() will raise an error.

Note: If the item to remove does not exist, discard() will NOT raise an error.
Pop():
You can also use the pop() method to remove an item, but this method will remove a random item, so
you cannot be sure what item that gets removed.
Del() and clear() keyword in SETS
Python - Join Sets
• Join Two Sets
There are several ways to join two or more sets in Python.You can use the union() method that
returns a new set containing all items from both sets, or the update() method that inserts all the
items from one set into another:

The update() method inserts the items in set2 into set1


Keep ONLY the Duplicates

The intersection_update() method will keep only the items that are present in both sets.

Keep All, But NOT the Duplicates.


The symmetric_difference_update() method will keep only the elements that are NOT present in
both sets.
Python Dictionaries
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*,changeable and do not allow
duplicates.
• Dictionaries are written with curly brackets, and have keys and values:

Accessing Items:
You can access the items of a dictionary by referring to its key name, inside square
brackets.

There is also a method called get() that will give you the same result
Contd..
• Get Keys
The keys() method will return a list of all the keys in the dictionary.

Get Values
The values() method will return a list of all the values in the dictionary.
Contd..
• Get Items:
The items() method will return each item in a dictionary, as tuples in a list.

Python - Change Dictionary Items:


Change Values
You can change the value of a specific item by referring to its key name.
Contd..
• Update Dictionary
• The update() method will update the dictionary with the items from the given argument.
• The argument must be a dictionary, or an iterable object with key:value pairs

Python - Remove Dictionary Items:


There are several methods to remove items from a dictionary
CONTD..
• The clear() method empties the dictionary

• The del keyword removes the item with the specified key name.

• The del keyword can also delete the dictionary completely

• The clear() method empties the dictionary:


Just leave the curly braces{ }
Applications of Python:
• Web Development: Python is widely used for web development as it offers multiple web
frameworks like Django, Flask, Pyramid, etc. These frameworks make web development easier
and faster.
• Data Science: Python is one of the most popular languages for data science and machine
learning. It has a rich set of libraries like NumPy, Pandas, SciPy, and Scikit-learn that are widely
used for data analysis, visualization, and modeling.
• Artificial Intelligence: Python is extensively used in AI and Machine Learning. It is the primary
language for popular AI frameworks like TensorFlow, PyTorch, and Keras.
• Game Development: Python is used for developing games as it provides powerful game
development libraries like Pygame, Panda3D, and PyOgre.
• Desktop Application Development: Python is used for creating cross-platform desktop
applications. Libraries like Tkinter, PyQt, and wxPython are used for developing desktop
applications.
• Scientific Computing: Python is extensively used for scientific computing and numerical
analysis. It has a large number of libraries like NumPy, SciPy, and Matplotlib that make
scientific computing easier.
• Automation: Python is used for automation tasks like web scraping, testing, and network
programming.
• Education: Python is a simple and easy-to-learn language, making it an ideal language for
teaching programming in schools and universities.

You might also like