Variables

In computer programming, a variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.

C

int x = 29;
float y = 321.321;
double z = 32132132132133.21;

Python

x = 343  # Integer
y = 4324n4324  # Flaot

Variable names in Python can contain alphanumerical characters a-z, A-Z, 0-9 and some special characters such as _. Normal variable names should start with a letter. _ can be used for special cases. By convension, variable names start with a lower-case letter, and Class names start with an upper-case letter. In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:

and, as, assert, break, class, continue, def, del, elif, else, except, 
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield

Note: Be aware of the keyword lambda, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.

Assignment

The assignment operator in Python is =. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one.

Assigning a value to a new variable creates the variable:


In [1]:
''' 
variable assignments
this is a variable assignment
'''
x = 1.0
my_variable = 12

In [2]:
print type(x)
print type(my_variable)


<type 'float'>
<type 'int'>

If we assign a new value to a variable, its type can change.


In [3]:
x = 1
type(x)


Out[3]:
int

We get a NameError when we try to access a variable which has not been defined.


In [4]:
t = x + y


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-38bad46c0fb4> in <module>()
----> 1 t = x + y

NameError: name 'y' is not defined

Fundamental data types


In [5]:
# integers
x = 1
type(x)


Out[5]:
int

In [6]:
# float
x = 1.0
type(x)


Out[6]:
float

In [7]:
# boolean
b1 = True
b2 = False

type(b1)


Out[7]:
bool

In [8]:
# Booleans are integers in Python
print True + True  # True has a value equal to 1
print False + False  # False has a value equal to 0


2
0

In [9]:
# complex numbers: note the use of `j` to specify the imaginary part
x = 1.0 - 1.0j
type(x)


Out[9]:
complex

In [10]:
print x


(1-1j)

In [11]:
# Real part
print x.real


1.0

In [12]:
# Imaginary 
print x.imag


-1.0

Typecasting

When you want to change variables from one type to another. We are using inbuilt functions to do the typecasting. Later we'll show you how to write your own functions.


In [13]:
a = 1
a


Out[13]:
1

In [14]:
float(a)


Out[14]:
1.0

In [15]:
z = 2 + 3j
z


Out[15]:
(2+3j)

In [16]:
float(z.imag)


Out[16]:
3.0

In [17]:
complex(a)


Out[17]:
(1+0j)

In [18]:
int(45.55)


Out[18]:
45

In [19]:
bool(0)


Out[19]:
False

Basic boolean algebra

  • and
  • or
  • not

In [20]:
True and True


Out[20]:
True

In [21]:
True and False


Out[21]:
False

In [22]:
True and True and False and True


Out[22]:
False

In [23]:
True or False


Out[23]:
True

In [24]:
False or False


Out[24]:
False

In [25]:
1 and 1


Out[25]:
1

In [26]:
1 and 0


Out[26]:
0

In [27]:
20 and 30  # It just gives you the latter


Out[27]:
30

In [28]:
200 and 30  # I told ya!


Out[28]:
30

In [29]:
0 and 431  # Not here!


Out[29]:
0

In [30]:
1 or 1


Out[30]:
1

In [31]:
1 or 0


Out[31]:
1

In [32]:
21 or 42  # Gives you former


Out[32]:
21

In [33]:
3214 or 42  # Proved!


Out[33]:
3214

In [34]:
not True


Out[34]:
False

In [35]:
not False


Out[35]:
True

In [36]:
not 1


Out[36]:
False

In [37]:
not 0


Out[37]:
True

In [38]:
not 420  # Yep!


Out[38]:
False

Some universal truths!


In [39]:
1 < 2


Out[39]:
True

In [40]:
2 != 3


Out[40]:
True

In [41]:
22 > 11


Out[41]:
True

In [42]:
5 == 5


Out[42]:
True

In [43]:
2 + 3 == 5


Out[43]:
True

Strings

Let's get deep!

Strings are the variable type that is used for storing text messages.


In [44]:
s = "Hello world"
type(s)


Out[44]:
str

In [45]:
# length of the string: the number of characters
len(s)


Out[45]:
11

In [46]:
s  # `s` is still the same! Strings are immutable.


Out[46]:
'Hello world'

In [47]:
s[0]


Out[47]:
'H'

In [48]:
s[1]


Out[48]:
'e'

In [49]:
s[2], s[3], s[4]


Out[49]:
('l', 'l', 'o')
String slicing

We can extract a part of a string.

Indexing starts with 0 and not 1!


In [50]:
s[0:5]


Out[50]:
'Hello'

In [51]:
s[:5]  # From start.


Out[51]:
'Hello'

In [52]:
s[6:]  # Till end.


Out[52]:
'world'

In [53]:
s[:]  # From start and till end!


Out[53]:
'Hello world'

String concatenation and formatting


In [54]:
a = "foo"
b = "bar"
a + b


Out[54]:
'foobar'

In [55]:
a + " "  + b


Out[55]:
'foo bar'

In [56]:
s.count("l")


Out[56]:
3

In [57]:
s.endswith("ld") # Also works with range


Out[57]:
True

In [58]:
s.upper()


Out[58]:
'HELLO WORLD'

In [59]:
s.lower()


Out[59]:
'hello world'

In [60]:
s2 = " " + s + "\n"
s2


Out[60]:
' Hello world\n'

Important string functions

strip()

Removes the whitespaces from the ends of a string.


In [61]:
s2.strip() # Performs both lstrip() and rstrip()


Out[61]:
'Hello world'

In [62]:
s2.strip("\n")


Out[62]:
' Hello world'
split()

Splits the string into a list according to the passed delimiter


In [63]:
s2.split()


Out[63]:
['Hello', 'world']

In [64]:
s2.split("l")


Out[64]:
[' He', '', 'o wor', 'd\n']
replace()

Replaces a substring of the string with the passed string


In [65]:
# replace a substring in a string with somethign else
s2.replace("world", "test")


Out[65]:
' Hello test\n'
find()/index()

Searches for the passed value in the entire string and returns its index. The only difference between find() and index() is that find returns -1 when the string is not found while index() raises an error.


In [66]:
s2.find("wo")


Out[66]:
7

In [67]:
s2.index("wo")


Out[67]:
7

In [68]:
s2.find("te")


Out[68]:
-1

In [69]:
s2.index("te")


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-69-eb748b844795> in <module>()
----> 1 s2.index("te")

ValueError: substring not found

Lists

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.


In [70]:
list1 = [1, 2, 4, 2]
print list1

list2 = ["hey", "how", "are", "you"]
print list2


[1, 2, 4, 2]
['hey', 'how', 'are', 'you']

In [71]:
list3 = [1, 2, 4, 'hello', '34', 'hi', 23, [45, 23, 7], 2]
print list3


[1, 2, 4, 'hello', '34', 'hi', 23, [45, 23, 7], 2]

So the best thing about a list is that it can hold any data type inside it and is also very fast. You can iterate through millions of values in a list in a matter of seconds

indexing

In [72]:
list1[2]


Out[72]:
4

In [73]:
list1[-1]


Out[73]:
2
list.index()

Similar to the index function of string. Returns the index of the specified object.


In [74]:
list4.index(5)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-74-eefe8040a2f1> in <module>()
----> 1 list4.index(5)

NameError: name 'list4' is not defined

In [75]:
list4.index(6)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-75-7c505fde3909> in <module>()
----> 1 list4.index(6)

NameError: name 'list4' is not defined
list.append()

Adds a new entry at the end of the list


In [76]:
list1.append(100)
print list1


[1, 2, 4, 2, 100]

In [77]:
list4 = list1 + list2
print list4


[1, 2, 4, 2, 100, 'hey', 'how', 'are', 'you']
list.pop()

Removes the last value from the list if no index is specified, otherwise removes the object at the specified index


In [78]:
list4.pop()


Out[78]:
'you'

In [79]:
list4.pop(1)


Out[79]:
2

In [80]:
print list4


[1, 4, 2, 100, 'hey', 'how', 'are']
list.extend()

Extends the list with the values of the parameter


In [81]:
tuple1 = (1, 2, 3)
print list4 + tuple1


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-81-173afe278179> in <module>()
      1 tuple1 = (1, 2, 3)
----> 2 print list4 + tuple1

TypeError: can only concatenate list (not "tuple") to list

In [82]:
list4 = [1,24,5,5]
list4.extend(tuple1)
print list4


[1, 24, 5, 5, 1, 2, 3]
list.count()

Counts the number of occurences of the given object


In [83]:
list4.count(5)


Out[83]:
2
list.sort()

Sorts the given list.


In [84]:
list4.sort()
print list4


[1, 1, 2, 3, 5, 5, 24]

In [85]:
list5 = ["hey", "how", "are", "you"]
list5.sort()
print list5


['are', 'hey', 'how', 'you']

In [86]:
list5.sort(key=lambda x : x[len(x)-1]) # Can also take functions as arguments for sorting.
print list5


['are', 'you', 'how', 'hey']

In [87]:
list5.sort(reverse=True) # Sort in reverse order
print list5


['you', 'how', 'hey', 'are']
list.insert()

Inserts the passed object at the specified position.


In [88]:
print list5
list5.insert(0, "hi")
print list5


['you', 'how', 'hey', 'are']
['hi', 'you', 'how', 'hey', 'are']
list.reverse()

Reverse the contents of the list.


In [89]:
print list5
list5.reverse()
print list5


['hi', 'you', 'how', 'hey', 'are']
['are', 'hey', 'how', 'you', 'hi']
range()

Generates a list from the range of numbers provided.


In [90]:
range(1,20)


Out[90]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [91]:
range(1,20,3)


Out[91]:
[1, 4, 7, 10, 13, 16, 19]

Dictionary

Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables.


In [92]:
dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

In [93]:
dict1['Beth'] # Accessing the value of a key


Out[93]:
'9102'

In [94]:
dict1['Alice'] = '3111' # Editing the value of a key
print dict1


{'Beth': '9102', 'Alice': '3111', 'Cecil': '3258'}

In [95]:
dict1['James'] = '4212' # Adding a value to a dict
print dict1


{'James': '4212', 'Beth': '9102', 'Alice': '3111', 'Cecil': '3258'}

In [96]:
del dict1['Alice']
print dict1


{'James': '4212', 'Beth': '9102', 'Cecil': '3258'}
dict.keys()

Get all the keys form the dictionary


In [97]:
print dict1.keys()


['James', 'Beth', 'Cecil']
dict.values()

Get all the values from the dictionary


In [98]:
print dict1.values()


['4212', '9102', '3258']
dict.items()

Get all the key:value pairs from the dictionary as tuples in a list


In [99]:
print dict1.items()


[('James', '4212'), ('Beth', '9102'), ('Cecil', '3258')]
dict.has_key()

Check if a particular entry exists in a dictionary


In [100]:
print dict1.has_key('Cecil')


True

In [101]:
dict1['Alice']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-101-7eef7cd23496> in <module>()
----> 1 dict1['Alice']

KeyError: 'Alice'

In [102]:
print dict1.has_key('Alice')


False
dict.update()

Update the first dictionary with the contents of the second dictionary


In [103]:
dict2 = {'a':1, 'b':'54', 'c':'hello'}

In [104]:
dict2.update(dict1)
print dict2


{'a': 1, 'c': 'hello', 'b': '54', 'James': '4212', 'Beth': '9102', 'Cecil': '3258'}

if / else

Note: Python uses indentation to group things.


In [105]:
if 2 > 1:
    print "Hello World!"


Hello World!

In [106]:
if 1 > 2:
    print "Hello World!"
else:
    print "World is not a beautiful place!"


World is not a beautiful place!

In [107]:
if 1 > 2:
    print "Hello World!"
elif 2 > 3:
    print "World is even better!"
elif 3 > 4:
    print "I don't want to live here!"
else:
    print "World is not a beautiful place!"


World is not a beautiful place!
if / else with strings and lists

In [108]:
print list1
print s


[1, 2, 4, 2, 100]
Hello world

In [109]:
if 4 in list1:
    print "Hey! 2 exists in list1"


Hey! 2 exists in list1

In [110]:
if 2 in list1:
    i = list1.index(2)
    print "Search successful. Found at index {0}".format((i+1))


Search successful. Found at index 2

In [111]:
if 'o' in s:
    print "'o' exists!"


'o' exists!

In [112]:
if 'llo' in s:
    print "'llo' exists!"


'llo' exists!

In [113]:
if 'house' not in s:
    print "house not found!"


house not found!

In [113]:


In [113]:


In [ ]: