0% found this document useful (0 votes)
83 views99 pages

Python Programming Unit 1

This document outlines the course CS702OE: Python Programming. The course aims to teach students Python syntax, data structures, object-oriented programming concepts, and how to implement network and database applications in Python. It covers Python basics like variables, data types, operators, and functions. The core data types discussed are numbers, strings, lists, tuples, dictionaries, and sets. Object-oriented concepts like classes and inheritance are also part of the curriculum. Real-world applications of Python in areas such as artificial intelligence, big data, and networking are discussed. The course uses a Python programming book as a reference text.

Uploaded by

SRAVANTI PEC
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)
83 views99 pages

Python Programming Unit 1

This document outlines the course CS702OE: Python Programming. The course aims to teach students Python syntax, data structures, object-oriented programming concepts, and how to implement network and database applications in Python. It covers Python basics like variables, data types, operators, and functions. The core data types discussed are numbers, strings, lists, tuples, dictionaries, and sets. Object-oriented concepts like classes and inheritance are also part of the curriculum. Real-world applications of Python in areas such as artificial intelligence, big data, and networking are discussed. The course uses a Python programming book as a reference text.

Uploaded by

SRAVANTI PEC
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/ 99

PALLAVI ENGINEERING COLLEGE

CS702OE:PYTHON PROGRAMMING
(OPEN ELECTIVE-II)

ELECTRONICS AND COMMUNICATION ENGINEERING

IV B.TECH I SEM
By
Dr T SRAVANTI
ECE HoD
Course Outcomes:
The students should be able to:
1. Examine Python syntax and semantics and be fluent in the use of Python
flow control and functions.
2. Demonstrate proficiency in handling Strings and File Systems.
3. Create, run and manipulate Python Programs using core data structures like
Lists, Dictionaries and use Regular Expressions.
4. Interpret the concepts of Object-Oriented Programming as used in Python.
5. Implement exemplary applications related to Network Programming, Web
Services and Databases in Python.
UNIT - I
Ø Python Basics Ø Categorizing the Standard Types

Ø Objects- Python Objects Ø Unsupported Types

Ø Standard Types Ø Numbers - Introduction to Numbers, Integers,

Ø Other Built-in Types Floating Point Real Numbers, Complex Numbers,

Ø Internal Types Ø Operators,

Ø Standard Type Operators Ø Built-in Functions, Related Modules

Ø Standard Type Built-in Functions Ø Sequences - Strings, Lists and Tuples

Ø Mapping and Set Types


Reference

Core Python Programming, Second Edition

By Wesley J. Chun

...............................................

Publisher: Prentice Hall


What Is Python? Python Basics

● Python is an elegant and robust programming language

● It allows you to get the job done, and then read what you wrote later.

● will be amazed at how quickly you will pick up the language as well as what

kind of things you can do

● with Python, not to mention the things that have already been done. Your

imagination will be the only limit.


Features

1.High Level 2.Object Oriented

3.Scalable 4.Extensible

5.Portable 6.Easy to Learn

7.Easy to Read 8.Easy to Maintain

9.Robust 10.Effective as a Rapid Prototyping Tool

11.A Memory Manager


Uses in Industry

● Central Intelligent Agency(CIA)


● Google’s- search engine
● Facebook- production Engineering
● NASA- workflow automation tool
● Nokia-telecommunication
● Dropbox
● Quora- social commenting websites
● Instagram
● You tube
Future of Python

1) Artificial Intelligence/ Machine Learning


2) Big Data
3) Networking
Modes of working
1) Interactive Mode
2) Script Mode
Keywords used……
False class finally Is return

None continue for lamda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


User input
Write a python program to find square root of a given
number
print(“ Enter the number”)

num=float(input())

result=num**0.5

print(“The square root of “,num,” is”, result)

Output

>>>Enter the number

49

The square root of 49 is 7.0


# This program adds two numbers

num1 = 1.5

num2 = 6.3
# Add two numbers

sum = num1 + num2

# Display the sum

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

With User Input


# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
calculate the area of a triangle
The semi-perimeter of triangle ABC = s = (a + b + c)/2
Then, the area of triangle ABC = √[s × (s – a) × (s – b) × (s – c)]

# Python Program to find the area of triangle


a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Specifying the comments
● print statement

● Expressions, on the other hand, do not use keywords


Python Objects
● Python uses the object model abstraction for data storage.
● Any construct that contains any type of value is an object

All Python objects have the following three characteristics:


IDENTITY : Unique identifier that differentiates an object from all others.

➔ Any object's identifier can be obtained using the id() built-in function (BIF).
.
TYPE : An object's type indicates what kind of values an object can hold,
what operations can be applied to such objects, and what behavioral rules these

objects are subject to.

➔ use the type() BIF to reveal the type of a Python object.

VALUE : Data item that is represented by an object.


Literal constants
★ Literal is a raw data given in a variable or
constant.
1) String Literals : enclose the text or the group of characters in single, double or triple quotes.

Single-line String Multi-line String


#string literals #string literals
#single line literal #multi line literal
single_quotes_string='Scaler Academy' str="Welcome\
double_quotes_string="Hello World" To\
print(single_quotes_string) Scaler\
print(double_quotes_string) Academy"
print(str)
Output:
Output:
Scaler Academy
Hello World WelcometoScalerAcademy
Using triple quotes-

#string literals
#multi line literal Output:
Welcome
str="""Welcome to
to Scaler
Scaler Academy
Academy"""
print(str)
2. Numeric Literals : Numerical literals in Python are those literals that contain digits only and
are immutable.
# integer literal
Integer: #positive whole numbers
The numerical literals that are zero, positive or
negative natural numbers and contain no decimal x = 2586
points are integers. #negative whole numbers
y = -9856
The different types of integers are- # binary literal
a = 0b10101
● Decimal- It contains digits from 0 to 9. The base # decimal literal
for decimal values is 10. b = 505
● Binary- It contains only two digits- 0 and 1. The # octal literal
base for binary values is 2 and prefixed with c = 0o350
“0b”. # hexadecimal literal
● Octal- It contains the digits from 0 to 7. The d = 0x12b
print (x,y)
base for octal values is 8. In Python, such values
are prefixed with “0o”. print(a, b, c, d)
● Hexadecimal- It contains digits from 0 to 9 and Output: 2586 -9856
alphabets from A to F. 21 505 232 299
The floating-point literals are also known as real literals. Unlike integers, these
Float: contain decimal points.
Float literals are primarily of two types-

A. Fractional- Fractional literals B. Exponential- Exponential literals in Python are


contain both whole numbers and represented in the powers of 10. The power of 10 is
decimal points represented by e or E. An exponential literal has two
parts- the mantissa and the exponent.
Example
Example
print(78.256)
print(2.537E5)
Output
Output
78.256
253700.0
Complex: A+Bj
Long
Example Example

# complex literal #usage long literal before it was


a=7 + 8j depreciated
b=5j x=037467L
print(a) print(x)
print(b)
Output:
(7+8j)
5j
3. Boolean Literals:

Boolean literals in Python are pretty straight-forward and have only two values-
● True- True represents the value 1.
● False-False represents the value 0.

Example

#boolean literals Output:


x = (1 == 1) x is True
y = (7 == False) y is False
print("x is", x)
print("y is", y)
4. Special Literals: Python literals have one special literal known as None

Example

#special literals
val=None
print(val)

Output
None
Variables : Variables are containers for storing data values.

x=5
y = "John"
print(x)
print(y)

Output:
5
John
Identifier
“An identifier is a name given to an entity”.
● a user-defined name to represent the basic building blocks of Python.
● can be a variable, a function, a class, a module, or any other object.

These are the valid characters.


● Lowercase letters (a to z)
● Uppercase letters (A to Z)
● Digits (0 to 9)
● Underscore (_)
Standard Types
Data Types
Other Built-in Types
Internal Types
● Code: *Byte-compiled
*return values from calling the compile()
*such objects are appropriate for execution by
either exec or by the eval()
● Frame
*These are objects representing execution stack frames in Python.
*Frame objects contain all the information the Python interpreter needs
to know during a runtime execution environment.
*Some of its attributes include a link to the previous stack frame, the
code object (see above) that is being executed, dictionaries for the local and
global namespaces, and the current instruction.
*Each function call results in a new frame object, and for each frame
object, a C stack frame is created as well.
*One place where you can access a frame object is in a traceback object
● Traceback
*When you make an error in Python, an exception is raised. If
exceptions are not caught or "handled," the interpreter exits with some
diagnostic information similar to the output shown below:
Traceback (innermost last): File "<stdin>", line N?, in ???
ErrorName: error reason

*The traceback object is just a data item that holds the stack trace
information for an exception and is created when an exception occurs. If
a handler is provided for an exception, this handler is given access to the
traceback object.
● Slice
*Slice objects are created using the Python extended slice syntax.
*This extended syntax allows for different types of indexing.
*These various types of indexing include stride indexing, multi-dimensional
indexing, and indexing using the Ellipsis type.
*The syntax for multi-dimensional indexing is sequence[start1 : end1, start2 :
end2], or using the ellipsis, sequence [..., start1 : end1].
*Slice objects can also be generated by the slice() BIF.
● Ellipsis
*Ellipsis objects are used in extended slice notations as demonstrated above.
*These objects are used to represent the actual ellipses in the slice syntax
(...).
*Like the Null object None, ellipsis objects also have a single name, Ellipsis,
and have a Boolean TRue *value at all times.
● Xrange
*XRange objects are created by the BIF xrange(), a sibling of the range() BIF,
and used when memory is limited and when range() generates an unusually large
data set.
* range() : returns list of numbers created
*xrange() : returns the generator object that can be used to display numbers
only by looping
Standard Type Operators
Operators in Python Questions

Write the output of the given Python


Question 1: Question 2: Question 3:
print (3 + 4)
code : print (3 – 4)
a=0 print (3 * 4) print (3/4)
a+ =2 print (3 % 2)
print (a) print (3**4) #3 to the
fourth power
print (3 // 4) #floor
division
Question 4: Question 5:
Question 6: Question 7:
Question 8: Question 9:
Standard Type Built-in Functions
Example: Example:
>>>a=10 >>>s1=’Enjoy Python’
>>>b=20 >>>print(str(s1))
>>>print(cmp(a,b)) >>>Enjoy Python
>>>-1
>>>a=20 >>>print(repr(s1))
>>>b=20 >>>’Enjoy Python’
>>>print(cmp(a,b))
>>>0
Categorizing the Standard Types
Storage Model

Scalar storage: single literal object- all numbers and strings type objects

Container storage: multiple objects- list,tuple and dictionaries

Update Model
Mutable Objects: can be changed after creating- list,dict,set,byte array etc.,

Immutable Objects: cannot be changed after creating-


int,float,complex,string,tuple
Access Model
Direct Types: single element, non-container types- all numeric types

Sequence Types: index value starting at 0-strings,lists and tuples

Mapping Types: hashed key-value pairs- dictionaries


Unsupported Types

● char or byte
● Pointer
● int,short,long
● Float or double
Numbers - Introduction to Numbers, Integers, Floating Point
Real Numbers, Complex Numbers,
use the type() function:

<class 'int'> <class 'float'>


<class 'int'> <class 'float'>
<class 'int'> <class 'float'>

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'complex'>
<class 'complex'>
<class 'complex'>
Operators

● Arithmetic operators

● Assignment operators

● Comparison operators

● Logical operators

● Identity operators

● Membership operators

● Bitwise operators
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators

● Membership operators
● Bitwise operators
Built-in Functions
Example:
numbers = [1,2,3]
str_numbers =
Output
['One','Two','Three']
<zip object at 0x0000014EC4A6B788>
result = zip(numbers, [(1, 'One'), (2, 'Two'), (3,
str_numbers) 'Three')]
print(result)
print(list(result))
Related Modules

● A file containing a set of functions you want to include in your application.

Create a Module
● To create a module just save the code you want in a file with the file
extension .py:
Hello, Jonathan
Example:

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway" Output ??????
}

Import the module named mymodule, and


access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
Import From Module
You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):

print("Hello, " + name)

person1 = {

"name": "John",

"age": 36,

"country": "Norway"

}
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])
Strings Sequences - Strings, Lists and Tuples

Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

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

Example
a = "Hello, World!"
print(a[1])

Output
e
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example

Loop through the letters in the word "banana":


Output
b
for x in "banana": a
n
a
print(x) n
a
String Length
To get the length of a string, use the len() function.

Example

The len() function returns the length of a string: Output


13
a = "Hello, World!"

print(len(a))
Python - Slicing Strings
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the
string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5]) Output:llo
Example Example
Get the characters from the start to Get the characters:
position 5 (not included): From: "o" in "World!" (position -5)

b = "Hello, World!" To, but not included: "d" in "World!"


print(b[:5]) (position -2):

b = "Hello, World!"
print(b[-5:-2])

Example
Get the characters from position 2, and all the way
to the end:

b = "Hello, World!"
print(b[2:])
Python Lists
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example

Create a List:

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

print(thislist)
Python Tuples
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other
3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Mapping and Set Types

Python Dictionaries
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
has been created.

Dictionaries are written with curly brackets, and have keys and values:
thisdict = { thisdict = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
"year": 1964 "year": 1964,
} "year": 2020
print(thisdict) } print(thisdict)
Python Sets
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of


data, the other 3 are List, Tuple, and Dictionary, all with different qualities
and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add
new items.

Sets are written with curly brackets.


Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
LIST TUPLE DICTIONARY SET

● Duplicates ● Duplicates are ● Duplicates ● Duplicates Not


are Allowed Allowed Not Allowed Allowed
● ordered ● ordered ● Ordered/ ● Unordered
● changeable ● Unchangeable Unordered ● Unchangeable
● changeable
Python If ... Else

● An "if statement" is written by using the if keyword.


● The elif keyword is pythons way of saying "if the
previous conditions were not true, then try this condition".
● The else keyword catches anything which isn't caught by
the preceding conditions.
Python While Loops

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


condition is true.
● 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.
Python For Loops

● With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
● With the break statement we can stop the loop before it has looped
through all the items.

You might also like