Python Lesson To Start Coding Instantly
What is Python?
Python is a software language used for developing useful software. It is used extensively by big players like Facebook, Wikipedia etc. It has plenty of support on all the major platforms. And it is very interesting, to say the least.
Why Python?
It has many features that makes it likeable, and preferred over other conventional languages. Some of them are:
- readable
- simple, lesser lines of code
- dynamic type checking
- object oriented
- lists, dictionaries
- automatic memory management
How do I start?
Simple, read about it, practice it and write your own programs :) . If you are a software enthusiast, think of a problem and create a solution for it in Python. W’ll talk about it later..
Some Basics to begin with
Indentation: Python uses whitespace for defining the block of code. It doesn’t use curly braces or any such other brackets. Same number of white spaces defines a block.
Comments: To provide information about the code, comments are used in any programming language. Python uses '#' to define the start of a comment.
print : Print function is used to print messages. It is very useful to understand the working of our code, and is used extensively to find problems. Print can also be used to write the output of some arithmetic calculation, which helps to check the functionality of our code.
Writing code in file: Lines of python code can be written together in a file, and saved with the extension of '.py' .
Executing Environment: Open a terminal window ( can be a Mac or Linux machine). Type python and press the 'enter' key.
Below is a sample output when python is typed on a mac terminal window.
$ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Data types: Number (int, float), string, list( like arrays in C, [1,2,3...] ), directories (like hashes, key-value pairs ), touples( (1,2,3..))
operators: +, -, *, /, %, **, ==, !=, , =, ...
Brain of Python, How to decide what to do: Decision Making
Most of the programs that we write need to make some decisions, that’s why I call it the brain part :) . Decisions are made by using statements like many other programming languages, some of which are:
- If statements
- If,else statements
- while loop
- for loop
All these statements, when used with correct logic in the code, help in making the right decision about the action to be taken.
Sample coding to get you started
- Open a terminal window. Create a directory where you would want to stash your precious code :) .
$ mkdir mypython
$ cd mypython
- Open a text editor, my favourite is vi. Its simple to use, and almost all Operating Systems have it. You would need to familiarise yourself with vi commands.
$ vi firststep.py
Eg 1. Compute and print
Write the following lines of code in the file firststep.py .
This code computes the result of 20*10 and prints it on the command line.
#!/usr/bin/python
i=20*10
print "value of i is: ",i
Save the file, give it executable permissions.
$ chmod +x firststep.py
Execute the code on command line
$ ./firststep.py
If all is well with the code with no errors, we are going to get the following output:
$ value of i is: 200
So you see, its as simple as this :) .
Eg 2. Taking input from user
#!/usr/bin/python
name=raw_input('what is your name?n')
print "hello ",name
When the above lines are saved in a .py file and run, the output is:
$ ./readuserinput.py
what is your name?
pooja
hello pooja
Eg 3. Using a system function to print date
Write the following code in an executable .py file
#!/usr/bin/python
import datetime
today = datetime.date.today()
print today
Datetime is a module, that provides date related functions. Python provides many modules for different functionalities.
Execute the above code, and the output will be
$ ./finddate.py
2017-01-11
Eg 4. Using 'if' to make a decision
'if' condition is used to make a correct decision. It is usually implemented in 'if, elif, else' format. Best understood with example :) .
Write the following code in validuser.py . It tests if the user is Anna or James. Otherwise, it prints Invalid user.
#!/usr/bin/python
girl="Anna"
boy="James"
user=raw_input('what is your name n')
if user==girl:
print "hello Anna"
elif user==boy:
print "hello James"
else:
print "Invalid user"
Run the code as in other examples above:
$./validuser.py
what is your name
Anna
hello Anna
$ ./validuser.py
what is your name
hobbes
Invalid user
Eg 5. 'for' loop
When we need to perform an action multiple times, we can use a 'for' loop.
Open findsum.py and write the following code in it:
#!/usr/bin/python
digits=[10,20,30,40,50]
result=0
for j in digits:
result=result+j
print result
print "sum is: ",result
As is evident from the code, the 'for' loop adds all the elements in the list 'digit' and prints the sum.
Eg 6. while loops
As with 'for' loop, while loops are also used to repeatedly execute some code. The loop is executed till the condition defined is 'true'.
Example :) .
#!/usr/bin/python
#here is the while loop
i=0
while i < 4:
print "value of i is ",i
i=i+1
print "finally out of while loop "
Run the code, and get the output:
$ ./mywhile.py
value of i is 0
value of i is 1
value of i is 2
value of i is 3
finally out of while loop
Eg 7. functions, defining code blocks
functions are like a block of code. They are used when you want to repeat some code in multiple places, or just to make the code more readable. Once you define the function, they can be called multiple times, maybe in multiple places.
As always, here is the example :) .
Write the following in myfunction.py
#!/usr/bin/python
#defining the function
def printmyname(str):
print "hello dear ",str
#calling the function
printmyname('pooja')
And, now run this code.
$ ./myfunction.py
And we get the following output
$ hello dear pooja
Eg 8. Dictionaries for storing data
In any programming language, we use variables, arrays etc to store values. These values are needed for computation by the software program. Dictionaries do the same in Python. But they are very cool :) .
Every value stored in dictionary dict has a reference associated with it. The reference can then be used later to access the actual value stored. Wow, so it has gone over your head :P .
Let's use an example.
Suppose you want to store information about yourself. Define a dict mySelf
mySelf= {'Name':'Pooja', 'Country':'India', 'Age':16}
You can then access the value of each entry as:
mySelf['Name'] will return Pooja.
mySelf['Country'] will return India.
And mySelf['Age'] will return 16.
Here is the code to print the above information:
#!/usr/bin/python
#define dict mySelf
mySelf= {'Name':'Pooja', 'Country':'India', 'Age':16}
#You can then access the value of each entry as:
print "my Name is: ",mySelf['Name']
print "I am from: ",mySelf['Country']
print "I am ",mySelf['Age'],"years old"
And the out is:
$ ./mydictionary.py
my Name is: Pooja
I am from: India
I am 16 years old
Pretty awesome right :) .
Eg 9. Sample Code to extract data from a website(data scrapping)
This is an interesting program. Here, our aim is to target a website, get all of its content( called the HTML data). We then extract the information that we need from it.
We use two libraries for this, 'urllib2', and BeautifulSoup (module that manipulates the HTML data, to help us get what we want ) .
#!/usr/bin/python
################################
#
# copyright Beingpoojatech
# code to get info from a website
#
####################################
import urllib2
poojazLink = "https://beingpoojatech.wordpress.com"
#get the content of the website
poojazPage = urllib2.urlopen(poojazLink)
from bs4 import BeautifulSoup
#Get the html in the 'poojazPage'
pageData = BeautifulSoup(poojazPage,"html.parser")
#print the '<title>' tag content of #the HTML data
print pageData.title
print"**********************"
#get all elements in tag 'a’, and then #get value of attribute 'href' i.e, the #urls
pageAllLinks=pageData.find_all("a")
for singleLink in pageAllLinks:
print singleLink.get("href")
On executing the above code, we’ll get the output :
<title>Pooja's Tech Central – understanding technology better</title>
**********************
#content
https://beingpoojatech.wordpress.com/
https://beingpoojatech.wordpress.com/
/
https://beingpoojatech.wordpress.com/about/
https://beingpoojatech.wordpress.com/contact/
https://beingpoojatech.wordpress.com/delhipicks/
https://beingpoojatech.wordpress.com/my-books/
#
Happy coding ☺️
Here is my blog on C programming , just incase you are vying to learn more technology.