Python
Python
( Knowledge For U )
Prasad
Co founder & CEO 2017
IOT Developer
M : 9182976493
Email : k4uinfo@gmail.com
Using C programming
// C program to add two numbers
#include<stdio.h>
int main()
{
int A, B, sum = 0;
return 0;
}
Using python
Python used by
python Applications
Tools for Implementing python code
Installing
python Software
Download Python from the below link:
https://www.python.org/downloads/
Step: We will be brought to another page, where we will need to select either
the x86-64 or amd64 installer to install Python.
We use here Windows x86-64 executable installer.
Check
python version
Python Introduction
What is Python?
Output :
Python Indentation (cont..)
Example 2:
The number of spaces is up to you as a programmer, but it has to be at least one.
Example 3:
• You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Example 4:
Python Comments
Python Comments
Example 1:
#This is a comment
print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example 2:
print("Hello, World!") #This is a comment
• Comments does not have to be text to explain the code, it can also be used to prevent Python
from executing code:
Example 3:
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
Python does not really have a syntax for multi line comments.
Example 4:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Python Variables
Creating Variables:
• Variables are containers for storing data values.
• 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.
Example 1:
• Variables do not need to be declared with any particular type and can even
change type after they have been set.
Example 2:
String variables can be declared either by using single or
double quotes:
Example 3:
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Example 4:
And you can assign the same value to multiple variables in one line:
Example 5:
Output Variables
Example 6:
• You can also use the + character to add a variable to another variable:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Getting the Data Type
You can get the data type of any object by using the type() function:
Setting the Data Type
Setting the Specific Data Type
Python Numbers
Python Numbers
• Complex : Complex numbers are written with a "j" as the imaginary part:
(z = 1j )
Type Conversion
• You can convert from one type to another with the int(), float(), and complex() methods:
Note: You cannot convert complex numbers into another number type.
Random Number
• Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make
random numbers:
Python Strings
String Literals
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and,
it could mean an increase in efficiency or security.
Python Collections - List
Python - List
• List items are indexed, the first item has index [0], the second item has
Ordered : When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
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
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:
type()
Access Items :
• List items are indexed and you can access them by referring to the index number:
Note: The search will start at index 2 (included) and end at index 5 (not included).
Example: This example returns the items from the beginning to, but NOT including, "kiwi":
Example : This example returns the items from "cherry" to the end:
Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end of the list:
Example : This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
Check if Item Exists
• 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:
Example : Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
If you insert more items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:
Example : Change the second value by replacing it with two new values:
If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example : Change the second and third value by replacing it with one value:
Insert Items :
• To insert a new list item, without replacing any of the existing values,
we can use the insert() method.
• The insert() method inserts an item at the specified index:
Append Items :
To add an item to the end of the list, use the append() method:
• If you do not specify the index, the pop() method removes the last item.
Example : Remove the last item:
• The del keyword also removes the specified index:
Example : Remove the first item:
Method Description
append() Adds an element at the end of the list
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 elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
• Tuple items are indexed, the first item has index [0], the second
Allow Duplicates : Since tuples are indexed, they can have items with the same value:
Example : Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() method:
Create Tuple With One Item
• To create a tuple with only one item, you have to add a comma after
• From Python's perspective, tuples are defined as objects with the data
type 'tuple':
<class 'tuple'>
• You can access tuple items by referring to the index number, inside
square brackets:
Note: The search will start at index 2 (included) and end at index 5 (not included).
• By leaving out the start value, the range will start at the first item:
Example : This example returns the items from the beginning to, but NOT
included, "kiwi":
• By leaving out the end value, the range will go on to the end of the list:
Example : This example returns the items from "cherry" and to the end:
Range of Negative Indexes
Example : This example returns the items from index -4 (included) to index -1
(excluded)
Check if Item Exists :
• To determine if a specified item is present in a tuple use the in keyword:
• Syntax :
if “item" in tuple:
condition
• Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items
• Python has two built-in methods that you can use on tuples.
Method Description
tuple
index() Searches the tuple for a specified value and returns the
• To determine how many items a set has, use the len() method.
Set Items - Data Types
• Set items can be of any data type:
• From Python's perspective, sets are defined as objects with the data
type 'set':
<class 'set'>
Example : What is the data type of a set?
Python - Access Items
Example:
Loop through the set, and print the values:
Example:
Check if "banana" is present in the set:
Change Items
• Once a set is created, you cannot change its items, but you can add
new items.
Python - Add Set Items
Add Items:
• Once a set is created, you cannot change its items, but you can add new items.
• To add more than one item to a set use the update() method.
Example: Example:
Remove "banana" by using the discard() method:
Remove "banana" by using the remove() method:
Example : The union()/ update() method returns a new set with all items from both
sets:
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
intersection_update() Removes the items in this set that are not present in other, specified set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Python Collections - Dictionaries
Python - Dictionaries
• Dictionary items are ordered, changeable, and do not allow duplicate values.
• Dictionary items are indexed, the first item has index [0], the second item has
• Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
• Ordered : When we say that dictionaries are ordered, it means that the items have a
• Changeable : Dictionaries are changeable, meaning that we can change, add or remove
• Duplicates Not Allowed : Dictionaries cannot have two items with the same key:
Dictionary Length
• To determine how many items a dictionary has, use the len() function:
<class 'dict'>
Get Items :
• The items() method will return each item in a dictionary, as tuples in a list.
• The keys() method will return a list of all the keys in the dictionary.
• There is also a method called get() that will give you the same result:
Change Values :
• You can change the value of a specific item by referring to its key name:
• 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.
Example : Update the "year" of the car by using the update() method:
Python - Add Dictionary Items
Adding Items :
• Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
Example :
Update Dictionary :
• The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
• The argument must be a dictionary, or an iterable object with key:value pairs.
Example : Add a color item to the dictionary by using the update() method:
Python - Remove Dictionary Items
Removing Items :
• There are several methods to remove items from a dictionary:
pop() method :
• The pop() method removes the item with the specified key name:
Example :
popitem() method
• The popitem() method removes the last inserted item
Example :
del() method
• The del keyword removes the item with the specified key name:
Example :
• The del keyword can also delete the dictionary completely:
clear() method
• The clear() method empties the dictionary:
Example:
Infotech
( Knowledge For U )
Banoth Prasad
Co founder & CEO 2017
IOT Developer
M : 9182976493
Email : k4uinfo@gmail.com
Python File - Handling
Python File - Handling
"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
In addition you can specify if the file should be handled as binary or text mode
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "r")
f = open("demofile.txt", "rt“)
• Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
Note: Make sure the file exists, or else you will get an error.
Python File Open - Open a File on the Server
• Assume we have the following file, located in the same folder as Python:
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many characters
you want to return:
By calling readline() two times, you can read the two first lines:
By looping through the lines of the file, you can read the whole file, line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
Python File Write - Write to an Existing 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
f = open("demofile2.txt", "a")
f.write(“B Prasad Python class!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Python File Write - overwrite the content
f = open("demofile3.txt", "w")
f.write(" Prasad - Add content!")
f.close()
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example:
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example:
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Python Delete File - Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Syntax : input(prompt)
Example 1:
Example 2:
Example 3:
Example 4:
Python Strings
Python - String
• You can assign a multiline string to a variable by using three quotes (single
or double):
• Python has a set of built-in methods that you can use on strings.
• Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
• The strip() method removes any whitespace from the beginning or the end:
Example :
Replace String
Example :
Split String
• The split() method returns a list where the text between the specified separator
becomes the list items.
• The split() method splits the string into substrings if it finds instances of the
separator:
• The capitalize() method returns a string where the first character is upper
case, and the rest is lower case.
• The casefold() method returns a string where all the characters are lower case.
Python - Format - Strings
• But we can combine strings and numbers by using the format() method!
• The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
Python Conditions :
• Equals: a == b
• Not Equals: a != b
Example: If statement
Else
In this example a is greater than b, so the first condition is not true, so we go to the else condition
and print to screen that "a is greater than b"
And - Keyword
Example :
Python - While/For Loops
Python Loops :
• while loops
• for loops
Python - While Loops
• With the break statement we can stop the loop even if the while
condition is true:
• With the continue statement we can stop the current iteration, and
continue with the next:
• With the else statement we can run a block of code once when the
condition no longer is true:
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Infotech
( Knowledge For U )
Banoth Prasad
CEO & CO- Founder 2017
Developer
M/W : 9182976493
Email : k4uinfo@gmail.com
Pip (preferred installer program)
What is PIP?
Note: If you have Python version 3.4 or later, PIP is included by default.
What is a Package?
Modules are Python code libraries you can include in your project.
Check if PIP is Installed
Prerequisite: Python
jupytper notebook
working on jupyter
https://jupyter.readthedocs.io/en/latest/running.html#running
Updating Jupyter:
Banoth Prasad
CEO & CO- Founder 2017
Developer
M/W : 9182976493
Email : k4uinfo@gmail.com
Packages
Pandas, numpy,
Matplotlib, OS, seaborn
pandas
A standard Python package for analyzing and manipulating data is pandas.
• Pandas is part of the Anaconda distribution and can be installed with Anaconda
https://pandas.pydata.org/docs/pandas.pdf
NUMPY
• NumPy is a general-purpose array-processing package. It provides a high-
performance multidimensional array object, and tools for working with these arrays. It
is the fundamental package for scientific computing with Python. ... A powerful N-
dimensional array object.
https://numpy.org/doc/stable/user/whatisnumpy.html
matplotlib
Matplotlib: Visualization with Python
https://matplotlib.org/
https://matplotlib.org/tutorials/introductory/images.html#sphx-glr-tutorials-introductory-images-py
• Install Matplotlib with pip:
• pip install os
• conda install os
Seaborn
Seaborn is a Python data visualization library based on matplotlib. It provides a
high-level interface for drawing attractive and informative statistical graphics.
http://seaborn.pydata.org/tutorial.html#
http://seaborn.pydata.org/installing.html
Infotech
( Knowledge For U )
Banoth Prasad
CEO & CO- Founder 2017
Developer
M/W : 9182976493
Email : k4uinfo@gmail.com