A variable is associated with pair of a storage location and associated symbolic name (an identifier), i.e. [location,identifier].
- Location is used by system and identifier is used by user/programmer to access the variable
- When a variable is created, some space in memory is reserved
- Data type of a variable decides, the amount of reserved memory and what can be stored in the reserved memory
- In python type of variable is decided based on the value it is assigned
- According to the type of variable, operations which can be performed on it are decided
Ex:
num = 100 # An integer value assignment dec = 100.0 # A floating point name = "Jonny" # A string x = y = z = 100 # Multiple assignment a,b,c = 100,100.0,"Jonny" # Multiple assignment print (num) print (dec) print (name) print ("x: ",x," y: ",y," z: ",z) print ("a: ",a," b: ",b," c: ",c)
OUTPUT:
100 100.0 Jonny x: 100 y: 100 z: 100
Standard Data Types
Python has five standard data types −
- Numbers
- String
- List
- Tuple
- Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when a value is assigned to them.
Ex:
num1 = 5 num2 = 10
Four different numerical types are supported in python:
- int (signed integers)
- long (long integers, they can also be represented in octal and hexadecimal)
- float (decimal/real values)
- complex (complex numbers)
Mathematical Functions
Python includes following functions for numbers:
abs(x), math.ceil(x), cmp(x, y), exp(x), fabs(x), math.floor(x), math.log(x), math.log10(x), max(x1, x2,…), min(x1, x2,…), math.modf(x), pow(x, y), round(x, n), math.sqrt(x).
For details click here.
Random Number Functions
Python includes following functions that are widely used. You have to import random library to use these functions.
choice(seq), random.randrange (start, last, step), random.random(), random.seed(x), random.shuffle(list), uniform(x, y).
For details click here.
Trigonometric Functions
In python trigonometric functions are avaiabe in math ibrary.
math.acos(x), math.asin(x), math.atan(x), math.atan2(y, x), math.cos(x), math.hypot(x, y), math.sin(x), math.tan(x), math.degrees(x), math.radians(x).
Mathematical Constants
In python pi and e are the two mathematical constants. They can be used as math.pi and math.e.
Python Strings
In Python character type variables are not defined; they are treated as strings of length one.
- Strings in Python are set of characters enclosed in the pair of quotation marks (either single or double quotes).
- Slice operator ([ ] and [:] ) can be used to take subset of string
- Indexes start at 0
- Concatenation operator: plus (+) sign
- Repetition operator: asterisk (*)
Ex:
str = "Hello world!" print(str) # Prints complete string print(str[0]) # Prints 1st character of the string print(str[2:5]) # Prints 3rd to 5th characters of the str print(str[2:]) # Prints rest of the string from 3rd character print(str * 2) # Prints string twice print(str + "TEST") # Prints concatenated string
OUTPUT:
Hello world! H llo llo world! Hello world!Hello world! Hello world!TEST
Triple Quotes
Row strings are defined by enclosing string within triple, single quotes or double quotes. While printing the tabs, new lines are also displayed. Ex:
para_str = ""This shows how triple quotes been executed. It shows how multiple lines and non-printable symbols such as TAB (\t), NEWLINEs [\n]are displayed.""" print (para_str)
OUTPUT:
This shows how triple quotes been executed. It shows how multiple lines and non-printable symbols such as TAB ( ), NEWLINEs [ ]are displayed.
Built-in String Methods
Python includes the following built-in methods/functions to manipulate strings:
len(string), find(str, beg, end), rfind(str, beg, end), index(str, beg, end), rindex( str, beg, end), max(str), min(str), startswith(str, beg, end), endswith(suffix, beg, end), join(seq), count(str, beg, end), capitalize(), swapcase(), lower(), upper(), split(“str”, num), splitlines(num), strip(), lstrip(), rstrip(), replace(old, new, max), ljust(width, fillchar), rjust(width, fillchar), zfill (width), title(), center(width, fillchar), isalnum(), isalpha(), isdigit(), islower(), isnumeric(), isdecimal(), isspace(), istitle(), isupper().
For more details about these function click here.
Python Lists
A list in python is a compound data type which can store multiple elements.
- Items of a list are enclosed within square brackets ([])
- Items are separated by commas
- The items of a list can be of different data type.
Ex: l1 = [1,2,”a”,2.3,3j] - Slice operator ([ ] and [:] ) can be used to access elements in a list. Negative index: count from the right. Ex: print(l1[-2]) returns 2.3
- Indexes start at 0
- Concatenation operator: plus (+) sign. Ex: [1, 2, 3] + [4, 5, 6]returns [1, 2, 3, 4, 5, 6]
- Repetition operator: asterisk (*). Ex: [‘Hi!’] * 4 returns [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]
- len(list) returns the number of elements in the list. Ex: len([1, 2, 3]) returns 3
- in operator returns the membership of an element in a list. Ex: 3 in [1, 2, 3] returns True
l1 = [1,2,"a",2.3,3j] l2 = [567, "jonny"] print(l1) # Prints all the elements of list print(l1[0]) # Prints 1st elements of the list print(l1[1:3]) # Prints elements from 2nd till 3rd print(l1[2:]) # Prints all the elements of l1 from 3rd value print(l2 * 2) # Prints list l2 twice print(l1 + l2) # Prints concatenated lists l1[2]=3 # Updates 3rd element of the list print(l1[2]) # Prints updated 3rd element of the list del l1[2] # Deleting 3rd element of the list print(l1)
OUTPUT:
[1, 2, 'a', 2.3, 3j] 1 [2, 'a'] ['a', 2.3, 3j] [567, 'jonny', 567, 'jonny'] [1, 2, 'a', 2.3, 3j, 567, 'jonny'] 3 [1, 2, 2.3, 3j, 567, 'jonny']
Built-in List Functions & Methods:
Functions defined for lists in python:
cmp(list1, list2), len(list), max(list), min(list), append(obj), count(obj), extend(seq), index(obj), insert(index, obj), pop(index), remove(obj), reverse(), sort().
For more details click here.
Python Tuples: Read only List
A tuple in python is also a compound data type which can store multiple elements.
- Tuples are almost same as list except that, elements of a tuple can not be changed like list.
- Items of a tuple are enclosed within round brackets (())
- Items are separated by commas
- The items of a tuple can be of different data type.
Ex: t1 = (1,2,”a”,2.3,3j) - Slice operator ([ ] and [:] ) can be used to access elements in a tuple. Negative index: count from the right. Ex: print(l1[-2]) returns 2.3
- Indexes start at 0
- Concatenation operator: plus (+) sign
- Repetition operator: asterisk (*)
To write a tuple containing a single value you have to include a comma, even though there is only one value:
tup1 = (50,);
Ex:
t1 = (1,2,"a",2.3,3j) t2 = (567, "jonny") print(t1) # Prints all the elements of list print(t1[0]) # Prints 1st elements of the list print(t1[1:3]) # Prints elements from 2nd till 3rd print(t1[2:]) # Prints all the elements of l1 from 3rd value print(t2 * 2) # Prints list l2 twice print(t1 + t2) # Prints concatenated lists t1[2]=3 #updates 3rd element of the list print(t1[2]) #prints updated 3rd element of the list
OUTPUT:
Traceback (most recent call last): File "C:/Users/Administrator/Desktop/Python/1.py", line 9, in <module> t1[2]=3 #updates 3rd element of the list TypeError: 'tuple' object does not support item assignment
Basic Tuples Operations
- len(): returns the length of tuple. Ex: len((1,2,3)) returns 3.
- +: Concatenation operation. Ex: (1, 2, 3) + (4, 5, 6) results (1, 2, 3, 4, 5, 6)
- *: Repetition. Ex: (‘Hi!’,) * 4 results (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)
- in: Membership operation. Ex: 3 in (1, 2, 3) results True
- for: Iterationt operation. Ex: for x in (1, 2, 3): print (x), results 1 2 3
- cmp(tuple1, tuple2): Compares elements of both tuples.
- max(tuple): Returns item from the tuple with max value.
- min(tuple): Returns item from the tuple with min value.
- tuple(seq): Converts a list into tuple.
Python Dictionary
Lets understand the basic functionalities of dictionaries with an example:
d1 = {} d1[123] = &quot;Hello&quot; d1[&quot;World&quot;] = 123 d2 = {&quot;;name&quot;: &quot;jonny&quot;,&quot;Employee_code&quot;:6103467, &quot;dept&quot;: &quot;CSE&quot;} print(d1[123]) # Prints value for 'one' key print(d1[&quot;World&quot;]) # Prints value for 2 key print(d2) # Prints complete dictionary print(d2.keys()) # Prints all the keys print(d2.values()) # Prints all the values
OUTPUT:
Hello 123 {'Employee_code': 6103467, 'dept': 'CSE', 'name': 'jonny'} dict_keys(['Employee_code', 'dept', 'name']) dict_values([6103467, 'CSE', 'jonny'])
Python Dictionary Functions
cmp(dict1, dict2), len(dict), str(dict), type(variable), clear(), copy(), fromkeys(seq,Value), get(key, default), has_key(key), items(), keys(), setdefault(key, default), update(d2), values(), del dict[‘Name’], dict.clear(), del dict, dict.has_key(key), dict.items(), dict.keys(), dict1.update(dict2), dict.values().
For more details click here.
Data Type Conversion
Many of the times type conversion is required. Python provides facility of data conversion. To convert between types, use the type name as a function.
Ex:
int(x), float(x), str(x), long(x), tuple(x), list(x), dict(x), char(x), hex(x), oct(x).