0% found this document useful (0 votes)
26 views

B Prasad - Basic Python Programming

Uploaded by

yepixi8546
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

B Prasad - Basic Python Programming

Uploaded by

yepixi8546
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 186

Infotech

( Knowledge For U )

Banoth Prasad
Co founder & CEO 2017
Prasad Banoth
IOT Developer
M : 9182976493
K4U Infotech
Email : k4uinfo@gmail.com
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Using C programming
// C program to add two numbers
#include<stdio.h>

int main()
{
int A, B, sum = 0;

// Ask user to enter the two numbers


printf("Enter two numbers A and B : \n");

// Read two numbers from the user || A = 5, B = 7


scanf("%d%d", &A, &B);

// Calclulate the addition of A and B


// using '+' operator
sum = A + B;

// Print the sum


printf("Sum of A and B is: %d", sum);

return 0;
}

Prasad Banoth K4U Infotech


(Knowledge for U)
Using python

Prasad Banoth K4U Infotech


(Knowledge for U)
Python used by

Prasad Banoth K4U Infotech


(Knowledge for U)
python Applications

Prasad Banoth K4U Infotech


(Knowledge for U)
Tools for Implementing python code

Prasad Banoth K4U Infotech


(Knowledge for U)
Installing
python Software

Prasad Banoth K4U Infotech


(Knowledge for U)
Download Python from the below link:

https://www.python.org/downloads/

Prasad Banoth K4U Infotech


(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Check
python version

Prasad Banoth K4U Infotech


(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Python Introduction

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
What can Python do?

• Python can be used on a server to create web applications.


• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify
files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.

Prasad Banoth K4U Infotech


(Knowledge for U)
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-orientated
way or a functional way.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Indentation

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Indentation

• Indentation refers to the spaces at the beginning of a code line.

• Where in other programming languages the indentation in code is for

readability only, the indentation in Python is very important.

• Python uses indentation to indicate a block of code.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Indentation (cont..)
Example 1:

Output :

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Indentation (cont..)

• Python will give you an error if you skip the indentation:

Example 2:

Prasad Banoth K4U Infotech


(Knowledge for U)
The number of spaces is up to you as a programmer, but it has to be at least one.

Example 3:

Prasad Banoth K4U Infotech


(Knowledge for U)
• You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

Example 4:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Comments

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Comments

• Comments can be used to

• explain Python code.

• make the code more readable.

• prevent execution when testing code.

Prasad Banoth K4U Infotech


(Knowledge for U)
Creating a Comment

Comments starts with a #, and Python will ignore them:

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!")

Prasad Banoth K4U Infotech


(Knowledge for U)
Multi Line Comments

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example 4:

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Variables

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
• Variables do not need to be declared with any particular type and can even
change type after they have been set.

Example 2:

Prasad Banoth K4U Infotech


(Knowledge for U)
String variables can be declared either by using single or
double quotes:

Example 3:

Prasad Banoth K4U Infotech


(Knowledge for U)
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)

Prasad Banoth K4U Infotech


(Knowledge for U)
Assign Value to Multiple Variables

• Python allows to assign values to multiple variables in one line:

Example 4:

Prasad Banoth K4U Infotech


(Knowledge for U)
And you can assign the same value to multiple variables in one line:

Example 5:

Prasad Banoth K4U Infotech


(Knowledge for U)
Output Variables

• The Python print statement is often used to output variables.


• To combine both text and a variable, Python uses the + character:

Example 6:

Prasad Banoth K4U Infotech


(Knowledge for U)
• You can also use the + character to add a variable to another variable:

• For numbers, the + character works as a mathematical operator:

Prasad Banoth K4U Infotech


(Knowledge for U)
• If you try to combine a string and a number, Python will give you an error:

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Built-in Data Types

Prasad Banoth K4U Infotech


(Knowledge for U)
Built-in Data Types

• In programming, data type is an important concept.


• Variables can store data of different types, and different types can
do different things.

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Prasad Banoth K4U Infotech


(Knowledge for U)
Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Prasad Banoth K4U Infotech


(Knowledge for U)
Getting the Data Type

You can get the data type of any object by using the type() function:

Prasad Banoth K4U Infotech


(Knowledge for U)
Setting the Data Type

Prasad Banoth K4U Infotech


(Knowledge for U)
Setting the Specific Data Type

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Numbers

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Numbers

There are three numeric types in Python:

• Int : Int, or integer, is a whole number, positive or negative, without

decimals, of unlimited length. (x = 1 )

• Float : Float, or "floating point number" is a number, positive or negative,

containing one or more decimals. (y = 2.8)

• Complex : Complex numbers are written with a "j" as the imaginary part:

(z = 1j )

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Strings

Prasad Banoth K4U Infotech


(Knowledge for U)
String Literals

• String literals in python are surrounded by either single quotation


marks, or double quotation marks.

ex: 'hello' is the same as "hello".

You can display a string literal with the print() function:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Collections (Arrays)
• List
• Tuple
• Set
• Dictionary

Prasad Banoth K4U Infotech


(Knowledge for U)
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 and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.

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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Collections - List

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - List

mylist = ["apple", "banana", "cherry"]

1. Lists are used to store multiple items in a single variable.


2. List is a collection which is ordered and changeable.
3. Allows duplicate members.
4. In Python lists are written with square brackets.

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Prasad Banoth K4U Infotech


(Knowledge for U)
List is a collection which is ordered and changeable. Allows duplicate members

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

Prasad Banoth K4U Infotech


(Knowledge for U)
List Length

• To determine how many items a list has, use the len() function:

Prasad Banoth K4U Infotech


(Knowledge for U)
List Items - Data Types
• List items can be of any data type:

Example : String, int and boolean data types:

Example : A list with strings, integers and boolean values:

Prasad Banoth K4U Infotech


(Knowledge for U)
type() ?

type()

• From Python's perspective, lists are defined as objects with the


data type 'list':
<class 'list'>
Example : What is the data type of a list?

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Access List Items

Access Items :

• List items are indexed and you can access them by referring to the index number:

Example : Print the second item of the list:

Note: The first item has index 0.

Prasad Banoth K4U Infotech


(Knowledge for U)
Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.

Example : Print the last item of the list:

Prasad Banoth K4U Infotech


(Knowledge for U)
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.
Example : Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
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):

Prasad Banoth K4U Infotech


(Knowledge for U)
Check if Item Exists

• To determine if a specified item is present in a list use the in keyword:

Example : Check if "apple" is present in the list:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Change List Items

Change Item Value :


To change the value of a specific item, refer to the index number:

Example : Change the second item:

Prasad Banoth K4U Infotech


(Knowledge for U)
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:
Example : Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Example : Insert "watermelon" as the third item:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Add List Items

Append Items :

To add an item to the end of the list, use the append() method:

Example : Using the append() method to append an item:

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Example : Insert an item as the second position:

Prasad Banoth K4U Infotech


(Knowledge for U)
Extend List :

• To append elements from another list to the current list, use


the extend() method.

Example : Add the elements of tropical to thislist:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Remove List Items

Remove Specified Item :

The remove() method removes the specified item.

Example : Remove "banana":

Prasad Banoth K4U Infotech


(Knowledge for U)
Remove Specified Index :
• The pop() method removes the specified index.
Example : Remove the second item:

• If you do not specify the index, the pop() method removes the last item.
Example : Remove the last item:

Prasad Banoth K4U Infotech


(Knowledge for U)
• The del keyword also removes the specified index:
Example : Remove the first item:

• The del keyword can also delete the list completely.


Example : Delete the entire list:

Prasad Banoth K4U Infotech


(Knowledge for U)
Clear the List :
• The clear() method empties the list.
• The list still remains, but it has no content.
Example : Clear the list content:

Prasad Banoth K4U Infotech


(Knowledge for U)
List Methods
• Python has a set of built-in methods that you can use on lists.

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Collections - TUPLES

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - TUPLES

mytuple = ("apple", "banana", "cherry")

• Tuples are used to store multiple items in a single variable.

• Tuple is a collection which is ordered and unchangeable.

• Allows duplicate members.

• In Python tuples are written with round brackets.

Prasad Banoth K4U Infotech


(Knowledge for U)
Tuple Items

• 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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Ordered : When we say that tuples are ordered, it means that the items have a

defined order, and that order will not change.

Unchangeable : Tuples are unchangeable, meaning that we cannot change, add or

remove items after the tuple has been created.

Allow Duplicates : Since tuples are indexed, they can have items with the same value:
Example : Tuples allow duplicate values:

Prasad Banoth K4U Infotech


(Knowledge for U)
Tuple Length

To determine how many items a tuple has, use the len() method:

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Example : One item tuple, remember the comma:

Prasad Banoth K4U Infotech


(Knowledge for U)
Tuple Items - Data Types

• Tuple items can be of any data type:


Example : String, int and boolean data types:

• A tuple can contain different data types:


Example : A tuple with strings, integers and boolean values:

Prasad Banoth K4U Infotech


(Knowledge for U)
type()

• From Python's perspective, tuples are defined as objects with the data
type 'tuple':

<class 'tuple'>

Example : What is the data type of a tuple?

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Access Tuple Items

Access Tuple Items :

• You can access tuple items by referring to the index number, inside
square brackets:

Example: Print the second item in the tuple:

Note: The first item has index 0.

Prasad Banoth K4U Infotech


(Knowledge for U)
Negative Indexing :

• Negative indexing means beginning from the end


• Remember that the last item has the index -1
• -1 refers to the last item
• -2 refers to the second last item etc.

Example : Print the last item of the tuple:

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Example : Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).

Prasad Banoth K4U Infotech


(Knowledge for U)
• 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:

Prasad Banoth K4U Infotech


(Knowledge for U)
Range of Negative Indexes

• Negative indexing means starting from the end of the tuple.

• Remember that the last item has the index -1

Example : This example returns the items from index -4 (included) to index -1
(excluded)

Prasad Banoth K4U Infotech


(Knowledge for U)
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

Example: Check if "apple" is present in the tuple:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Update Tuples

• Tuples are unchangeable, meaning that you cannot change, add, or


remove items once the tuple is created.

Prasad Banoth K4U Infotech


(Knowledge for U)
Add Items

• Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

Prasad Banoth K4U Infotech


(Knowledge for U)
Remove Items

Note: You cannot remove items in a tuple.


• Tuples are unchangeable, so you cannot remove items from it, but you
can delete the tuple completely:

The del keyword can delete the tuple completely:

Prasad Banoth K4U Infotech


(Knowledge for U)
Join Two Tuples

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

Prasad Banoth K4U Infotech


(Knowledge for U)
Tuple Methods

• Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a

tuple

index() Searches the tuple for a specified value and returns the

position of where it was found

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Collections - SETS

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - SETS
myset = {"apple", "banana", "cherry"}
• Sets are used to store multiple items in a single variable.
• Set is a collection which is unordered and unindexed.
• No duplicate members.
• In Python sets are written with curly brackets.

Note: Sets are unordered


• meaning: the items will appear in a random order.
• so you cannot be sure in which order the items will appear.

Prasad Banoth K4U Infotech


(Knowledge for U)
Set Items
• Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered :
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable :
• Sets are unchangeable, meaning that we cannot change the items after the set
has been created.
NOTE : Once a set is created, you cannot change its items, but you can add new items.
Duplicates Not Allowed:
Sets cannot have two items with the same value.

Prasad Banoth K4U Infotech


(Knowledge for U)
Get the Length of a Set

• To determine how many items a set has, use the len() method.

Prasad Banoth K4U Infotech


(Knowledge for U)
Set Items - Data Types
• Set items can be of any data type:

Example : String, int and boolean data types:

• A set can contain different data types:

Example : A set with strings, integers and boolean values:

Prasad Banoth K4U Infotech


(Knowledge for U)
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?

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Access Items

• You cannot access items in a set by referring to an index, since sets


are unordered the items has no index.
• 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.

Example:
Loop through the set, and print the values:
Example:
Check if "banana" is present in the set:

Prasad Banoth K4U Infotech


(Knowledge for U)
Change Items

• Once a set is created, you cannot change its items, but you can add
new items.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Add Set Items
Add Items:

• Once a set is created, you cannot change its items, but you can add new items.

• To add one item to a set use the add() method.

• To add more than one item to a set use the update() method.

Example: Add an item to a set, using the add() method:

Prasad Banoth K4U Infotech


(Knowledge for U)
Example: Add multiple items to a set, using the update() method:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Remove Item
• To remove an item in a set, use the remove(), or the discard() method.

Example: Example:
Remove "banana" by using the discard() method:
Remove "banana" by using the remove() method:

Note: If the item to remove does not exist,


• remove() will raise an error.
• discard() will NOT raise an error.

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Example : The union()/ update() method returns a new set with all items from both
sets:

Prasad Banoth K4U Infotech


(Knowledge for U)
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

discard() Remove the specified item


intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

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

pop() Removes an element from the set


remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Collections - Dictionaries

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Dictionaries

• Dictionary is a collection which is ordered, indexed and changeable.


• No duplicate members.
• In Python Dictionary are written with curly brackets and have keys and
values:

Prasad Banoth K4U Infotech


(Knowledge for U)
Dictionary Items

• 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

index [1] etc.

• Dictionary items are presented in key:value pairs, and can be referred to by using the key

name.

Prasad Banoth K4U Infotech


(Knowledge for U)
• Ordered : When we say that dictionaries are ordered, it means that the items have a

defined order, and that order will not change.

• Changeable : Dictionaries are changeable, meaning that we can change, add or remove

items after the dictionary has been created.

• Duplicates Not Allowed : Dictionaries cannot have two items with the same key:

Prasad Banoth K4U Infotech


(Knowledge for U)
Dictionary Length

• To determine how many items a dictionary has, use the len() function:

Example : Print the number of items in the dictionary:

Prasad Banoth K4U Infotech


(Knowledge for U)
Dictionary Items - Data Types
• Dictionary items can be of any data type:

Example : String, int, boolean, and list data types:

Prasad Banoth K4U Infotech


(Knowledge for U)
type()

• From Python's perspective, dictionaries are defined as objects with the

data type 'dict':

<class 'dict'>

Example : Print the data type of a dictionary:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Access Dictionary Items

Get Items :

• The items() method will return each item in a dictionary, as tuples in a list.

Example : Get a list of the key:value pairs

Prasad Banoth K4U Infotech


(Knowledge for U)
Get Keys :

• The keys() method will return a list of all the keys in the dictionary.

Example : Get a list of the keys:

Prasad Banoth K4U Infotech


(Knowledge for U)
Get Values:
• The values() method will return a list of all the values in the dictionary.

Example : Get a list of the values:

Prasad Banoth K4U Infotech


(Knowledge for U)
Accessing Items
• You can access the items of a dictionary by referring to its key name, inside square brackets:
Example : Get the value of the "model" key:

• There is also a method called get() that will give you the same result:

Example : Get the value of the "model" key:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Change Dictionary Items

Change Values :
• You can change the value of a specific item by referring to its key name:

Example : Change the "year" to 2018:

Prasad Banoth K4U Infotech


(Knowledge for U)
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.

Example : Update the "year" of the car by using the update() method:

Prasad Banoth K4U Infotech


(Knowledge for U)
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 :

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
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 :

Prasad Banoth K4U Infotech


(Knowledge for U)
popitem() method
• The popitem() method removes the last inserted item

Example :

Prasad Banoth K4U Infotech


(Knowledge for U)
del() method
• The del keyword removes the item with the specified key name:

Example :

Prasad Banoth K4U Infotech


(Knowledge for U)
• The del keyword can also delete the dictionary completely:

Prasad Banoth K4U Infotech


(Knowledge for U)
clear() method
• The clear() method empties the dictionary:

Example:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python File - Handling

Prasad Banoth K4U Infotech


(Knowledge for U)
Python File - Handling

• File handling is an important part of any web application.


• Python has several functions for creating, reading, updating, and deleting
files.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - File Handling
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:

 "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

 "t" - Text - Default value. Text mode


 "b" - Binary - Binary mode (e.g. images)

Prasad Banoth K4U Infotech


(Knowledge for U)
Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python File Open - Open a File on the Server

• Assume we have the following file, located in the same folder as Python:

 To open the file, use the built-in open() function.


 The open() function returns a file object, which has a read() method for reading the
content of the file:
demofile.txt
Ex – 1:
WELCOME
TO
f = open("demofile.txt", "r") PYTHON
CLASS
print(f.read())

Prasad Banoth K4U Infotech


(Knowledge for U)
If the file is located in a different location, you will have to specify the file path, like this:

EX - 2 : Open a file on a different location:

f = open("E:\K4U\K4U TRANNING\Python Programs\welcome.txt", "r")

print(f.read())

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Ex – 3 : Return the 5 first characters of the file demofile.txt


WELCOME
TO
f = open("demofile.txt", "r") PYTHON
CLASS
print(f.read(5))

Prasad Banoth K4U Infotech


(Knowledge for U)
Read Lines - readline() method:

You can return one line by using the readline() method:

Ex – 4 : Read one line of the file


f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Ex – 5 : Read two lines of the file:


f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

Prasad Banoth K4U Infotech


(Knowledge for U)
read the whole file, line by line

By looping through the lines of the file, you can read the whole file, line by line:

Ex -6 : Loop through the file line by line

f = open("demofile.txt", "r")
for x in f:
print(x)

Prasad Banoth K4U Infotech


(Knowledge for U)
Close Files

It is a good practice to always close the file when you are done with it.

Ex : Close the file when you are finish 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.

Prasad Banoth K4U Infotech


(Knowledge for U)
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

Ex – 7 : Open the file "demofile2.txt" and append content to the file

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())

Prasad Banoth K4U Infotech


(Knowledge for U)
Python File Write - overwrite the content

Ex – 8 : Open the file "demofile3.txt" and overwrite the content

f = open("demofile3.txt", "w")
f.write(" Prasad - Add content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.

Prasad Banoth K4U Infotech


(Knowledge for U)
Create a New File

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")

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Delete File - Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Ex - 10: Remove the file "demofile4.txt"


import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete it:
Ex – 11 : Check if file exists, then delete it
import os
if os.path.exists("demofile4.txt"):
os.remove("demofile4.txt")
else:
print("The file does not exist")

Prasad Banoth K4U Infotech


(Knowledge for U)
Delete Folder

To delete an entire folder, use the os.rmdir() method:

Ex - Remove the folder "myfolder":


import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - User Input

Prasad Banoth K4U Infotech


(Knowledge for U)
User Input

• Python allows for user input.


• That means we are able to ask the user for input.

Python input() Function :

• The input() function allows user input.

Syntax : input(prompt)

Prasad Banoth K4U Infotech


(Knowledge for U)
Example 1:

Example 2:

Prasad Banoth K4U Infotech


(Knowledge for U)
Example 3:

Prasad Banoth K4U Infotech


(Knowledge for U)
Example 4:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python Strings

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - String

• String literals in python are surrounded by either single quotation


marks, or double quotation marks.

ex: 'hello' is the same as "hello".

You can display a string literal with the print() function:

Prasad Banoth K4U Infotech


(Knowledge for U)
Assign String to a Variable

• Assigning a string to a variable is done with the variable name followed by an


equal sign and the string:

Prasad Banoth K4U Infotech


(Knowledge for U)
Multiline Strings

• You can assign a multiline string to a variable by using three quotes (single
or double):

Three double quotes: “ “ “ “ “ “


Example : You can use three double quotes:

Prasad Banoth K4U Infotech


(Knowledge for U)
Three single quotes: ‘’’ ‘’’

Example : You can use three single quotes:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Slicing Strings

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Modify Strings

• Python has a set of built-in methods that you can use on strings.

Upper Case : upper() method

Example : The upper() method returns the string in upper case:

Prasad Banoth K4U Infotech


(Knowledge for U)
Lower Case : lower() method

Example : The lower() method returns the string in lower case:

Prasad Banoth K4U Infotech


(Knowledge for U)
Remove Whitespace

• 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 :

Prasad Banoth K4U Infotech


(Knowledge for U)
Replace String

• The replace() method replaces a string with another string:

Example :

Prasad Banoth K4U Infotech


(Knowledge for U)
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:

Prasad Banoth K4U Infotech


(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
• 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.

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Format - Strings

• Python Variables cannot combine strings and numbers :

Prasad Banoth K4U Infotech


(Knowledge for U)
String Format

• 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:

Example : Use the format() method to insert numbers into strings:

Prasad Banoth K4U Infotech


(Knowledge for U)
• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:

Prasad Banoth K4U Infotech


(Knowledge for U)
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

Prasad Banoth K4U Infotech


(Knowledge for U)
Python - Escape Characters
Escape Character :
• To insert characters that are illegal in a string, use an escape character.
• An escape character is a backslash \ followed by the character you want to insert.
• An example of an illegal character is a double quote inside a string that is surrounded
by double quotes:

• To fix this problem, use the escape character \":

Prasad Banoth K4U Infotech


(Knowledge for U)
Prasad Banoth K4U Infotech
(Knowledge for U)
Engineering Innovatin Center

Banoth Prasad
M/W : 9182976493
Email : k4uinfo@gmail.com

Prasad Banoth K4U Infotech


(Knowledge for U)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy