Python Practical
Python Practical
Python contains several advanced programming features such as generators (used to create
iterators with a different approach that most other languages) and list comprehensions (used to
create new lists from other iterables). Python also has automatic memory management eliminating
the need to manually allocate and free memory in the code.
Data types in Python:
Python Data Types are used to define the type of a variable. It defines what type of data we are
going to store in a variable. The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is stored as alphanumeric
characters.
Python has following built-in data types:
Python numeric data types store numeric values. Number objects are created when you
assign a value to them.
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
B) String –str
Python Strings are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.The plus (+) sign is the string
concatenation operator and the asterisk (*) is the repetition operator in Python.
str='Hello World!'
List: Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python
lists are similar to arrays in C. One difference between them is that all the items belonging
to a Python list can be of different data type where as C array can store elements related to
a particular data type.
The values stored in a Python 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 −
list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']
Python Dictionary
Python 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 −
dict={}
dict['one']="This is one"
dict[2]="This is two"
tinydict={'name':'john','code':6734,'dept':'sales'}