Python Programming Unit 1
Python Programming Unit 1
CS702OE:PYTHON PROGRAMMING
(OPEN ELECTIVE-II)
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
By Wesley J. Chun
...............................................
● 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
● with Python, not to mention the things that have already been done. Your
3.Scalable 4.Extensible
as elif if or yield
num=float(input())
result=num**0.5
Output
49
num1 = 1.5
num2 = 6.3
# Add two numbers
➔ 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
#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-
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
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.
*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
Scalar storage: single literal object- all numbers and strings type objects
Update Model
Mutable Objects: can be changed after creating- list,dict,set,byte array etc.,
● 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 '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
Create a Module
● To create a module just save the code you want in a file with the file
extension .py:
Hello, Jonathan
Example:
person1 = {
"name": "John",
"age": 36,
"country": "Norway" Output ??????
}
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):
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import only the person1 dictionary from the module:
print (person1["age"])
Strings Sequences - Strings, Lists and Tuples
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
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
Example
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
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!"
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.
Example
Create a List:
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.
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.
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.
* Note: Set items are unchangeable, but you can remove items and add
new items.
● 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.