Python Basics
Python Basics
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic
typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing
components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports
modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or
binary form without charge for all major platforms, and can be freely distributed.
Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful
environment for scientific computing.
Python 3
Python 3 is regarded as the future of Python and is the version of the language that is currently in development. A major overhaul, Python 3 was released in late
2008 to address and amend intrinsic design flaws of previous versions of the language. The focus of Python 3 development was to clean up the codebase and
remove redundancy, making it clear that there was only one way to perform a given task.
Major modifications to Python 3.0 included changing the print statement into a built-in function, improve the way integers are divided, and providing more Unicode
support.
At first, Python 3 was slowly adopted due to the language not being backwards compatible with Python 2, requiring people to make a decision as to which version of
the language to use. Additionally, many package libraries were only available for Python 2, but as the development team behind Python 3 has reiterated that there is
an end of life for Python 2 support, more libraries have been ported to Python 3. The increased adoption of Python 3 can be shown by the number of Python
packages that now provide Python 3 support, which at the time of writing includes 339 of the 360 most popular Python packages.
Python 2.7
Following the 2008 release of Python 3.0, Python 2.7 was published on July 3, 2010 and planned as the last of the 2.x releases. The intention behind Python 2.7
was to make it easier for Python 2.x users to port features over to Python 3 by providing some measure of compatibility between the two. This compatibility support
included enhanced modules for version 2.7 like unittest to support test automation, argparse for parsing command-line options, and more convenient classes in
collections.
Because of Python 2.7’s unique position as a version in between the earlier iterations of Python 2 and Python 3.0, it has persisted as a very popular choice for
programmers due to its compatibility with many robust libraries. When we talk about Python 2 today, we are typically referring to the Python 2.7 release as that is
the most frequently used version.
Python 2.7, however, is considered to be a legacy language and its continued development, which today mostly consists of bug fixes, will cease completely in 2020.
Key Differences
While Python 2.7 and Python 3 share many similar capabilities, they should not be thought of as entirely interchangeable. Though you can write good code and
useful programs in either version, it is worth understanding that there will be some considerable differences in code syntax and handling.
Anaconda offers a collection of over 720 open-source packages, and is available in both free and paid versions. The Anaconda distribution ships with the conda
command-line utility. You can learn more about Anaconda and conda by reading the Anaconda Documentation pages.
Why Anaconda?
User level install of the version of python you want
Able to install/update packages completely independent of system libraries or admin privileges
conda tool installs binary packages, rather than requiring compile resources like pip - again, handy if you have limited privileges for installing necessary
libraries.
More or less eliminates the headaches of trying to figure out which version/release of package X is compatible with which version/release of package Y, both of
which are required for the install of package Z
Comes either in full-meal-deal version, with numpy, scipy, PyQt, spyder IDE, etc. or in minimal / alacarte version (miniconda) where you can install what you
want, when you need it
No risk of messing up required system libraries
Installing on Windows
1. Download the Anaconda installer (https://www.continuum.io/downloads).
2. Optional: Verify data integrity with MD5 or SHA-256. More info on hashes
3. Double click the installer to launch.
NOTE: If you encounter any issues during installation, temporarily disable your anti-virus software during install, then re-enable it after the installation
concludes. If you have installed for all users, uninstall Anaconda and re-install it for your user only and try again.
4. Click Next.
5. Read the licensing terms and click I Agree.
6. Select an install for “Just Me” unless you’re installing for all users (which requires Windows Administrator privileges).
7. Select a destination folder to install Anaconda and click Next.
NOTE: Install Anaconda to a directory path that does not contain spaces or unicode characters.
Installing on macOS
1. Download the graphical macOS installer (https://www.continuum.io/downloads#macos) for your version of Python.
2. OPTIONAL: Verify data integrity with MD5 or SHA-256. For more information on hashes, see What about cryptographic hash verification?.
3. Double-click the .pkg file.
4. Answer the prompts on the Introduction, Read Me and License screens.
5. On the Destination Select screen, select Install for me only.
NOTE: If you get the error message “You cannot install Anaconda in this location,” reselect Install for me only.
6. On the Installation Type screen, you may choose to install in another location. The standard install puts Anaconda in your home user directory:
7. Click the Install button.
8. A successful installation displays the following screen:
Installing on Linux
1. In your browser, download the Anaconda installer for Linux.
2. Optional: Verify data integrity with MD5 or SHA-256. (For more information on hashes, see cryptographic hash validation.)
sha256sum /path/filename
3. Verify results against the proper hash page to make sure the hashes match.
4. Enter the following to install Anaconda for Python 3.6:
bash ~/Downloads/Anaconda3-4.4.0-Linux-x86_64.sh OR
bash ~/Downloads/Anaconda2-4.4.0-Linux-x86_64.sh NOTE: You should include the bash command regardless of whether you are using Bash shell.
The installer prompts “Do you wish the installer to prepend the Anaconda"2 or 3" install location to PATH in your /home/"user"/.bashrc ?” We recommend yes.
NOTE: If you enter “no”, you will need to manually specify the path to Anaconda when using Anaconda. To manually add the prepended path, edit file .bashrc to
add ~/anaconda"2 or 3"/bin to your path manually using:
8. export PATH="/home/"user"/anaconda"2 or 3"/bin:$PATH" Replace /home/"user"/anaconda"2 or 3" with the actual path.
9. The installer finishes and displays “Thank you for installing Anaconda"2 or 3"!”
10. Close and open your terminal window for the installation to take effect, or you can enter the command source ~/.bashrc.
Enter conda list. If the installation was successful, the terminal window should display a list of installed Anaconda packages.
NOTE: Power8 users: Navigate to your Anaconda directory and run this command:
The notebook is a web application that allows you to combine explanatory text, math equations, code, and visualizations all in one easily sharable document.
Notebooks have quickly become an essential tool when working with data. You'll find them being used for data cleaning and exploration, visualization, machine
learning, and big data analysis. Typically you'd be doing this work in a terminal, either the normal Python shell or with IPython. Your visualizations would be in
separate windows, any documentation would be in separate documents, along with various scripts for functions and classes. However, with notebooks, all of these
are in one place and easily read together.
Notebooks are also rendered automatically on GitHub. It’s a great feature that lets you easily share your work. There is also http://nbviewer.jupyter.org/
(http://nbviewer.jupyter.org/) that renders the notebooks from your GitHub repo or from notebooks stored elsewhere.
The central point is the notebook server. You connect to the server through your browser and the notebook is rendered as a web app. Code you write in the web
app is sent through the server to the kernel. The kernel runs the code and sends it back to the server, then any output is rendered back in the browser. When you
save the notebook, it is written to the server as a JSON file with a .ipynb file extension.
The great part of this architecture is that the kernel doesn't need to run Python. Since the notebook and the kernel are separate, code in any language can be sent
between them. For example, two of the earlier non-Python kernels were for the R and Julia languages. With an R kernel, code written in R will be sent to the R
kernel where it is executed, exactly the same as Python code running on a Python kernel. IPython notebooks were renamed because notebooks became language
agnostic. The new name Jupyter comes from the combination of Julia, Python, and R.
Another benefit is that the server can be run anywhere and accessed via the internet. Typically you'll be running the server on your own machine where all your data
and notebook files are stored. But, you could also set up a server on a remote machine or cloud instance like Amazon's EC2. Then, you can access the notebooks
in your browser from anywhere in the world.
By far the easiest way to install Jupyter is with Anaconda. Jupyter notebooks automatically come with the distribution. You'll be able to use notebooks from the
default environment.
To install Jupyter notebooks in a conda environment, use conda install jupyter notebook.
When you run the command (try it yourself!), the server home should open in your browser. By default, the notebook server runs at http://localhost:8888
(http://localhost:8888). If you aren't familiar with this, localhost means your computer and 8888 is the port the server is communicating on. As long as the server is
still running, you can always come back to it by going to http://localhost:8888 (http://localhost:8888) in your browser.
If you start another server, it'll try to use port 8888, but since it is occupied, the new server will run on port 8889. Then, you'd connect to it at http://localhost:8889
(http://localhost:8889). Every additional notebook server will increment the port number like this.
Integers
Integer literals are created by any number without a decimal or complex component.
In [2]: # integers
x = 1
print(x)
y=5
print(y)
z="Sayan"
print(z)
1
5
Sayan
In [3]: #Implicit Printing
x
Out[3]: 1
Floats
Float literals can be created by adding a decimal component to a number.
5.7
3
1.0
5.6
Boolean
Boolean can be defined by typing True/False without quotes
True
6
Strings
String literals can be defined with any of single quotes ('), double quotes (") or triple quotes (''' or """). All give the same result with two important differences.
If you quote with single quotes, you do not have to escape double quotes and vice-versa. If you quote with triple quotes, your string can span multiple lines.
In [6]: a="Sayan"
b=5
print(type(a))
print(type(b))
<class 'str'>
<class 'int'>
In [7]: # string
name1 = 'your name'
print(name1)
name2 = "He's coming to the party"
print(name2)
name3 = '''XNews quotes : "He's coming to the party"'''
print(name3)
your name
He's coming to the party
XNews quotes : "He's coming to the party"
In [8]: import this
Variables
Definining
A variable in Python is defined through assignment. There is no concept of declaring a variable outside of that assignment.
In [9]: a=10
a="Sayan"
a=5.6
a=True
print(a)
True
The names you use when creating these labels need to follow a few rules:
Strong Typing
While Python allows you to be very flexible with your types, you must still be aware of what those types are. Certain operations will require certain types as
arguments.
In [10]: print(5+6)
11
In [11]: a=5
b=6
c=a+b
print(c)
11
In [12]: 6*7
Out[12]: 42
In [13]: #Concatenation
'Hello'+'World'
Out[13]: 'HelloWorld'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-643fe001d103> in <module>()
----> 1 'Day ' + 1
<class 'int'>
<class 'str'>
In [16]: #Typecasting
print('Day ' + str(1))
Day 1
Simple Expressions
In [17]: True and False
Out[17]: False
Out[18]: True
Out[19]: False
Out[20]: True
In [22]: # Addition and subtraction
print(5 + 5)
print(5 - 5)
# Exponentiation
print(4 ** 2)
# Modulo
print(18 % 7)
10
0
15
5.0
16
4
194.87171000000012
We can then expand the idea further with elif and else statements, which allow us to tell the computer:
"Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happened, perform this
action."
Let's go ahead and look at the syntax format for if statements to get a better idea of this:
if case1:
perform action1
elif case2:
perform action2
else:
perform action3
In [ ]:
Each line of code in a certain block level must be indented equally and indented more than the surrounding scope. The standard (defined in PEP-8) is to use 4
spaces for each level of block indentation. Statements preceding blocks generally end with a colon (:).
Because there are no semi-colons or other end-of-line indicators in Python, breaking lines of code requires either a continuation character (\ as the last char) or for
the break to occur inside an unfinished structure (such as open parentheses).
Lists
The first container type that we will look at is the list. A list represents an ordered, mutable collection of objects. You can mix and match any type of object in a list,
add to it and remove from it at will.
Creating Empty Lists. To create an empty list, you can use empty square brackets or use the list() function with no arguments.
<class 'list'>
In [36]: marks_student[0]
Out[36]: 10
In [30]: l = []
l
Out[30]: []
In [31]: l = list()
l
Out[31]: []
Out[34]: 'a'
In [35]: l = ['a',6]
l
Out[35]: ['a', 6]
# Print areas
print(areas[2])
print(type(areas))
kitchen
<class 'list'>
[['hallway', 11.25], ['kitchen', 18.0], ['living room', 20.0], ['bedroom', 10.75], ['bathroom', 9.5]]
<class 'list'>
In [41]: print(house[1])
print(type(house[1]))
['kitchen', 18.0]
<class 'list'>
In [42]: print(house[1][1])
print(type(house[1][1]))
18.0
<class 'float'>
A Python string is also a sequence of characters and can be treated as an iterable over those characters. Combined with the list() function, a new list of the
characters can easily be generated.
In [43]: list('abcdef')
Adding. You can append to a list very easily (add to the end) or insert at an arbitrary index.
In [44]: l = []
l.append('b')
print(l)
l.append('c')
print(l)
l.insert(1, 56)
l
#Implicit Printing
['b']
['b', 'c']
String Basics
In Strings, the length of the string can be found out by using a function called len().
Out[49]: 11
String Indexing
We know strings are a sequence, which means Python can use indexes to call all the sequence parts. Let's learn how String Indexing works. • We use brackets []
after an object to call its index. • We should also note that indexing starts at 0 for Python. Now, Let's create a new object called s and the walk through a few
examples of indexing.
Out[3]: 'e'
In [51]: #Check
s
Hello World
Out[53]: 'H'
In [54]: s[1]
Out[54]: 'e'
In [55]: s[2]
Out[55]: 'l'
We can use a : to perform slicing which grabs everything up to a designated point. For example:
In [60]: # Grab everything past the first term all the way to the length of s which is len(s)
s[1:]
Out[62]: 'Hel'
Note the above slicing. Here we're telling Python to grab everything from 0 up to 3. It doesn't include the 3rd index. You'll notice this a lot in Python, where
statements and are usually in the context of "up to, but not including".
In [63]: #Everything
s[:]
Out[64]: 'd'
String Properties
Immutability is one the finest string property whichh is created once and the elements within it cannot be changed or replaced. For example:
In [66]: s
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-67-976942677f11> in <module>()
1 # Let's try to change the first letter to 'x'
----> 2 s[0] = 'x'
In [73]: 7*6
Out[73]: 42
In [74]: print('demo'*10)
demodemodemodemodemodemodemodemodemodemo
Print Formatting
Print Formatting ".format()" method is used to add formatted objects to the printed string statements.
In [75]: print('Insert another string with curly brackets: {}'.format('The inserted string'))
print('My first name is {0}. Last name is {1}'.format('Sayan','Dey'))
Out[77]: 'one'
We can also use "+" to concatenate lists, just like we did for Strings.
In [81]: my_list
In this case, you have to reassign the list to make the permanent change.
In [82]: # Reassign
my_list = my_list + ['add new item permanently']
In [83]: my_list
In [84]: 'Zoo'*10
Out[84]: 'ZooZooZooZooZooZooZooZooZooZoo'
Out[86]: ['one',
'two',
'three',
4,
5,
'add new item permanently',
'one',
'two',
'three',
4,
5,
'add new item permanently']
In [99]: # Append
l=[1,2,3]
l.append('append me!')
In [100]: # Show
l
Use pop to "pop off" an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let's see an example:
Out[101]: 1
In [102]: # Show
l
In [104]: popped_item
Out[105]: [2, 3]
Note that lists indexing will return an error if there is no element at that index. For example:
In [106]: l[100]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-106-e2a0c2623844> in <module>()
----> 1 l[100]
We can use the sort method and the reverse methods to also effect your lists:
In [108]: #Show
new_list
In [110]: new_list
In [111]: # Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
In [112]: new_list
List Comprehensions
In [170]: first_col
Out[170]: [1, 4, 7]
In [1]: l = [1,2,3]
In [2]: l.count(10)
Out[2]: 0
In [3]: l.count(2)
Out[3]: 1
In [4]: l.index(2)
Out[4]: 1
In [5]: l.index(12)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-da9218b18168> in <module>()
----> 1 l.index(12)
In [7]: l
Out[7]: [1, 2, 3]
In [9]: l
In [11]: l
In [12]: ele
Out[12]: 3
In [13]: l
In [14]: l.remove('inserted')
In [15]: l
Out[15]: [1, 2]
In [16]: l = [1,2,3,4,3]
In [17]: l.remove(3)
In [18]: l
Out[18]: [1, 2, 4, 3]
In [ ]:
Loops
In [113]: # Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4,9]
Printing
6
Printing
11
Printing
14
Printing
22
Printing
26
Printing
28
Printing
33
Printing
37
Printing
46
The sum is 46
sum = 0
i = 1
The sum is 55
In [1]: print(range(10))
range(0, 10)
In [2]: print(list(range(100)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 99]
[2, 3, 4, 5, 6, 7]
[2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117, 122, 127, 132, 137,
142, 147, 152, 157, 162, 167, 172, 177, 182, 187, 192, 197, 202, 207, 212, 217, 222, 227, 232, 237, 242, 247, 252, 257,
262, 267, 272, 277, 282, 287, 292, 297, 302, 307, 312, 317, 322, 327, 332, 337, 342, 347, 352, 357, 362, 367, 372, 377,
382, 387, 392, 397, 402, 407, 412, 417, 422, 427, 432, 437, 442, 447, 452, 457, 462, 467, 472, 477, 482, 487, 492, 497,
502, 507, 512, 517, 522, 527, 532, 537, 542, 547, 552, 557, 562, 567, 572, 577, 582, 587, 592, 597, 602, 607, 612, 617,
622, 627, 632, 637, 642, 647, 652, 657, 662, 667, 672, 677, 682, 687, 692, 697, 702, 707, 712, 717, 722, 727, 732, 737,
742, 747, 752, 757, 762, 767, 772, 777, 782, 787, 792, 797, 802, 807, 812, 817, 822, 827, 832, 837, 842, 847, 852, 857,
862, 867, 872, 877, 882, 887, 892, 897, 902, 907, 912, 917, 922, 927, 932, 937, 942, 947, 952, 957, 962, 967, 972, 977,
982, 987, 992, 997, 1002, 1007, 1012, 1017, 1022, 1027, 1032, 1037, 1042, 1047, 1052, 1057, 1062, 1067, 1072, 1077, 108
2, 1087, 1092, 1097, 1102, 1107, 1112, 1117, 1122, 1127, 1132, 1137, 1142, 1147, 1152, 1157, 1162, 1167, 1172, 1177, 11
82, 1187, 1192, 1197, 1202, 1207, 1212, 1217, 1222, 1227, 1232, 1237, 1242, 1247, 1252, 1257, 1262, 1267, 1272, 1277, 1
282, 1287, 1292, 1297, 1302, 1307, 1312, 1317, 1322, 1327, 1332, 1337, 1342, 1347, 1352, 1357, 1362, 1367, 1372, 1377,
1382, 1387, 1392, 1397, 1402, 1407, 1412, 1417, 1422, 1427, 1432, 1437, 1442, 1447, 1452, 1457, 1462, 1467, 1472, 1477,
1482, 1487, 1492, 1497, 1502, 1507, 1512, 1517, 1522, 1527, 1532, 1537, 1542, 1547, 1552, 1557, 1562, 1567, 1572, 1577,
1582, 1587, 1592, 1597, 1602, 1607, 1612, 1617, 1622, 1627, 1632, 1637, 1642, 1647, 1652, 1657, 1662, 1667, 1672, 1677,
1682, 1687, 1692, 1697, 1702, 1707, 1712, 1717, 1722, 1727, 1732, 1737, 1742, 1747, 1752, 1757, 1762, 1767, 1772, 1777,
1782, 1787, 1792, 1797, 1802, 1807, 1812, 1817, 1822, 1827, 1832, 1837, 1842, 1847, 1852, 1857, 1862, 1867, 1872, 1877,
1882, 1887, 1892, 1897, 1902, 1907, 1912, 1917, 1922, 1927, 1932, 1937, 1942, 1947, 1952, 1957, 1962, 1967, 1972, 1977,
1982, 1987, 1992, 1997]
We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate though a sequence using
indexing. Here is an example.
I like pop
I like rock
I like jazz
I like sapna
In [9]: print(len(genre))
print(list(range(len(genre))))
4
[0, 1, 2, 3]
I like pop
I like rock
I like jazz
I like sapna
print("The end")
s
t
r
The end
print("The end")
s
t
r
n
g
The end
Tuples
In Python, tuples are similar to lists but they are immutable i.e. they cannot be changed. You would use the tuples to present data that shouldn't be changed, such
as days of week or dates on a calendar.
Out[33]: 3
# Show
t
Out[34]: ('one', 2)
Out[35]: 'one'
Out[36]: 2
Out[37]: 0
Out[38]: 1
Immutability
As tuples are immutable, it can't be stressed enough and add more into it. To drive that point home:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-39-1257c0aa9edd> in <module>()
----> 1 t[0]= 'change'
Because tuple being immutable they can't grow. Once a tuple is made we can not add to it.
In [40]: t.append('nope')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-40-b75f5b09ac19> in <module>()
----> 1 t.append('nope')
Tuples are not used often as lists in programming but are used when immutability is necessary. While you are passing around an object and if you need to make
sure that it does not get changed then tuple become your solution. It provides a convenient source of data integrity.
You should now be able to create and use tuples in your programming as well as have a complete understanding of their immutability.
room 0: 11.25
room 1: 18.0
room 2: 20.0
room 3: 10.75
room 4: 9.5
Sets
Sets are an unordered collection of unique elements which can be constructed using the set() function.
In [42]: x = set()
Out[44]: {1}
Note that the curly brackets do not indicate a dictionary! Using only keys, you can draw analogies as a set being a dictionary.
We know that a set has an only unique entry. Now, let us see what happens when we try to add something more that is already present in a set?
In [46]: #Show
x
Out[46]: {1, 2}
In [48]: #Show
x
Out[48]: {1, 2}
Notice, how it won't place another 1 there as a set is only concerned with unique elements! However, We can cast a list with multiple repeat elements to a set to get
the unique elements. For example:
{1, 2, 3, 4, 5, 6}
Dictionaries
In [15]: # Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
berlin
<class 'dict'>
dict_keys(['spain', 'france', 'germany', 'norway'])
dict_values(['madrid', 'paris', 'berlin', 'oslo'])
madrid
Note that dictionaries are very flexible in the data types they can hold. For example:
Out[37]: list
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-deb635d37c9c> in <module>()
1 # Can call an index on that value
----> 2 my_dict['key1'][0:2]
Out[39]: 'ITEM0'
In [40]: my_dict['key1']
Out[40]: 123
In [42]: #Check
my_dict['key1']
Out[42]: 0
Out[47]: -123
# Print europe
print(europe)
paris
{'spain': {'capital': 'madrid', 'population': 46.77}, 'france': {'capital': 'paris', 'population': 66.03}, 'germany':
{'capital': 'berlin', 'population': 80.62}, 'norway': {'capital': 'oslo', 'population': 5.084}, 'italy': {'capital': 'r
ome', 'population': 59.83}}
In [54]: #Tuples
(a,b)=(1,2)
In [55]: a
Out[55]: 1
In [56]: b
Out[56]: 2
In [57]: c= (1,2,3)
type(c)
Out[57]: tuple
Dictionary Comprehensions
Functions
In [75]: def name_of_function(arg1,arg2):
'''
This is where the function's Document String (doc-string) goes
'''
# Do stuff here
#return desired result
You'll see the doc-string where you write the basic description of the function. Using iPython and iPython Notebooks, you'll be able to read these doc-strings by
pressing Shift+Tab after a function name. It is not mandatory to include docstrings with simple functions, but it is a good practice to put them as this will help the
programmers to easily understand the code you write
Example 1: A simple print 'hello' function
In [77]: say_hello()
hello
In [79]: greeting('Jose')
Hello Jose
Using return
Let's see some examples that use a return statement. Return allows a function to "return" a result that can then be stored as a variable, or used in whatever manner
a user wants.
In [81]: add_num(4,5)
Out[81]: 9
In [83]: print(result)
In [84]: print(add_num('one','two'))
onetwo
In [86]: is_prime(16)
not prime
In [87]: help(max)
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
In [88]: ?max
# Return shout_words
return shout_words
congratulations!!!
you!!!
# Define change_team()
def change_team():
"""Change the value of the global variable team."""
# Print team
print(team)
# Call change_team()
change_team()
# Print team
print(team)
teen titans
justice league
In [92]: # Define three_shouts
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
hellohello hellohellohello
#Print echo_word
print(echo_word)
#Print echo_word
print(echo_word)
hellohello
hellohello!!!
In [95]: # Define shout_echo
def shout_echo(word1, echo=1, intense=False):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Return echo_word_new
return echo_word_new
HEYHEYHEYHEYHEY!!!
HEY!!!
# Return hodgepodge
return hodgepodge
luke
lukeleiahanobidarth
In [97]: # Define report_status
def report_status(**kwargs):
"""Print out the status of a movie character."""
print("\nBEGIN: REPORT\n")
print("\nEND REPORT")
BEGIN: REPORT
name: luke
affiliation: jedi
status: missing
END REPORT
BEGIN: REPORT
name: anakin
affiliation: sith lord
status: deceased
END REPORT
Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import
command. Before you go ahead and import modules, check out the full list of built-in modules in the Python Standard library.
When a module is loaded into a running script for the first time, it is initialized by executing the code in the module once. If another module in your code imports the
same module again, it will not be loaded twice but once only - so local variables inside the module act as a "singleton" - they are initialized only once.
Out[14]: 3
In [16]: pi
Out[16]: 3.141592653589793
# Calculate C
C = 2 * r * math.pi
# Calculate A
A = math.pi * r ** 2
# Build printout
print("Circumference: " + str(C))
print("Area: " + str(A))
Circumference: 2.701769682087222
Area: 0.5808804816487527
In [2]: # Definition of radius
r = 0.43
import numpy
# Import the math package
from math import pi
# Calculate C
C = 2 * r * pi
# Calculate A
A = pi * r ** 2
# Build printout
print("Circumference: " + str(C))
print("Area: " + str(A))
Circumference: 2.701769682087222
Area: 0.5808804816487527
In [6]: print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'at
anh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',
'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'l
og', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'tru
nc']
When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:
In [103]: help(math.ceil)
ceil(...)
ceil(x)
In [104]: print('Hello)
try:
You do your operations here...
...
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
...
else:
If there is no exception then execute this block.
Using just except, we can check for any exception: To understand better let's check out a sample code that opens and writes a file:
## example 1
try:
if n > 5 :
print(nm)
except:
print('plz check the code')
In [3]: ## example 2
try:
print(x)
except:
print("An exception occurred")
An exception occurred
In [4]: ## example 3
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
In [5]: ## example 4
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong
In [6]: ## example 5
## try and finally
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
In [105]: try:
f = open('testfile','w')
f.write('Test write this')
except IOError:
# This will only check for an IOError exception and then execute this print statement
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
Now, let's see what happens when we don't have write permission? (opening only with 'r'):
In [106]: try:
f = open('testfile','r')
f.write('Test write this')
except IOError:
# This will only check for an IOError exception and then execute this print statement
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
Notice, how we only printed a statement! The code still ran and we were able to continue doing actions and running code blocks. This is extremely useful when you
have to account for possible input errors in your code. You can be prepared for the error and keep running code, instead of your code just breaking as we saw
above.
We could have also just said except: if we weren't sure what exception would occur. For example:
In [107]: try:
f = open('testfile','r')
f.write('Test write this')
except:
# This will check for any exception and then execute this print statement
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
Now, we don't actually need to memorize the list of exception types! Now what if we keep wanting to run code after the exception occurred? This is where finally
comes in.
finally
The finally: Block of code will always be run regardless if there was an exception in the try code block. The syntax is:
try:
Code block here
...
Due to any exception, this code may be skipped!
finally:
This code block would always be executed.
For example:
In [108]: try:
f = open("testfile", "w")
f.write("Test write statement")
finally:
print("Always execute finally code blocks")
Always execute finally code blocks
We can use this in conjunction with except. Let's see a new example that will take into account a user putting in the wrong input:
finally:
print("Finally, I executed!")
print(val)
In [110]: askint()
In [111]: askint()
Check how we got an error when trying to print val (because it was properly assigned). Let's find the right solution by asking the user and checking to make sure the
input type is an integer:
In [113]: askint()
Hmmm...that only did one check. How can we continually keep checking? We can use a while loop!
In [115]: askint()
In [117]: square(25)
Out[117]: 5.0
In [118]: square(25.0)
Out[118]: 5.0
In [119]: square("Hello")
In [120]: square(-25)
map function
The map function allows you to "map" a function to an iterable object. That is to say you can quickly call the same function to every item in an iterable, such as a
list. For example:
In [5]: map(square,my_nums)
In [10]: list(map(splicer,mynames))
In [15]: filter(check_even,nums)
In [16]: list(filter(check_even,nums))
lambda expression
One of Pythons most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create "anonymous" functions. This
basically means we can quickly make ad-hoc functions without needing to properly define a function using def.
Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is key difference that makes lambda
useful in specialized roles:
The lambda's body is similar to what we would put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it.
Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding
simple functions, and def handles the larger tasks.
In [18]: square(2)
Out[18]: 4
In [20]: square(2)
Out[20]: 4
In [22]: square(2)
Out[22]: 4
This is the form a function that a lambda expression intends to replicate. A lambda expression can then be written as:
In [26]: square(2)
Out[26]: 4
So why would use this? Many function calls need a function passed in, such as map and filter. Often you only need to use the function you are passing in once, so
instead of formally defining it, you just use the lambda expression. Let's repeat some of the examples from above with a lambda expression
Here are a few more examples, keep in mind the more comples a function is, the harder it is to translate into a lambda expression, meaning sometimes its just
easier (and often the only way) to create the def keyword function.
You can even pass in multiple arguments into a lambda expression. Again, keep in mind that not every function can be translated into a lambda expression.
You will find yourself using lambda expressions often with certain non-built-in libraries, for example the pandas library for data analysis works very well with lambda
expressions.