Advanced python language training : variable and data type
![Advanced python language training : variable and data type](/images/remos_downloads/id-12725.12725.pdf_thumb_prev.jpg)
Python Data Types
3. Python Data Types
3.1 Python Variables
Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
Defining python Variables
In Python When defining the variable no need to sfecifyt the data going to be store in the variable like C programing.
Python Variable Names
Following table has examples of legal variable names. You can name a variable anything as long as it obeys the following three rules:
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character. 3. It can’t begin with a number.
List of Python key word as follows
Type help() in python shell and type keywords to ge the list of key word in python
Python variables are dynamically typed
There are two types of variables in programing, static typed and dynamic typed .static typed languages(c, c++ ,c# ,java..) are those in which type checking is done at compile-time, whereas dynamic typed languages(Python,) are those in which type checking is done at run-time.
Scope of a Python Variable
Variables can only be seen or accessible within their scope. Two variable scopes are classified in Python:
Local variables are defined and only used by the calling function. They are not recognized by the main program or in any other calling functions.
Global variables are common to most part of the code. They are recognized everywhere and can be accessed by any functions.
3.2 Python Data types
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 string. Python has various standard data types, can be listed as follows
String (Str)
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.
1. Creating string
Creating strings is as simple as assigning a value to a variable
2. Accessing Values in Strings.
In python all string can acces through the variable nameand the part of string can acces through indexing
3. String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then
4. String formating Operator (%)
Sring format operater is used when need to insert the value of a variable, or expression into a string, For example, you can insert the value of a Decimalvalue into a string to display it to the user as a single string:
The order of inserting variable value in a string can change using positional order or key word order. See the following example.
Here is the list of complete set of symbols which can be used along with % (old style)
Old | new | output |
Basic formatting ![]() | ||
'%s %s' % ('one', 'two') | '{} {}'.format('one', 'two') | one two |
'%d %d' % (1, 2) | '{} {}'.format(1, 2) | 1 2 |
Padding and Aligning of strings | ||
'%10s' % ('test',) | '{:>10}'.format('test') | xxxxxxtest |
'%-10s' % ('test',) | '{:10}'.format('test') | testxxxxxx |
N/A | '{:_<10}'.format('test') | test______ |
N/A | '{:^10}'.format('test') | xxxtestxxx |
Numbers | ||
'%d' % (42) | '{:d}'.format(42) | 42 |
'%f' % (3.14159265,) | '{:f}'.format(3.14159265) | 3.141593 |
Padding and Aligning of Numbers | ||
'%4d' % (42) ![]() | '{:4d}'.format(42) | xx42 |
'%06.2f' % (3.1415926) | '{:06.2f}'.format(3.1415926) | 003.14 |
'%04d' % (42,) | '{:04d}'.format(42) | 0042 |
5. Escap character
An escape character is a characterwhich do an alternative opeartion at where it placed in a character sequence. Following table is a list of escape characters that can be represented with backslash notation.
Escape Sequence | Description | Example | Output |
\\ | Prints Backslash | print ("\\") | \ |
\’ | Prints singlequote | print ("\'") | ' |
\" | Pirnts double quote | print ("\"") | " |
\a | Bell alert sounds ( eg. ![]() xterm ) | print ("\a") | (bell soud) |
Escape Sequence | Description | Example | Output |
\b | Removes previous character | print ("ab" + "\b" + "c") | ac |
\f | ASCII formfeed ( FF ) | print ("hello\fworld") | hello world |
\n | ASCII linefeed ( LF ) | print ("hello\nworld") | hello world |
\t | ASCII horizontal tab (TAB). Prints TAB | print ("\t* hello") | * hello |
6. Built-in String Methods
Python includes the following built-in methods (fucntions) to manipulate strings.
Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.Python supports three different numerical types –
![](/images/remos_downloads/detail/127/id-12725.12725.pdf-008.jpg)
List (list)
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.
7. How to create a list?
In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
Also, a list can even have another list as an item. This is called nested list.
8. How to access elements from a list?
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4. The index must be an integer.
Nested list are accessed using nested indexing.
Output will be as follows
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
9. How to slice lists in Python?
We can access a range of items in a list by using the slicing operator (colon).
Output will be as follows
10. How to change or add elements to a list?
List are mutable, meaning, their elements can be changed unlike string or tuple. We can use assignment operator (=) to change an item or a range of items.
Output will be as follows
We can add one item to a list using append() method or add several items using extend() method.
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
Output will be as follows
11. How to delete or remove elements from a list?
We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
Output will be as follows
We can use remove() method to remove the given item or pop() method to remove an item at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
12. Python List Membership Test
We can test if an item exists in a list or not, using the keyword in.
![](/images/remos_downloads/detail/127/id-12725.12725.pdf-052.jpg)
Example program 3.6
Example program 3.6 output
13.Iterating Through a List
NOTE1 IN C: for (i = 0; i < n; i++) Inpython3: for i in range(n): | NOTE2 InC: for(int i=0; i<9; i+=2) { dosomething(i); } Inpython3: for i in range(0, 9, 2): dosomething(i) |
Tuple (tuple)
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-
Difference between Tuples and List
Python Dictionary Data type
Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. While values can be of any data type and can repeat, keys must be of immutable (unable to change) type (string, number or tuple with immutable elements) and must be unique.
Ø Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
As you can see above, we can also create a dictionary using the built-in function dict().
Ø How to access elements from a dictionary?
Dictionary uses keys accsess the data . Key can be used either inside square brackets or with the get() method.
When you run the program, the output will be:
Ø How to change or add elements in a dictionary?
We can add new items or change the value of existing items using assignment the key is already present, value gets updated, else a new key: value pair is added to the dictionary.