Python - Variable Types:

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

Assigning Values to Variables:

The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example:

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print counter
print miles
print name

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously. For example:

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

a, b, c = 1, 2, "john"

Here two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.

 

Statically typed language:

It is a language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.

 

Dynamically typed language

It is a language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.

 

Strongly typed language

It is a language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.

 

Weakly typed language

A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.

So Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters).

Standard Data Types:

Python has following standard data types:

 

Python Numbers:

Number objects are created when you assign a value to them. For example:

var1 = 1
var2 = 10

Python supports four different numerical types:

Here are some examples of numbers:

int

long

float

complex

10

51924361L

0.0

3.14j

 

#print1.py#

a=6

b=6.62

 

 

print "hi %d hello %.3f \n" % (a,b)

str= "hi %d hello %.3f \n" % (a,b)

print str

 

Strings

 

• "hello"+"world" "helloworld" # concatenation

• "hello"*3 "hellohellohello" # repetition

• len("hello") 5 # size

• "hello" < "jello" 1 # comparison

• "e" in "hello" 1 # search

• "escapes: \n etc,

>>> word = 'Python'

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)

'Py'

>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)

'tho'

>>> word[:2]  # character from the beginning to position 2 (excluded)

'Py'

>>> word[4:]  # characters from position 4 (included) to the end

'on'

>>> word[-2:] # characters from the second-last (included) to the end

'on'

+---+---+---+---+---+---+

 | P | y | t | h | o | n |

 +---+---+---+---+---+---+

 0   1   2   3   4   5   6

-6  -5  -4  -3  -2  -1

Slicing in Python

Attempting to use a index that is too large will result in an error:

>>> word[42]  # the word only has 7 characters

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IndexError: string index out of range

 

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 ([]).

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd to (3-1) elements
print list[2:]      # Prints elements starting from 3rd element till end
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

 

more examples on list:

 

 

a = [99, "bottles of beer", ["on", "the", "wall"]]

• Same operators as for strings

• a+b, a*3, a[0], a[-1], a[1:], len(a)

• Item and slice assignment

 

myList =[1,2,"Kalyan", 'Nokia', ['hi',"Hello"], "bye"]

print myList

 

>>> a = range(5) # [0,1,2,3,4]

>>> a.append(5) # [0,1,2,3,4,5]

>>> a.pop() # [0,1,2,3,4]

5

 

>>> a.insert(0, 42) # [42,0,1,2,3,4]

>>> a.pop(0) # [0,1,2,3,4]

42

>>> a.reverse() # [4,3,2,1,0]

>>> a.sort() # [0,1,2,3,4]

>>>a.extend(["kalyan", 5]) #![0, 1, 2, 3, 4, 'kalyan', 5]

>>> len(a)

7

>>> a.index('kalyan')

5

 

 

list1 = myList + [1,2,3] #! Adding the two lists, same as list1.extend([1,2,3])

print list1

list2 = list1

print list2

n=2

print list2.pop() #! pops up the last element, list2 gets modified after the opetaion

print list2.pop(n) #! pops up the nth element

print list2 #! list gets modified after the op operation

exercise 1:  what is the output of each print?

 

a = [99, "bottles of beer", ["on", "the", "wall"]]
a[0] = 98
print (a)
a[1:2] = ["bottles", "of", "beer"]
print (a)
a[1:2] = [["bottles", "of", "beer"]]
print (a)
del a[-1]
print (a)
 

 

 

Difference between extend() and append()

 

>>> li = ['a', 'b', 'c']

>>> li.extend(['d', 'e', 'f']) 

>>> li

['a', 'b', 'c', 'd', 'e', 'f']

>>> len(li) 

6

>>> li[-1]

'f'

>>> li = ['a', 'b', 'c']

>>> li.append(['d', 'e', 'f']) 

>>> li

['a', 'b', 'c', ['d', 'e', 'f']]

>>> len(li) 

4

>>> li[-1]

['d', 'e', 'f']

 

 

Dictionary

 

>>> d = {"server":"mpilgrim", "database":"master"} 

>>> d

{'server': 'mpilgrim', 'database': 'master'}

>>> d["server"] 

'mpilgrim'

>>> d["database"] 

'master'

 

#Dictinary.py

#Dictinary operations

 

d = {"kalyan":"it professional", "nokia":"it company", 34:"number_value", "number_key":3}

print d

print d["kalyan"]

d["motorola"]="mobile" #! inserting new attributes

print d

d["nokia"]="no one mobile company" #! overwrite

print d

del d["nokia"]

print d

print d.keys() #prints all the keys as separate strings in a list

print d.values() # prints all the values as separate strings in a list

print d.items() # prints all the (‘key’, ‘value’) pairs as tuples in a list

print d.has_key("kalyan") #returns True in case key exists

print d.has_key("Garai") #returns False in case of non existence

d1=d.copy() #! copy dictionary d into d1

print "d1 dictionary: "

print d1

print d1.popitem() #! pops out the first item from d1 and prints that item

print d1 #! now d1 has lost the first item in the above operation

d1.update(d) #! this will update d1 with the d, means all the new items of d will be

print d1 #! copied into d1. now d1 will have all the items what d has and in

# addition to that d1 may have some extra items which it originally has

d.clear() #! clears all the element in the dictionary

print d

del d #deletes the entire dictionary

 

Dictinary Details

• Keys must be immutable:

– numbers, strings, tuples are immutables

• these cannot be changed after creation

– reason is hashing (fast lookup technique)

– not lists or other dictionaries

• these types of objects can be changed "in place"

– no restrictions on values

• Keys will be listed in arbitrary order

again, because of hashing

 

 

Shallow copy vs Deep Copy

d = {"kalyan":"it professional", "nokia":"it company", 34:"number_value", 'number_key':3}
print d
d1 = d.copy();#deep copy
print d1;
d["kalyan"] = "trainer"
print d;
print d1;

d2 = d;#shallow copy, both d2 and d pointing to the same object
print d2;
d["kalyan"]="corporate trainer"
print d;
print d2
 

Tuples

>>> t=(1,2,3,[1,2,3],{"sd":"fdhdh",2:3,"d":4},4)

>>> print t

(1, 2, 3, [1, 2, 3], {2: 3, 'd': 4, 'sd': 'fdhdh'}, 4)

>>> print t[1:4]

(2, 3, [1, 2, 3])

 

• key = (lastname, firstname)

• point = x, y, z # parentheses optional

• x, y, z = point # unpack

• lastname = key[0]

• singleton = (1,) # trailing comma!!!

 

• empty = () # parentheses!

 

>>>t = ("a", "b", "mpilgrim", "z", "example")

>>> t[1:3] #('b', 'mpilgrim')

 

• tuples vs. lists; tuples immutable

 

 

NoteTuples Have No Methods

 

 

 

So what are tuples good for?

 

What's True in Python?

Before version 2.2.1, Python had no separate boolean datatype. To compensate for this, Python

accepted almost anything in a boolean context (like an if statement), according to the following

rules:

• 0 is false; all other numbers are true.

• An empty string ("") is false, all other strings are true.

• An empty list ([]) is false; all other lists are true.

• An empty tuple (()) is false; all other tuples are true.

• An empty dictionary ({}) is false; all other dictionaries are true.

These rules still apply in Python 2.2.1 and beyond, but now you can also use an actual boolean,

which has a value of True or False. Note the capitalization; these values, like everything else in

Python, are case-sensitive.

 

Assigning Multiple Values at Once

One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.

 

Example:

>>> v = ('a', 'b', 'e')

>>> (x, y, z) = v

>>> x

'a'

>>> y

'b'

>>> z

'e'

 

Example

>>> range(7)

[0, 1, 2, 3, 4, 5, 6]

>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)

>>> MONDAY

0

>>> TUESDAY

1

>>> SUNDAY

6

 

String Formatting

>>> uid = "sa"

>>> pwd = "secret"

>>> print pwd + " is not a good password for " + uid

secret is not a good password for sa

>>> print "%s is not a good password for %s" % (pwd, uid)

secret is not a good password for sa

>>> userCount = 6

>>> print "Users connected: %d" % (userCount, )

Users connected: 6

>>> print "Users connected: " + userCount

Error.

 

Explanation:

(userCount, ) is a tuple with one element. Yes, the syntax is a little strange, but there's a good reason for it: it's unambiguously a tuple. In fact, you can always include a comma after the last element when defining a list, tuple, or dictionary, but the comma is required when defining a tuple with one element. If the comma weren't required, Python wouldn't know whether (userCount) was a tuple

with one element or just the value of userCount.

 

String formatting works with integers by specifying %d instead of %s.

 

Trying to concatenate a string with a non-string raises an exception. Unlike string formatting, string concatenation works only when everything is already a string.

 

 

Example

>>> print "Today's stock price: %f" % 50.4625

50.462500

>>> print "Today's stock price: %.2f" % 50.4625

50.46

>>> print "Change since yesterday: %+.2f" % 1.5

+1.50

 

 

The keys(), values() and item() functions

 

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}

 

>>> params.keys() 

['server', 'uid', 'database', 'pwd']

 

>>> params.values() 

['mpilgrim', 'sa', 'master', 'secret']

 

>>> params.items() 

[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]

 

 the keys method of a dictionary returns a list of all the keys. The list is not in the order in which the dictionary was defined (remember that elements in a dictionary are unordered), but it is a list.

 the values method returns a list of all the values. The list is in the same order as the list returned by keys, so params.values()[n] == params[params.keys()[n]] for all values of n.

 the items method returns a list of tuples of the form (key, value). The list contains all the data in the dictionary.

 

 

Joining Lists and Splitting Strings

 

>>> sample_dict = {"Kalyan":"garai", "hello":"world"}; #!sample dictionary

>>> sample_dict

{'Kalyan': 'garai', 'hello': 'world'}

 

>>> li= ["%s=%s" % (k,v) for k,v in sample_dict.items()] #!converted into list

>>> li

['Kalyan=garai', 'hello=world']

 

>>> str1 = ";".join(li); #! list will be converted into string, actuall all the items will be a part of the same string

>>> str1

'Kalyan=garai;hello=world'

 

>>> str1.split(";") #string will be split into string

['Kalyan=garai', 'hello=world']

 

 

 

Note: You Can't join Non-Strings

join works only on lists of strings; it does not do any type coercion. Joining a list that has one or more non-string elements will raise an exception.

 

 

 

>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> s = ";".join(li)

>>> s

'server=mpilgrim;uid=sa;database=master;pwd=secret'

>>> s.split(";") 

['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> s.split(";", 1) 

['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

split reverses join by splitting a string into a multi-element list. Note that the delimiter (“;”) is

stripped out completely; it does not appear in any of the elements of the returned list.

 split takes an optional second argument, which is the number of times to split.

 

Searching with split

anystring.split(delimiter, 1) is a useful technique when you want to search a string for a

substring and then work with everything before the substring (which ends up in the first element of the returned list) and everything after it (which ends up in the second element).

 

 

Tuples into lists into tuples

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple

 

li = ["Kalyan", "Gara", 1,23,45]

print li #["Kalyan", "Gara", 1,23,45]

t = tuple(li)

print t #("Kalyan", "Gara", 1,23,45)

l1 = list(t)

print l1 #["Kalyan", "Gara", 1,23,45]

 

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. base specifies the base if x is a string.

long(x [,base] )

Converts x to a long integer. 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.

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.