0% found this document useful (0 votes)
3 views7 pages

Python Unit-I Part-II

The document provides an overview of Python programming, covering standard data types such as numbers, strings, lists, tuples, and dictionaries. It includes explanations of data type conversion and built-in functions available in Python. Additionally, it features example code snippets demonstrating the usage of these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Python Unit-I Part-II

The document provides an overview of Python programming, covering standard data types such as numbers, strings, lists, tuples, and dictionaries. It includes explanations of data type conversion and built-in functions available in Python. Additionally, it features example code snippets demonstrating the usage of these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

PYTHON PROGRAMMING Subject code: 4101

Text Book:
1. Learning With Python, by Allen Downey, Jeff Elkner and Chris Meyers
Reference Books:
1. Dive into Python,Mike
2. Learning Python, 4th Edition by Mark Lutz
3. Programming Python, 4th Edition by MarkLutz
4. Python Cookbook, Third edition by David Beazley and Brian K. Jones
5. Head First Python: A Brain-Friendly Guide, by Paul Barry
6. Learn Python The Hard Way, by Zed A. Shaw

UNIT-I Part-II
Standard Data Types
1. Python Numbers
Python supports different numerical types-
 int (signed integers): They are often called just integers or ints. They are positive or negative
whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2
has two integer types - int and long. There is no 'long integer' in Python 3 anymore. float
(floating point real values) : Also called floats, they represent real numbers and are written
with a decimal point dividing the integer and the fractional parts. Floats may also be in
scientific notation, with E or e indicating the power of
10 (2.5e2 = 2.5 x 102 = 250).
 complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number). The real part of the number
is a, and the imaginary part is b. Complex numbers are not used much in Python
programming.
Number data types store numeric values. Number objects are created when you assign a value to
them. For example
var1= 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the
del statement is
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example
del var
del var_a, var_b
Python supports three different numerical types
 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
All integers in Python 3 are represented as long integers. Hence, there is no separate number type as
long.
Here are some examples of numbers
int float complex
10 0.0 3.14j
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where
x and y are real numbers and j is the imaginary unit.
2. Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows either pair of single or double quotes. Subsets of strings can be taken

ICBCS | [Link] HIRAY


2

using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string
and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example Output:
#!/usr/bin/python3 Hello World!
str = 'Hello World!' H
print (str) # Prints complete string
llo
print (str[0]) # Prints first character of the string
llo World!
print (str[2:5]) # Prints characters starting from 3rd to 5th
Hello World!Hello World!
print (str[2:]) # Prints string starting from 3rd character
Hello World!TEST
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

3. Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
One of the differences between them is that all the items belonging to a list can be of different data
type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator. For example
Output:
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] ['abcd', 786, 2.23, 'john',
tinylist = [123, 'john'] 70.200000000000003]
print (list) # Prints complete list abcd
print (list[0]) # Prints first element of the list [786, 2.23]
print (list[1:3]) # Prints elements starting from 2nd till 3rd [2.23, 'john', 70.200000000000003]
print (list[2:]) # Prints elements starting from 3rd element [123, 'john', 123, 'john']
print (tinylist * 2) # Prints list two times ['abcd', 786, 2.23, 'john',
print (list + tinylist) # Prints concatenated lists 70.200000000000003, 123, 'john']
4. Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are enclosed within parenthesis. The main
difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size
can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be
thought of as read-only lists. For example
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times Output:
print (tuple + tinytuple) # Prints concatenated tupleprint (list +
tinylist) # Prints concatenated lists
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john') 70.200000000000003, 123, 'john']

ICBCS | [Link] HIRAY


3

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with listprint
(tuple + tinytuple) # Prints concatenated tupleprint
(list + tinylist) # Prints concatenated lists

5. Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes found
in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example

#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
print (tuple + tinytuple) # Prints concatenated tuple
print (list + tinylist) # Prints concatenated lists

Output:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among the elements. It is incorrect to say that the elements are "out of
order"; they are simply unordered.
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types. To convert between
types, you simply use the type-name as a function. There are several built-in functions to perform
conversion from one data type to another. These functions return a new object representing the converted
value.
Function Description
int(x [,base]) Converts x to an integer. The base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real[,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
ICBCS | [Link] HIRAY
4

chr(x) Converts an integer to a character.


unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Built in Functions in Python
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The
python interpreter has several functions that are always present for use.
Built In Description
Function
abs(x) The absolute value of x: the (positive) distance between x and
all() The python all() function accepts an iterable object (such as list, dictionary, etc.). It
returns true if all items in passed iterable are true. Otherwise, it returns False.
bin() Pyhton's built-in function bin() can be used to obtain binary representation of an integer
number.
bool() The python bool() converts a value to boolean(True or False) using the standard truth
testing procedure.
bytes() The python bytes() in Python is used for returning a bytes object. It is an immutable
version of the bytearray() function.
callable() A python callable() function in Python is something that can be called. This built-in
function checks and returns true if the object passed appears to be callable, otherwise
false.
compile() The python compile() function takes source code as input and returns a code object
which can later be executed by exec() function.
exec() The python exec() function is used for the dynamic execution of Python program which
can either be a string or object code and it accepts large blocks of code, unlike the eval()
function which only accepts a single expression.
sum() As the name says, python sum() function is used to get the sum of numbers of an
iterable, i.e., list.
any() The python any() function returns true if any item in an iterable is true. Otherwise, it
returns False.
ascii() The python ascii() function returns a string containing a printable representation of an
object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.
bytearray() The python bytearray() returns a bytearray object and can convert objects into bytearray
objects, or create an empty bytearray object of the specified size.
eval() The python eval() function parses the expression passed to it and runs python
expression(code) within the program.
float() The python float() function returns a floating-point number from a number or string.
format() The python format() function returns a formatted representation of the given value.
len() The python len() function is used to return the length (the number of items) of an object.
list() The python list() creates a list in python.
print() The python print() function prints the given object to the screen or other standard output
devices.
frozenset() The python frozenset() function returns an immutable frozenset object initialized with
elements from the given iterable.
iter() The python iter() function is used to return an iterator object. It creates an object which
can be iterated one element at a time.
open() The python open() function opens the file and returns a corresponding file object.
filter() The first argument can be none, if the function is not available and returns only elements
that are true.
min() Python min() function is used to get the smallest element from the collection.
sorted() Python sorted() function is used to sort elements. By default, it sorts elements in an
ascending order but can be sorted in descending also.

ICBCS | [Link] HIRAY


5

next() This function is used to fetch next item from the collection. It takes two arguments, i.e.,
an iterator and a default value, and returns an element.
input() This function is used to get an input from the user.
int() Used to get an integer value. It returns an expression converted into an integer number.
oct() Python oct() function is used to get an octal value of an integer number.
pow() The python pow() function is used to compute the power of a number. It returns x to the power
of y.
range() The python range() function returns an immutable sequence of numbers starting from 0 by
default, increments by 1 (by default) and ends at a specified number.
str() The python str() converts a specified value into a string.
tuple() The python tuple() function is used to create a tuple object.
type() This function returns the type of the specified object if a single argument is passed to the type()
built in function.

Programs: Outputs:
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer)) Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))

# all values true


k = [1, 3, 4, 6] True
print(all(k)) False
False
# all values false False
k = [0, False] True
print(all(k))

# one false value


k = [1, 3, 7, 0]
print(all(k))

# one true value


k = [0, False, 5]
print(all(k))

# empty iterable
k = []
print(all(k))

ICBCS | [Link] HIRAY


6
#Using bin function 0b1010
x = 10
y = bin(x) [] is False
print (y) [0] is True
0.0 is False
#Using bool function None is False
test1 = [] True is True
print(test1,'is',bool(test1)) Easy string is True
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))

# compile string source to code <class 'code'>


code_str = 'x=5\ny=10\nprint("sum =",x+y)' sum = 15
code = compile(code_str, '[Link]', 'exec')
print(type(code)) True
exec(code) 12
exec(x)
7
#using exec function 17
x=8
exec('print(x==8)')
exec('print(x+4)')

#using sum function


s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)

#using format function 123


# integer 123.456790
print(format(123, "d"))
1100
# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))

ICBCS | [Link] HIRAY


7

# list of numbers
list = [1,2,3,4,5]
1
2
listIter = iter(list)
3
4
# prints '1'
5
print(next(listIter))

# prints '2'
print(next(listIter))

# prints '3'
print(next(listIter))

# prints '4'
print(next(listIter))

# prints '5'
print(next(listIter))
# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))

ICBCS | [Link] HIRAY

You might also like