Python Programming
Python Programming
Dr.Bharanidharan.G,
Assistant Professor,
Department of Computer Applications,
The New College, Chennai-14.
E-Mail: bharanidharan@thenewcollege.edu.in
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
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.
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.
Python
• 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-oriented way or a functional way.
Python Syntax compared to other programming
languages
• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often use
curly-brackets for this purpose.
How to Check Python Version on Linux, Mac &
Windows
How to Check Python Version on Linux, Mac &
Windows
How to check the Python version using a script?
• Python scripts can identify the version of Python installed on the computer. It
enables you to validate if multiple versions are installed in the system. The script
developed to check the Python version remains the same for windows OS, Mac
OS, and Linux distributions. You can create a script by importing either the
platform module or sys module of python.
How to Run Python Scripts: Step by Step Guide
• What is the Script in Python?
• A script in Python can be defined as a file that consists of Python code or a program.
• It ends with an extension as .py
• An interpreter can execute a script in two distinct ways, as listed below: –
• A script can be executed as a module or as a script itself.
• A code that is written in an interactive Python command prompt session manner.
• Step 3) The programmer can sequentially write Python code and execute them in the same order.
• The following program can be typed in the command line as shown below:
Python Indentation
Python Indentation
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!")
Print() Statement
• The print() function in Python is used to print a specified message on the screen.
• The print command in Python prints strings or objects which are converted to a
string while printing on a screen.
• Syntax:
print(object(s))
• Example: 1
To print the Welcome to Guru99, use the Python print statement as follows:
print ("Welcome to Guru99")
Output:
Welcome to Guru99
• Example 2:
If you want to print the name of five countries, you can write:
print ("USA")
print ("Canada")
print ("Germany")
print ("France")
print ("Japan")
Output:
USA
Canada
Germany
France
Japan
• How to print blank lines
• Sometimes you need to print one blank line in your Python program.
Following is an example to perform this task using Python print format.
• Example:
• Let us print 8 blank lines. You can type:
print (8 * "\n")
(or)
print ("\n\n\n\n\n\n\n\n")
,
• Example 1:
Output:
Welcome to Guru99!
Output:
Python@
Python Variables
• What is a Variable in Python?
• A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
• Python Variable Types
• Every value in Python has a datatype. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc.
• Variables in Python can be declared by any name or even alphabets like a, aa, abc,
etc.
• How to declare and use a variable?
• Let us see an example. We will define variable in Python and declare it as “a” and
print it.
a=100
print (a)
• Re-declare a Variable
• You can re-declare Python variables even after you have declared once.
• Here we have Python declare variable initialized to f=0.
• Later, we re-assign the variable f to value “guru99”
Python String Concatenation and Variable
• Let’s see whether you can concatenate different data types like string and number together. For example, we
will concatenate “Guru” with the number “99”.
• Unlike Java, which concatenates number with string without declaring number as string, while declaring
variables in Python requires declaring the number as string otherwise it will show a TypeError.
Python Variable Types: Local & Global
• There are two types of variables in Python, Global variable and Local
variable. When you want to use the same variable for rest of your program
or module you declare it as a global variable, while if you want to use the
variable in a specific function or method, you use a local variable while
Python variable declaration.
• Let’s understand this Python variable types with the difference between
local and global variables in the below program.
1. Let us define variable in Python where the variable “f” is global in scope and is
assigned value 101 which is printed in output
2. Variable f is again declared in function and assumes local scope. It is assigned value
“I am learning Python.” which is printed out as an output. This Python declare
variable is different from the global variable “f” defined earlier.
3. Once the function call is over, the local variable f is destroyed. At line 12, when we
again, print the value of “f” is it displays the value of global variable f=101
• While Python variable declaration using the keyword global, you can
reference the global variable inside a function.
1. Variable “f” is global in scope and is assigned value 101 which is printed in
output
2. Variable f is declared using the keyword global. This is NOT a local variable,
but the same global variable declared earlier. Hence when we print its
value, the output is 101
3. We changed the value of “f” inside the function. Once the function call is
over, the changed value of the variable “f” persists. At line 12, when we
again, print the value of “f” is it displays the value “changing global variable”
Delete a variable
• You can also delete Python variables using the command del “variable
name”.
• In the below example of Python delete variable, we deleted variable f,
and when we proceed to print it, we get error “variable name is not
defined” which means you have deleted the variable.
Summary
• Variables are referred to “envelop” or “buckets” where information can be maintained
and referenced. Like any other programming language Python also uses a variable to
store the information.
• Variables can be declared by any name or even alphabets like a, aa, abc, etc.
• Variables can be re-declared even after you have declared them for once
• Python constants can be understood as types of variables that hold the value which can
not be changed. Usually Python constants are referenced from other files. Python define
constant is declared in a new or separate file which contains functions, modules, etc.
• Types of variables in Python or Python variable types : Local & Global
• Declare local variable when you want to use it for current function
• Declare Global variable when you want to use the same variable for rest of the program
• To delete a variable, it uses keyword “del”.
Python Escape Character Sequences (Examples)
• Escape characters or sequences are illegal characters for Python and never get
printed as part of the output. When backslash is used in Python programming, it
allows the program to escape the next characters.
• Following would be the syntax for an escape sequence.
• Explanation:
Here, the escape character could be t, n, e, or backslash itself.
Types of Escape Sequence
• Escape characters can be classified as non-printable characters when backslash precedes them. The print statements do
not print escape characters.
• Here is a list of Escape Characters
Example Usage of Various Escape Characters
Explanation:
In the above example, instead of adding space using a keyboard, the program helps us by
putting a space or a tab between the string “Guru99”. It also provides a space at the precise
location where the escape sequence is added.
Summary
• Backslash is also regarded as a special character.
• To create an escape sequence, begin with a backslash followed by the
illegal character.
• Examples of escape sequences include “\b”, “\t”,”\n”,”\xhh” and “\ooo”
respectively.
• “\t” allows inserting a space or tab between two words. It plays a similar
role to the space key present on the keyboard.
• “\t” is used when the programmer wants to add space to a string at a
precise location.
• Certain whitespaces help in putting a new line between python strings.
• Line feed and carriage return, vertical tab, and form feed are types of
whitespaces.
Built-
Built-in Data Types
Built-
Built -in Data Types
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
• In the dictionary, you can also sort the elements. For example, if we
want to print the name of the elements of our dictionary
alphabetically, we have to use the for a loop. It will sort each element
of the dictionary accordingly.
Sorting the Dictionary
• With Str() method, you can make a dictionary into a printable string
format.
• Use the code % str (Dict)
• It will return the dictionary elements into a printable string format
Summary
• Dictionaries in a programming language is a type of data-structure used to
store information connected in some way.
• Python Dictionary are defined into two elements Keys and Values.
• Dictionaries do not store their information in any particular order, so you
may not get your information back in the same order you entered it.
• Keys will be a single element
• Values can be a list or list within a list, numbers, etc.
• More than one entry per key is not allowed ( no duplicate key is allowed)
• The values in the dictionary can be of any type, while the keys must be
immutable like numbers, tuples, or strings.
• Dictionary keys are case sensitive- Same key name but with the different
cases are treated as different keys in Python dictionaries.
Python Dictionary Append: How to Add Key/Value
Pair
• Dictionary is one of the important data types available in Python. The
data in a dictionary is stored as a key/value pair. It is separated by a
colon(:), and the key/value pair is separated by comma(,).
• The keys in a dictionary are unique and can be a string, integer, tuple,
etc. The values can be a list or list within a list, numbers, string, etc.
• Here is an example of a dictionary:
Restrictions on Key Dictionaries
• Here is a list of restrictions on the key in a dictionary:
• If there is a duplicate key defined in a dictionary, the last is considered. For
example consider dictionary my_dict =
{“Name”:”ABC”,”Address”:”Mumbai”,”Age”:30, “Name”: “XYZ”};.It has a key
“Name” defined twice with value as ABC and XYZ. The preference will be
given to the last one defined, i.e., “Name”: “XYZ.”
• The data-type for your key can be a number, string, float, boolean, tuples,
built-in objects like class and functions.
• For example my_dict = {bin:”001″, hex:”6″ ,10:”ten”, bool:”1″, float:”12.8″,
int:1, False:’0′};Only thing that is not allowed is, you cannot defined a key in
square brackets for example my_dict =
{[“Name”]:”ABC”,”Address”:”Mumbai”,”Age”:30};
Operators in Python – Logical, Arithmetic,
Comparison
• 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 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.
Python with MySQL Connectivity: Database & Table
[Examples]
• In order to use MySQL connectivity with Python, we must have some
knowledge of SQL
• MySQL is an Open-Source database and one of the best type of
RDBMS (Relational Database Management System). Co-founder of
MySQLdb is Michael Widenius’s, and also MySQL name derives from
the daughter of Michael.