0% found this document useful (0 votes)
159 views44 pages

Python Programming - Introduction All

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It was created by Guido van Rossum in 1991 and includes key features like being interactive, object-oriented, and having a large standard library. Python can be used for web and app development, data science, scripting, and more. It supports features like functions, classes, exception handling, and modules/packages. Common data types in Python include integers, floats, strings, lists, tuples, dictionaries, sets, and booleans.

Uploaded by

JEEVITHA A
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
159 views44 pages

Python Programming - Introduction All

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It was created by Guido van Rossum in 1991 and includes key features like being interactive, object-oriented, and having a large standard library. Python can be used for web and app development, data science, scripting, and more. It supports features like functions, classes, exception handling, and modules/packages. Common data types in Python include integers, floats, strings, lists, tuples, dictionaries, sets, and booleans.

Uploaded by

JEEVITHA A
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 44

Python Programming

Python – Programming language

• Python is a general-purpose interpreted, interactive, object-

oriented, and high-level programming language.

• It was created by Guido van Rossum during 1985- 1990.

• Like Perl, Python source code is also available under the GNU

General Public License (GPL).


Key advantages of learning Python
• Python is Interpreted − Python is processed at runtime by the
interpreter. We do not need to compile your program before executing it.
This is similar to PERL and PHP.

• Python is Interactive − We can actually sit at a Python prompt and


interact with the interpreter directly to write your programs.

• Python is Object-Oriented − Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.

• Python is a Beginner's Language − Python is a great language for the


beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
Characteristics of Python

oIt supports functional and structured programming methods as well as


OOP.
o It can be used as a scripting language or can be compiled to byte-code
for building large applications.
o It provides very high-level dynamic data types and supports dynamic
type checking.
o It supports automatic garbage collection.
o It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
Applications of Python
o Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the
student to pick up the language quickly.
o Easy-to-read − Python code is more clearly defined and visible to the eyes.
o Easy-to-maintain − Python's source code is fairly easy to maintain.
o A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on
UNIX, Windows, and Macintosh.
o Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
o Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
o Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers
to add to or customize their tools to be more efficient.
o Databases − Python provides interfaces to all major commercial databases.
o GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
o Scalable − Python provides a better structure and support for large programs than shell scripting .
Python comments
Single line comment
In python we use # special character to start the comment.
# This is just a comment. Anything written here is ignored by Python
Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the
beginning and at the end of the comment
'''
This is a
multi-line
comment
'''
Python Variable
Variables are used to store data, they take memory space based on the type of value we
assigning to them.
num = 100 #num is of type int
str = "Chaitanya" #str is of type string
Variable name – Identifiers
Variable name is known as identifier.
1. The name of the variable must always start with either a letter or an underscore (_). For
example: _str, str, num, _num are all valid name for the variables.
2. The name of the variable cannot start with a number. For example: 9num is not a valid
variable name.
3. The name of the variable cannot have special characters such as %, $, # etc, they can only
have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).
4. Variable name is case sensitive in Python which means num and NUM are two different
variables in python.
num = 100
str = "BeginnersBook"
print(num) print(str)
Operators
Operators are the constructs which can manipulate the value of operands.
Types of Operator
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Python Arithmetic Operators
Comparison Operators
Assignment Operators
Bitwise Operators
Logical Operators
Membership Operators
Identity Operators
Python Operators Precedence
Data Types
Data type defines the type of the variable, whether it is an integer variable, string
variable, tuple, dictionary, list etc.
The data types in Python are divided in two categories:
1. Immutable data types – Values cannot be changed.
2. Mutable data types – Values can be changed
Immutable data types in Python
 1. Numbers
 2. String
 3. Tuple
Mutable data types in Python
 1. List
 2. Dictionaries
 3. Sets
1. Numeric Data Type in Python
Integer
In Python 3, there is no upper bound on the integer number which means we can have
the value as large as our system memory allows.

# Integer number
num = 100
print(num)
print("Data Type of variable num is", type(num))

Float
Values with decimal points are the float values, there is no need to specify the data type in
Python. It is automatically inferred based on the value we are assigning to a variable.

# float number
fnum = 34.45
print(fnum)
print("Data Type of variable fnum is", type(fnum))
2. Python Data Type – String
String is a sequence of characters in Python. The data type of String in Python is called
“str”.
Strings in Python are either enclosed with single quotes or double quotes.
# Python program to print strings and type

s = "This is a String"
s2 = 'This is also a String'

# displaying string s and its type


print(s)
print(type(s))

# displaying string s2 and its type


print(s2)
print(type(s2))
3. Tuple
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you


can put these comma-separated values between parentheses also. For example −

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −

tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there
is only one value −

tup1 = (50,);
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index.

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements.
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new tuple, not a string.
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings. Assuming following input −

L = ('spam', 'Spam', 'SPAM!’)


Built-in Tuple Functions
Accessing Values in Lists -To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index. list1=['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
Updating Lists- We can update single or multiple elements of lists by giving the slice on the left-hand
side of the assignment operator and add to elements in a list with the append() method.
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Delete List Elements -To remove a list element, we can use either the del statement if weknow exactly
which element(s) we are deleting or the remove() method if we do not know.
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Indexing, Slicing, and Matrixes-Because lists are sequences, indexing and slicing work the same way
for lists as they do for strings.
L = ['spam', 'Spam', 'SPAM!’]
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
Built-in List Functions & Methods
Python includes the following list functions −
Python includes following list methods
4. Python Data Type – Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with just
two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of
any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age’]
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice’]
Updating Dictionary
We can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting
an existing entry.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
Delete Dictionary Elements
We can either remove individual dictionary elements or clear the entire contents of a dictionary. You
can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School’]
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or
user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys
encountered during assignment, the last assignment wins.
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name’]
(b) Keys must be immutable. Which means we can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
Built-in Dictionary Functions & Methods
Python includes the following dictionary functions
Python includes following dictionary methods
Python - Decision Making
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Syntax of If statement
The syntax of if statement in Python is pretty simple.
if condition:
block_of_code
If statement flow diagram

flag = True
if flag:
print("Welcome")
print("To")
print("BeginnersBook.com")
Python –if..else statement
if condition:
block_of_code_1
else:
block_of_code_2
block_of_code_1: This would execute if the given condition is true
block_of_code_2: This would execute if the given condition is false

If else statement flow diagram

num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Python –elif statement
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as
soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most
one statement, there can be an arbitrary number of elif statements following an if.
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
num = 1122
if 9 < num < 99:
print("Two digit number")
elif 99 < num < 999:
print("Three digit number")
elif 999 < num < 9999:
print("Four digit number")
else:
print("number is <= 9 or >= 9999")
Python –Loops
A loop statement allows us to execute a statement or group of statements multiple times.
Python –while loop
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −

while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of
grouping statements.
Python –while loop
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1

print ("Good bye! ")


Using else Statement with While Loop
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a while loop, the else statement is executed when the condition
becomes false.

count = 0
while count < 5:
print (count, " is less than 5 ")
count = count + 1
else:
print (count, " is not less than 5 “)
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on
the same line as the while header.

flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
array = [10,20,30,40,50]
for x in array: # First Example
print ('elements:', x)
For Loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to
the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to
iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!“


Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself.
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!“


Using else Statement with For Loop
Python supports to have an else statement associated with a loop statement

If the else statement is used with a for loop, the else statement is executed when the loop has exhausted
iterating the list.
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
break
Python nested loops
Python programming language allows to use one loop inside another loop.
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
Nesting is that we can put any type of loop inside of any other type of loop. For example a for loop can be
inside a while loop or vice versa.
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
print "Good bye!"

You might also like