#!/usr/bin/env python # coding: utf-8 # Ignore this, this is just to apply styple to this notebook # In[1]: from IPython.core.display import HTML def css_styling(): styles = open(r'custom.css', 'r').read() return HTML(styles) css_styling() # In[2]: from IPython.display import Image # # **Quick Introduction to Basic Python** # by sukhbinder singh # Ignore the below for now, but make sure its executed # In[3]: get_ipython().run_line_magic('pylab', 'inline') # Lets give a quick check # ##### Just like matlab plots the numbers. So lets start from the start. # In[4]: plot([1,2,3,4]) # In[5]: 2+3 # In[6]: 3**3 # In[7]: 2+3*4+56+67 # # Basically works as a calculator, practice creating calculation # In[8]: #practice one # In[9]: #practice two # # Question for you # ##### So now you know that anything that starts with **"#"** is a comment in python. This will not be executed by the interpretor # # Just getting a calcultor is not enough, lets declare some **variables**. # In[10]: a=2 b=3 # In[11]: print a,b # ##### So we define two variables a and b and print is used to check their values and use them to do some interesting things # In[12]: type(a) # In[13]: print a,'\n',b # In[14]: print a**b # Notice the double ** for power # In[15]: print a*b # In[16]: print a-b # In[17]: print a+b # # Question for you # In[18]: print a,b # ##### What will be printed when we do ** b / a ** ? # In[19]: print b/a # ##### What!!! Is this right? What is going on? # In[20]: print 3/2 # ##### Lets Check the type? # In[21]: print type(a),type(b) # but.... # In[22]: print 3.0/2 # # Beware of integer division. # # One more Question? # ##### What is the operator for not equal to ? # In[23]: # Equal to operator is print 3==3 # In[24]: # write the operation for not equal to, # ##### Ok we just defined interger and float, we can also define other type of variables. # In[25]: logical = False # logical variable # In[26]: print logical logical = True print logical # ##### Lets check type. # In[27]: print type(logical) # # String variables defined as follows # In[28]: name="python" # In[29]: print name # In[30]: phase=" is cool!" # So what's the output for this command. # # **print name+phase ** # In[31]: print name+phase # ##### **+** concatenates or in simple words joins two strings # # Python does automatic typing depending on what data you put in an object. # # # It converts a data type depending on what you put in it. # # In[32]: # try a=10**4 and b=10**100 and check their types # So we have learnt how to declare python variables, lets try some exercises. # # Question for you # In[33]: # define varible cost_price, sale_price and profit # and calculate and display the profit percentage # In[34]: # define variable width, length, area and circum and # calculate the area and circumference of the rectangle pi=3.14 # In[35]: # define a variable "name" and assign it with your name... # + concatenates a string "is learnig python!" , now check # what happens when you do name * 5 # ##### We can declare a multiline comment with 3 single quote or 3 double quotes as shown below # In[36]: name='''python venkat ''' # # **Lists** # ##### You now know how to define individual variables and print them. # # # # ##### What about if you need collection of varibales, so lets use **lists**. # # # Lists are types of arrays # In[37]: # Created using square brackets alist=[1,2,3,4,5] # In[38]: print alist # ##### We define a list named **alist** which contains list of numbers from 1 to 5, we can add more numbers to it # In[39]: alist.append(6) # In[40]: print alist # ##### so **append** adds a number, what about **removing** a number? # In[41]: alist.pop() # # Lists can be changed in place which is called being “mutable” # In[42]: alist[1]=666 # In[43]: print alist # ##### So **pop** removes the last number out of the list. So remember **append** and **pop** # # What else can we do with lists. # ##### Here are some examples. # In[44]: # add some more numbers alist.append(60 ) alist.append(23) # In[45]: print alist # In[46]: # find out how many numbers in a list print len(alist) # In[47]: # sort the list print sorted(alist) # ##### Bounds are automatically enforced when retrieving items and extended when storing them. # # In[48]: alist[0] # In[49]: # plot this list plot(alist) # ##### How about adding multiple items? # In[50]: # to insert multiple items in the list alist.extend([101,202,303,404]) # In[51]: print alist # ##### Till now we just added only integer items to the list, but list is **secular** # # ##### It can contain all other type. # # ##### Lets see some examples # In[52]: # add a string variable in above list alist.append("Derby") # In[53]: print alist # In[54]: alist.append("value of pi") alist.append(3.14) # In[55]: print alist # ##### So we see a list can contain all sorts of types. But what will happen if i want to sort this list, lets find out # In[56]: print sorted(alist) # ##### So it behaves as expected, 3.14 is between 3 and 4 and D is ahead of v. so lets add one more and check the sort # In[57]: alist.append("Apple") # added apple, it should come before sukhbinder print sorted(alist) # In[58]: print alist # ##### Now we know we can use **len** to find the number items in the list, but what about getting them and using them. How do we fetch them individually? # # # # ##### How do we get the one at 1? # ##### When I learnt counting in tamil, 0 was the last count that I learnt, I started with 1 But in python everything starts with > **0** # In[59]: print alist # In[60]: # so the to get the first item print alist[0] # In[61]: # to get the value of pi print alist[17] # ##### To get the last item of the list we can use **-1** # In[ ]: print alist[-1] # ##### What will happeren if we use -2? # In[ ]: print alist[-2] # # Question for you # In[ ]: # create a list containg squares of the number from 2 to 8 # append squares of the number 9 and 10 to it. # plot the list # In[ ]: # create a list of your favourite fruits in order of your preference # print the name of the least favorite fruit using the indices. # In[ ]: # create a newlist called **combined** and put the above two list together # sort and print the new list # ##### The boolean operators are spelled out as words **and**,**not**, **or** # In[ ]: True and False # In[ ]: True or False # In[ ]: not False # # Dictionaries # ##### Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is `{key1 : value1, ...}`: # # Dictionaries are unordered lists of objects stored with reference to a key. # In[ ]: #Created with curly brackets {} PriceList = {"apples" : 100.0, "Mango" : 200.0, "Pineapple" : 30.0,} # In[ ]: print(type(PriceList)) # # A Dictionary is like a hash table. # # ##### Accessing all Values # In[ ]: print(PriceList) # ##### Accessing single values # In[ ]: print PriceList["Mango"] # ##### Print all keys # In[ ]: PriceList.keys() # ##### Just like lists, **dictionaries** has many useful methods associated with it, explore. # # Question for you # In[ ]: # How can you create an empty dictionary and a list and add something to it # # Control Flow # ##### Conditional statements: if, elif, else # # The Python syntax for conditional execution of code use the keywords `if`, `elif` (else if), `else`: # In[ ]: statement1 = True statement2 = False if statement1: print("statement1 is True") elif statement2: print("statement2 is True") else: print("statement1 and statement2 are False") # # Indentation level # ##### In C blocks are defined by the enclosing curly brakets `{` and `}`. And the level of indentation (white space before the code statements) does not matter (completely optional). # # # ##### But in Python, the extent of a code block is defined by the **indentation level** (usually a tab or say four white spaces). # #

# # ##### This means that we have to be careful to indent our code correctly, or else we will get syntax errors. # ##### This enforces a consistent appearance aiding readability and avoiding common errors. # # # **`for` loop**: # # In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. # # # ##### Check examples for basic syntax # In[ ]: for x in [1,2,3]: print(x) # In[ ]: for x in range(-3,3): print(x) # ##### Notice the use of **range** in the above code # ##### Syntax is # # ##### for **variable** in **iterator**: # # One more example using text list # In[ ]: things = ['tv', 'laptop', 'chair', 'mobile', 'table'] for name in things: print name # # Questions for you # In[ ]: # find the square of first 1 to 10 numbers using for loop # In[ ]: # Write a program to iterate find len of each word from the below text text = "Do what is right not what is easy" # In[ ]: # Write a program to find if text contains the word "hard" text = "Do what is right not what is easy" # # List comprehensions # ##### List comprehensions are a tool for transforming one list (any iterable actually) into another list. # In[ ]: print [num**2 for num in range(1,11)] # In[ ]: a= [(word,len(word)) for word in text.split()] # In[ ]: print a print type(a[0]) # # **`while` loop**: # In[ ]: i = 0 while i < 5: print(i) i = i + 1 print("done") # In[ ]: # another example i=0 while True: print i, i+=1 if (i >5): break print "done!" # # **Functions** # # ##### A function in Python is defined using the keyword `def`, followed by a function name, a signature within parentheses `()`, and a colon `:`. # ##### The following code, with one additional level of indentation, is the function body. # In[ ]: # Defined using the def keyword def testFunction(): print("If at first you don’t succeed; call it version 1.0.!!") # In[ ]: testFunction() # In[ ]: def func1(s): """ Print a string 's' and tell how many characters it has """ print(s + " has " + str(len(s)) + " characters") # In[ ]: help(func1) # ##### Notice the doc string # In[ ]: func1("Python is cool") # In[ ]: help(testFunction) # # So always write a doc string... # # # ##### Return is optional and then you effectively get a “procedure” but a None value is returned # ##### Define some functions that return and take a argument # In[ ]: def square(x): """ Return the square of x. """ return x ** 2 # In[ ]: square(4) # In[ ]: # Functions can return multiple values def powers(x): """ Return a few powers of x. """ return x ** 2, x ** 3, x ** 4 # In[ ]: powers(4) # In[ ]: # Calling function using keywords powers(x=2) # # Remember: # # ##### All objects including functions can be passed. # ##### Default arguments must follow all non-default arguments. # ##### Two special argument catchers. # ##### ** *x ** puts all remaining positional args into a list x. Must come after all normal argusments and defaults # ##### double x pulls all remaining args in a dictionary # # # Questions for you # In[ ]: # write a function to write out times tables for a given number # 9 x 1 = 9 # 9 x 2 = 18 # etc # In[ ]: # write a function that calculates distance between two points (x1,y1) (x2,y2) x1,y1 = 0.0,0.0 x2,y2 = 10.0,10.0 # In[ ]: # write a function that takes a text string and returns a dictonary of word and its len # text = "Hard work beats talent when latent doesn't work hard" # # # **Files** # # ##### Files are objects that are created using the built in open function. # # # ##### f=**open**(filename,opt) # # ##### opt can be **"r"**, **"w"** etc # # # # # # In[ ]: # In[ ]: # Lets open a file and write out our alist one line at a time into the file fp=open('ourfile.txt',"w") # In[ ]: for word in alist: fp.write(str(word)+'\n') # In[ ]: fp.close() # In[ ]: get_ipython().system('type ourfile.txt') # In[ ]: # Lets write out the dictionary keys PriceList that we created earlier fp=open('ourfile2.txt',"w") # In[ ]: fp.writelines(PriceList.keys()) # In[ ]: fp.close() # In[ ]: get_ipython().system('type ourfile2.txt') # # **Classes** # # ##### Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object. # ##### In Python a class can contain *attributes* (variables) and *methods* (functions). # ##### A class is defined almost like a function, but using the `class` keyword, and the class definition usually contains a number of class method definitions (a function in a class). # * Each class method should have an argument `self` as it first argument. This object is a self-reference. # # * Some class method names have special meaning, for example: # # * `__init__`: The name of the method that is invoked when the object is first created. # * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed. # * There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names # # Lets define a Point class # In[ ]: class Point: """ Simple class for representing a point in a Cartesian coordinate system. """ def __init__(self, x, y): """ Create a new Point at x, y. """ self.x = x self.y = y def translate(self, dx, dy): """ Translate the point by dx and dy in the x and y direction. """ self.x += dx self.y += dy def __str__(self): return("Point at [%f, %f]" % (self.x, self.y)) # ##### To create a new instance of a class: # In[ ]: p1 = Point(0, 0) # this will invoke the __init__ method in the Point class print(p1) # this will invoke the __str__ method # ##### Lets check type # In[ ]: print (type(p1)) # ##### Lets check its methods # In[ ]: dir(p1) # In[ ]: p2 = Point(1, 1) p1.translate(0.25, 1.5) print(p1) print(p2) # # Questions for you # In[ ]: # Create a class rectangle, implement area and perimeter calculation as its methods class rectangle: """ Simple class for representing a rectangle. """ # ##### Create a class to represent a simple cantilever beam # # $$\delta_B = \frac {F L^3} {3 E I}$$ # # $$\phi_B = \frac {F L^2} {2 E I}$$ # where # # * F = Force acting on the tip of the beam # * L = Length of the beam (span) # * E = Modulus of elasticity # * I = Area moment of inertia # # # In[ ]: # Cantilever class # # **Modules** # # ##### One of the most important concepts in good programming is to reuse code and avoid repetitions. # # # # # # ##### The idea is to write functions and classes with a well-defined purpose and scope, and reuse these instead of repeating similar code in different part of a program (modular programming). The result is usually that readability and maintainability of a program is greatly improved. # # # ##### What this means in practice is that our programs have fewer bugs, are easier to extend and debug/troubleshoot. # # # # ##### Most of the functionality in Python is provided by *modules*. # # ##### The Python Standard Library is a large collection of modules that provides *cross-platform* implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more. # ### References # # * The Python Language Reference: http://docs.python.org/2/reference/index.html # * The Python Standard Library: http://docs.python.org/2/library/ # # # ##### To use a module in a Python program it first has to be imported. # # # ##### A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do: # In[ ]: import math # ##### This includes the whole module and makes it available for use later in the program. For example, we can do: # In[ ]: x = math.cos(2 * math.pi) print(x) # In[ ]: # print the value of pi print math.pi # In[ ]: # Second method of importing (not recommended) from math import * x = cos(2 * pi) print(x) # In[ ]: # Third method of importing a module from math import cos,pi x=cos(2*pi) print x # # # Few Inbuilt modules # # sys # ##### 1. path: contains the list of directions python imports from. # ##### 2. argv: a list of the arguments supplied on the command line. # ##### 3. stdin,stdout,stderr: file objects that handle the standard file handlers. # # # os # ##### Generic operating system commands. # ##### **getcwd**, ***listdir(path)**, **system(cmd)** # # # Json # In[ ]: import json # In[ ]: # Find what are its available methods print dir(json) # # Tar file # In[ ]: import tarfile def untar(fname): if (fname.endswith("tar.gz")): tar = tarfile.open(fname) tar.extractall() tar.close() print "Extracted in Current Directory" else: print "Not a tar.gz file: '%s '" % fname # # We have just started, there lot you can do , so explore # # Thank You #