## 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 :

'''
variable assignments
this is a variable assignment
'''
x = 1.0
my_variable = 12

``````
``````

In :

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 :

x = 1
type(x)

``````
``````

Out:

int

``````

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

``````

In :

t = x + y

``````
``````

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
----> 1 t = x + y

NameError: name 'y' is not defined

``````

## Fundamental data types

``````

In :

# integers
x = 1
type(x)

``````
``````

Out:

int

``````
``````

In :

# float
x = 1.0
type(x)

``````
``````

Out:

float

``````
``````

In :

# boolean
b1 = True
b2 = False

type(b1)

``````
``````

Out:

bool

``````
``````

In :

# 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 :

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

``````
``````

Out:

complex

``````
``````

In :

print x

``````
``````

(1-1j)

``````
``````

In :

# Real part
print x.real

``````
``````

1.0

``````
``````

In :

# 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 :

a = 1
a

``````
``````

Out:

1

``````
``````

In :

float(a)

``````
``````

Out:

1.0

``````
``````

In :

z = 2 + 3j
z

``````
``````

Out:

(2+3j)

``````
``````

In :

float(z.imag)

``````
``````

Out:

3.0

``````
``````

In :

complex(a)

``````
``````

Out:

(1+0j)

``````
``````

In :

int(45.55)

``````
``````

Out:

45

``````
``````

In :

bool(0)

``````
``````

Out:

False

``````

## Basic boolean algebra

• and
• or
• not
``````

In :

True and True

``````
``````

Out:

True

``````
``````

In :

True and False

``````
``````

Out:

False

``````
``````

In :

True and True and False and True

``````
``````

Out:

False

``````
``````

In :

True or False

``````
``````

Out:

True

``````
``````

In :

False or False

``````
``````

Out:

False

``````
``````

In :

1 and 1

``````
``````

Out:

1

``````
``````

In :

1 and 0

``````
``````

Out:

0

``````
``````

In :

20 and 30  # It just gives you the latter

``````
``````

Out:

30

``````
``````

In :

200 and 30  # I told ya!

``````
``````

Out:

30

``````
``````

In :

0 and 431  # Not here!

``````
``````

Out:

0

``````
``````

In :

1 or 1

``````
``````

Out:

1

``````
``````

In :

1 or 0

``````
``````

Out:

1

``````
``````

In :

21 or 42  # Gives you former

``````
``````

Out:

21

``````
``````

In :

3214 or 42  # Proved!

``````
``````

Out:

3214

``````
``````

In :

not True

``````
``````

Out:

False

``````
``````

In :

not False

``````
``````

Out:

True

``````
``````

In :

not 1

``````
``````

Out:

False

``````
``````

In :

not 0

``````
``````

Out:

True

``````
``````

In :

not 420  # Yep!

``````
``````

Out:

False

``````

## Some universal truths!

``````

In :

1 < 2

``````
``````

Out:

True

``````
``````

In :

2 != 3

``````
``````

Out:

True

``````
``````

In :

22 > 11

``````
``````

Out:

True

``````
``````

In :

5 == 5

``````
``````

Out:

True

``````
``````

In :

2 + 3 == 5

``````
``````

Out:

True

``````

## Strings

Let's get deep!

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

``````

In :

s = "Hello world"
type(s)

``````
``````

Out:

str

``````
``````

In :

# length of the string: the number of characters
len(s)

``````
``````

Out:

11

``````
``````

In :

s  # `s` is still the same! Strings are immutable.

``````
``````

Out:

'Hello world'

``````
``````

In :

s

``````
``````

Out:

'H'

``````
``````

In :

s

``````
``````

Out:

'e'

``````
``````

In :

s, s, s

``````
``````

Out:

('l', 'l', 'o')

``````
##### String slicing

We can extract a part of a string.

Indexing starts with `0` and not `1`!

``````

In :

s[0:5]

``````
``````

Out:

'Hello'

``````
``````

In :

s[:5]  # From start.

``````
``````

Out:

'Hello'

``````
``````

In :

s[6:]  # Till end.

``````
``````

Out:

'world'

``````
``````

In :

s[:]  # From start and till end!

``````
``````

Out:

'Hello world'

``````

#### String concatenation and formatting

``````

In :

a = "foo"
b = "bar"
a + b

``````
``````

Out:

'foobar'

``````
``````

In :

a + " "  + b

``````
``````

Out:

'foo bar'

``````
``````

In :

s.count("l")

``````
``````

Out:

3

``````
``````

In :

s.endswith("ld") # Also works with range

``````
``````

Out:

True

``````
``````

In :

s.upper()

``````
``````

Out:

'HELLO WORLD'

``````
``````

In :

s.lower()

``````
``````

Out:

'hello world'

``````
``````

In :

s2 = " " + s + "\n"
s2

``````
``````

Out:

' Hello world\n'

``````

## Important string functions

##### strip()

Removes the whitespaces from the ends of a string.

``````

In :

s2.strip() # Performs both lstrip() and rstrip()

``````
``````

Out:

'Hello world'

``````
``````

In :

s2.strip("\n")

``````
``````

Out:

' Hello world'

``````
##### split()

Splits the string into a list according to the passed delimiter

``````

In :

s2.split()

``````
``````

Out:

['Hello', 'world']

``````
``````

In :

s2.split("l")

``````
``````

Out:

[' He', '', 'o wor', 'd\n']

``````
##### replace()

Replaces a substring of the string with the passed string

``````

In :

# replace a substring in a string with somethign else
s2.replace("world", "test")

``````
``````

Out:

' 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 :

s2.find("wo")

``````
``````

Out:

7

``````
``````

In :

s2.index("wo")

``````
``````

Out:

7

``````
``````

In :

s2.find("te")

``````
``````

Out:

-1

``````
``````

In :

s2.index("te")

``````
``````

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

``````

## 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 :

list1 = [1, 2, 4, 2]
print list1

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

``````
``````

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

``````
``````

In :

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 :

list1

``````
``````

Out:

4

``````
``````

In :

list1[-1]

``````
``````

Out:

2

``````
##### list.index()

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

``````

In :

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 :

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 :

list1.append(100)
print list1

``````
``````

[1, 2, 4, 2, 100]

``````
``````

In :

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 :

list4.pop()

``````
``````

Out:

'you'

``````
``````

In :

list4.pop(1)

``````
``````

Out:

2

``````
``````

In :

print list4

``````
``````

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

``````
##### list.extend()

Extends the list with the values of the parameter

``````

In :

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 :

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 :

list4.count(5)

``````
``````

Out:

2

``````
##### list.sort()

Sorts the given list.

``````

In :

list4.sort()
print list4

``````
``````

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

``````
``````

In :

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

``````
``````

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

``````
``````

In :

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

``````
``````

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

``````
``````

In :

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 :

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 :

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 :

range(1,20)

``````
``````

Out:

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

``````
``````

In :

range(1,20,3)

``````
``````

Out:

[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 :

dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

``````
``````

In :

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

``````
``````

Out:

'9102'

``````
``````

In :

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

``````
``````

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

``````
``````

In :

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

``````
``````

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

``````
``````

In :

del dict1['Alice']
print dict1

``````
``````

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

``````
##### dict.keys()

Get all the keys form the dictionary

``````

In :

print dict1.keys()

``````
``````

['James', 'Beth', 'Cecil']

``````
##### dict.values()

Get all the values from the dictionary

``````

In :

print dict1.values()

``````
``````

['4212', '9102', '3258']

``````
##### dict.items()

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

``````

In :

print dict1.items()

``````
``````

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

``````
##### dict.has_key()

Check if a particular entry exists in a dictionary

``````

In :

print dict1.has_key('Cecil')

``````
``````

True

``````
``````

In :

dict1['Alice']

``````
``````

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

KeyError: 'Alice'

``````
``````

In :

print dict1.has_key('Alice')

``````
``````

False

``````
##### dict.update()

Update the first dictionary with the contents of the second dictionary

``````

In :

dict2 = {'a':1, 'b':'54', 'c':'hello'}

``````
``````

In :

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 :

if 2 > 1:
print "Hello World!"

``````
``````

Hello World!

``````
``````

In :

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

``````
``````

World is not a beautiful place!

``````
``````

In :

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 :

print list1
print s

``````
``````

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

``````
``````

In :

if 4 in list1:
print "Hey! 2 exists in list1"

``````
``````

Hey! 2 exists in list1

``````
``````

In :

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 :

if 'o' in s:
print "'o' exists!"

``````
``````

'o' exists!

``````
``````

In :

if 'llo' in s:
print "'llo' exists!"

``````
``````

'llo' exists!

``````
``````

In :

if 'house' not in s:

``````
``````

``````
``````

In :

``````
``````

In :

``````
``````

In [ ]:

``````