0% found this document useful (0 votes)
39 views229 pages

Python

Python programming

Uploaded by

abdul7ahad73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
39 views229 pages

Python

Python programming

Uploaded by

abdul7ahad73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 229

Infotech

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

// 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;
}
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?

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


Python Indentation (cont..)
Example 1:

Output :
Python Indentation (cont..)

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

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

• Comments can be used to

• explain Python code.

• make the code more readable.

• prevent execution when testing code.


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

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)
Assign Value to Multiple Variables

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

Example 4:
And you can assign the same value to multiple variables in one line:

Example 5:
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:
• You can also use the + character to add a variable to another variable:

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


• If you try to combine a string and a number, Python will give you an error:
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.
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.
Built-in Data Types
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


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

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

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


Python Collections (Arrays)
• List
• Tuple
• Set
• Dictionary
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.
Python Collections - List
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.
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.


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

Example : String, int and boolean data types:

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


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


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:


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).
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 determine if a specified item is present in a list use the in keyword:

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


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:


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

Example : Insert "watermelon" as the third item:


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:


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:


Extend List :

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


the extend() method.

Example : Add the elements of tropical to thislist:


Python - Remove List Items

Remove Specified Item :

The remove() method removes the specified item.

Example : Remove "banana":


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:
• 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:
Clear the List :
• The clear() method empties the list.
• The list still remains, but it has no content.
Example : Clear the list content:
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
Python Collections - TUPLES
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.


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.


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

the item, otherwise Python will not recognize it as a tuple.

Example : One item tuple, remember the comma:


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


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.


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:


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

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


Python - Update Tuples

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


remove items once the tuple is created.
Add Items

• Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
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:


Join Two Tuples

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


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


Python Collections - SETS
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.
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.
Get the Length of a Set

• To determine how many items a set has, use the len() method.
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:


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

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


Example: Add multiple items to a set, using the update() method:
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.
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:
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
Python Collections - Dictionaries
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:
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.
• 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:
Dictionary Length

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

Example : Print the number of items in the dictionary:


Dictionary Items - Data Types
• Dictionary items can be of any data type:

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


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:


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


Get Keys :

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

Example : Get a list of the keys:


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

Example : Get a list of the values:


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:


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:


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

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


• Python has several functions for creating, reading, updating, and
deleting files.
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)
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", "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:

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


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


Python - User Input
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)
Example 1:

Example 2:
Example 3:
Example 4:
Python Strings
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:


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:
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:
Three single quotes: ‘’’ ‘’’

Example : You can use three single quotes:


Python - Slicing Strings
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:


Lower Case : lower() method

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


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 :
Replace String

• The replace() method replaces a string with another 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

• Python Variables cannot combine strings and numbers :


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:


• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
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 \":


Python Flow Control
Python - Flow Control

• Python If ... Else


• Python While Loops
• Python For Loops
Python - If ... Else

Python Conditions :

Python supports the usual logical conditions from mathematics:

• Equals: a == b

• Not Equals: a != b

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b


If statements

• Python conditions can be used in several ways, most commonly


in "if statements" and loops.
• An "if statement" is written by using the if keyword.

Example: If statement
Else

• The else keyword catches anything which isn't caught by the


preceding conditions.
Example: else statement

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

The and keyword is a logical operator, and is used to combine conditional


statements:

Example : Test if a is greater than b, AND if c is greater than a:


Or - Keyword

• The or keyword is a logical operator, and is used to combine conditional


statements:
Example : Test if a is greater than b, OR if a is greater than c:
Nested If

• You can have if statements inside if statements, this is

called nested if statements.

Example :
Python - While/For Loops

Python Loops :

Python has two primitive loop commands:

• while loops

• for loops
Python - While Loops

• With the while loop we can execute a set of statements as long as


a condition is true.
• The while loop in Python executes a block of code until the specified
condition becomes False.
Example : Print i as long as i is less than 6:

Note: remember to increment i, or else the loop will continue forever.


break statement

• With the break statement we can stop the loop even if the while
condition is true:

Example : Exit the loop when i is 3:


continue statement

• With the continue statement we can stop the current iteration, and
continue with the next:

Example : Continue to the next iteration if i is 3


else statement

• With the else statement we can run a block of code once when the
condition no longer is true:

Example : Print a message once the condition is false


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

PIP is a package manager for Python packages, or modules if you like.

Note: If you have Python version 3.4 or later, PIP is included by default.

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.
Check if PIP is Installed

C:\Users\UDDISH > pip --version

C:\Users\UDDISH> python -m pip install --upgrade pip --user

python.exe -m pip install --upgrade pip


Installing
Jupyter Software
Installing the Jupyter Software

Prerequisite: Python

While Jupyter runs code in many programming languages, Python is a

requirement (Python 3.3 or greater, or Python 2.7) for installing the

classic Jupyter Notebook.


Installing Jupyter Notebook using pip

If you use pip, you can install it with command

pip install notebook


To run the notebook, run the following command at the Terminal
(Mac/Linux) or Command Prompt (Windows):

jupytper notebook
working on jupyter
https://jupyter.readthedocs.io/en/latest/running.html#running
Updating Jupyter:

pip3 install --upgrade --user nbconvert


Programming on jupyter
Infotech
( Knowledge For U )

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 can be installed via pip from PyPI.

• pip install pandas

• Pandas is part of the Anaconda distribution and can be installed with Anaconda

• conda install pandas

When working with tabular data, such as data stored in spreadsheets or


databases, Pandas is the right tool for you.
Pandas will help you to explore, clean and process your data

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.

• If you use pip, you can install it with:


• pip install numpy
• If you use conda, you can install it with:
• conda install numpy

https://numpy.org/doc/stable/user/whatisnumpy.html
matplotlib
Matplotlib: Visualization with Python

Matplotlib is a comprehensive library for creating static, animated,


and interactive visualizations in Python.

https://matplotlib.org/

https://matplotlib.org/tutorials/introductory/images.html#sphx-glr-tutorials-introductory-images-py
• Install Matplotlib with pip:

• pip install matplotlib

• Install Matplotlib with the Anaconda Prompt:

• conda install matplotlib


0s
The OS module in Python provides a way of using operating system dependent
functionality. The functions that the OS module provides allows you to interface with
the underlying operating system that Python is running on – be that Windows, Mac or
Linux.

• Install os with pip:

• pip install os

• Install os with the Anaconda Prompt:

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

• Install seaborn with pip:

• pip install seaborn

• Install seaborn with the Anaconda Prompt:

• conda install seaborn

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

You might also like