Warning - This Website is only for education purposes, By reading these articles you agree that HackingBytes is not responsible in any way for any kind of damage caused by the information provided in these articles.

Tuesday, July 30, 2013

Learn Python The Easy Way


Hello guys, In this tutorial I'm going to go throught some basic concepts which are required to understand python programming like Loops, if statements, indentation etc etc. I'm going to explain each part one by one so be sure to read one part carefully then proceed to the next one.

Please do not copy paste codes! Type each code even if it's a one line code. Being lazy will make you Worthless

First of all we need to know what python is so lets go on that part

What do you need?
* In this tutorial I'll be using Python 3 so better install it from Here
* I'm using Linux so to install Python 3, opne the terminal and type sudo apt-get install python3-minimal
* An IDE or use the default Python IDE, I am using Sublime Text 2
* A Brain
* A soul which bears the property "Patience" Wink

1) What is Python?

Python is a VHL (Very High Level ), general purpose, Object Oriented Programming language. The modules of Python are developed in C and C++ so being influenced by those two languages (More than just two), python has a similar sytnax to them especially C. In python you can express your code in a few lines.

Here we take an example of Hello World program in C++ and Python:

Hello World In C++:
Thanks to @ Psycho_Coder
Code:
#include <iostream>

int main()
{
    cout<<"Hello World!"<<endl;
    return 0;
}

Hello World in Python
Code:
print ("Hello World")

Now you should be able to see the difference yourself.

Python is cross platform programming language meaning that it can run on nearly all OS, the most common one's are
Code:
Linux
Windows
MAC OSX

Of-course like other languages Python can be used and integrated to work with another language like C, Well this is only for reference as this topic is little above the beginners level so we'll now make our first Hello World Program.

2) Making Your First Hello World Program

Now in order to Print a statement, python uses a function called print(). When you call a Function, you need to provide it an Argument. An argument is simply a value that you give to the function upon calling it. So as we are going to CALL our Function to Print the Argument "Hello World".
When using print, your argument must be inside quotes like:

Code:
print("arg")

So type in your IDLE:
Code:
print("Hello World!")

Congrats! You just made your own python Hello World program
Remember that print is a function and the argument must be inside the parentheses!

More Printing:

Lets do some more printing before we go to the next topic. So type these code in the IDE:

Code:
print("Hello! What's up mate?")

print("123456, Can't you see those numbers?")

print('I want to learn Python!')

While typing these codes, examine each symbol, letter because in the next part you're gonna have to solve some problems

Now, as you are done with the above printing, you'll have to find out the solution to the errors in the statements below:

Code:
print('Why aren't you that active')

print("yeah, haters gonna hate")

print('Herb’s sister yelled, "Does anyone have a telephone?")

If you have corrected the mistakes then you have now understood how and when to use the quotes ' ' and " " while printing.

Printing Numbers:

You can print numbers with or without using the quotes like:

Code:
print(123456789) -> 123456789

and

Code:
print('123456789') -> 123456789

The first print statements' argument is an int and the second print statements' argument is a String . We'll learn more about Strings, Integers etc in the upcoming lesson.

Comments

Comments are crucial for a programming to keep track of codes, In python it's acheived by putting a Hash infront the statement that you want as a comment like:

Code:
#This is a comment

3) What Are Variables?

I'm going to explain Variables as easily as I can, Consider this diagram:

[Image: nY8Z77D.png]

Suppose the large box is your System Memory, as the data is stored in the system memory so the small boxes inside the large box are the Memory Locations which hold your data so now Variables are just reserved memory locations used to store data - Tutorials Point How simple is that?

Each memory locations is denoted by the address written above the box for example
Code:
name = 'LiveFaster'
name

When I call the name variable, it actually calls the memory address (x1241) in which the name 'LiveFaster' is stored, Easy Eh?

Here are some lines from a course I did:

A value has a memory address.
A variable stores a memory address.
A variable refers to a value.
A variable points to a value.


So the data is actually stored in the memory having a specific memory address and the variable point to the memory address when called

Code:
name -> memory address -> x1241 -> Stored Data -> LiveFaster

Till now you should and must have understood What Variables are, Lets study about the types of Variables.

Variable Types

Here I'm going to teach you only three of the data types which we use commonly, The rest you can find them HERE as they are not hard to understan:

1) Integers i.e 100, 1, 2, 50
2) Strings (Text enclosed in quotes like 'Ex094' are called strings)
3) Boolean (True and False)


There is nothing to explain about these 3 types for variables as you must be familiar with them. so I'll go to the declaration part but here's something for you to ponder on:

Consider two variables:
Code:
var_one = 94
var_two = '94'
var1 == var2
>>> False

Think yourself that why does this var1 == var2 statement gives False upon call, If you guessed it instantly then you know about the 3 type well.


Declaring Variables:'

For Strings:
We declare a variable with the equal sign like;
Code:
variable = 'Ex094'

For Integer:
To declare an Integer you do it with out the quotes like:
Code:
integer = 10

For Boolean:
Boolean Values are True and False so they are declared as same as Integers
Code:
boolean = True
boolean = False

Printing Variables

To print the data stored in a Variable, you can simply use the print function or return if it's inside a function like:

Code:
name = 'Ex094'
forum = 'hackcommunity'
print(name, forum)

The output will be:
Code:
Ex094 hackcommunity

4) Getting Input From User:

You must have come across certain program that can take an input like e.g A Name and then output. But how's it's done in Python?
For that we use the input() function, the question for the input is a string placed inside the parentheses like:

Code:
input("What's your Good Name Sir?")

Output will be a string

Store Input in a Variable:

This part is very easy if you've understood the declaration of variables, so similarly what we did previously

Code:
name = input('What is your name: ')
print(name)

Here's is a small function which takes and input and gives the output that's the name plus last name combined, run it in your IDE and observe what happens:
Code:
def full_name():
    first = input('Enter your First Name: ')
    last = input('Enter your Last Name: ')
    return first + last
full_name()

5) Conditionals

Consider a program which takes "yes" as an input but there might be a situation when the user has to enter "no", at that point the program will give you an error because it's designed to take Only Yes as an input and it doesn't recognize No because it's not a part of it's code or either t's not supported. For situations like this we make use of conditionals, a very common example on usage of conditionals is:

[Image: YzwxaGt.png]

Code:
Get user Input
    if input is yes
        go to the yes function
    if else input is no
        go to the no function
    else if it's nothing
        exit the program

Explanation:
If the input is yes then it'll execute the yes function, but if else the input is no then it'll execute the no function or else if the user enters non of the above then exit the program.

Indentation:

As a default, Python accepts an indentation(Space before statement) of 4 spaces. For example:

Code:
a = True
if a == True:
print('OK')

If you run this code, you'll get indentation error because the print statement is a part of if statement and it should be inside it so we give 4 spaces before it

Code:
a = True
if a == True:
    print('OK')

Running this code will result in successful implication as indentation has been applied

Types Of Conditionals:

After looking at the example given above, we can say there are three types of conditionals:

1) The if statement
2) The if...else statement
3) The else statement

Example of IF Statement:
Here is a small program that will print True if 2 multiply by 4 is 8
Code:
multi = 2 * 4
if multi == 8:
    print('True')

Example of if Else Statement:
This program will print False if the output is greater than 8
Code:
multi = 2 * 9
if multi == 8:
   print('True')
elif multi > 8:
   print('False')

Example of Else Statement:
If the output is other than both of the previous conditions, then it'll print false
Code:
multi = 2 * 1
if multi == 8:
    print('True')
elif multi > 8:
    print('False')
else:
    print('No')

6) Python Operators:

Here is a list of all the arithmetic operators in python:

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponent
// Floor Division

Examples:
1) 2 + 4 will give you 6
Code:
>>> 2 + 4
>>> 6

2) 4 - 2 will give you 2
Code:
>>> 4 - 2
>>> 2

3) 2 * 4 will give you 8
Code:
>>> 2 * 4
>>> 8

4) 4 / 2 gives 2
Code:
>>> 4/2
>>> 2

5) 2 % 4 gives you 2
Code:
>>> 2 % 4
>>> 2

6) 2 ** 4 gives you 16
Code:
>>> 2**4
>>> 16

7) 9 // 2 gives you 4
Code:
>>> 9//2
>>> 4

Other Operators can be found here => http://www.tutorialspoint.com/python/pyt...rators.htm

6) Loops

Loops are really important for a programmer, there comes a situation when a programmer wants to run a single code a number of times. For that we use loops. In python there are 2 types of loops:

1) The for Loop
2) The while Loop


To under stand loop here's a simple flow chart:

[Image: 87ezf2G.png]

The For Loop:

The syntax of a For Loop is as Follows:

Code:
for expression:
    statement

Example: In this example, we want to make a program that will output the numbers from 1 to 10, so we will be using a for loop:

Code:
for i in range(1, 11):
   print(i)

The Output will be:
Code:
1
2
3
4
5
6
7
8
9
10

What does the range function do??? Go here

The While Loop:

The syntax of while loop is same as that of for loop:

Code:
while expression:
    statement

Example: We shall do the same example as that of for instead we will use the while loop to generate numbers from 1 to 10.

Code:
i = 0
while i < 10:
   i += 1
   print(i)

The Output will be:
Code:
1
2
3
4
5
6
7
8
9
10

Explanation: As indicated in the code, our condition is that we need numbers that are less than 10, First we declare the variable i = 0 which will be used to store the value we get from each iteration. First as the loop starts, i get the value 1, as 1 is less than 10 so it gets stored in the variable i, the next line of code adds 1 to i making it 2, it's also less than 10 so it gets stored and the next line adds 1 to it making it 3 and so on till reaches 10. Once it reaches 10 the loop breaks as provided by the expression.

7) Understanding List and String Indexing:


Lists In Python
A list in Python is just like an array in PHP, infact list is an Array. Using a list you can store much data and also you can do alot of stuff with it which are useful. the syntax of a list is:

Code:
my_list = []

Lets consider a list 'names' where we will store a list of names Grin

Code:
names = []

Now I want to append a name in that list, We can't just do this:

Code:
names = 'Ex094'

Remember, = is an assignment statement.
To introduce a string or integer in the list we use the .append method which come with the list.
So it's like:

Code:
names.append('Ex094')

Now type the name of your list in the Python IDLE and you'll see:

Code:
['Ex094']

Task: Add 3 more names to the list and see the result

List Indexing:

Consider this list of names:

Code:
names = ['Deque', 'Bluedog.tar.gz', 'ArkPhase']

Now I'm given a question that which of the following are the owners of Hackcommunity, we know it's Bluedog.tar.gz but how do we get an output like that? If we type the name of the list, we'll get the whole list. We need only one name, thats where Indexing comes in:

The names are in the list are in the following index order (Starting From 0 MOST IMPORTANT POINT!!!)
Item Index Number Item
0 Deque
1 Bluedog.tar.gz
2 ArkPhase

Now as we know the index number, we can select which name we want to output. In our case we want Bluedog.tar.gz which is the 1 index So we will type:

Code:
names[1]

The output is:

Code:
'Bluedog.tar.gz'

If we want to list all the items of a specific List then we use a for loop like:

Code:
names = ['Deque', 'Bluedog.tar.gz', 'ArkPhase']

for name in names:
    print(name)


The output is:

Code:
Deque
Bluedog.tar.gz
ArkPhase

Explanation: The loop iterates through the list, staff is a variable, the first value in the list is Deque so it's stored in the Variable and then displayed, then it iterates to the next value and Bluedog.tar.gz gets saved in the Variable and printed as output same goes for ArkhPhase

If you want to get name of the last two members then you can do:

Code:
names = ['Deque', 'Bluedog.tar.gz', 'ArkPhase']
names[1:]

This will give you the output:
Code:
['Bluedog.tar.gz', 'ArkPhase']

Task: Using the list given below, make a program such that it outputs 'Hackcommunity For Life'

Code:
list = ['Hack', 'Life', 'Community', 'for']

After completing this task, You know now about list, how to apply a loop and index the items in it.

String Indexing/Slicing:

Indexing the string is totally the same principle based on list, it's just we are working with strings now. So lets consider this example string:

Code:
exp = 'Hackcommunity'

What I want is that to slice that string and I want to make it print only Hack, So lets apply indexing:
Remember that it starts from 0 to onwards

Code:
exp[:4]

This will exactly give us the output:
Code:
'Hack'

If we want to do it for community then:
Code:
exp[4:]

8) Functions

Functions are well organized, reusable piece of code which are used to make the work of a programmer easier. There are many inbuilt functions the most common one is print(). You can also make your own functions, they are called user-defined functions.

The default syntax to define a functions is:

Code:
def name ( paramaters ):
   conditions
    statements

To run this function you simply do:
Code:
name_of_function()

An example function is:

Code:
def add(x, y):
   return x + y

Explanation: X and Y are the parameters, the function takes the 2 values and returns the sum of the two values

So the sum of 2 + 4 will be:
Code:
add(2, 4)

The output will be:
Code:
>>> 6

Making A Proper Function

In the topic above, we learned what a Function is and how to use it, Also in the previous topics you might have come across some functions. Now is time to make a proper one, I'm going to teach you how to make a proper function via Function Recipe. It's what I learned from my Python Course and it really helps you make a proper function.

Function Recipe:

1) Doc String
2) Type
3) Description
4) Examples

These are the four you need to make a good function.
Lets make a function which calculates the average of the given values in a list:

So, first we are going to make the DOC String, remember that strings are enclosed in ' ' or " " quotes, well we also use triple quotes """ if you have long text to write. For example:

Code:
""" Hey It's me Ex094 """

You can also do this:

Code:
""" Hey
it's me Ex094! """

Now for the function, so lets define our function, We'll name it average:

Code:
def average(values):

Well a Doc string is usually used to define a Function, when you type help(your_function) it actually displays the Doc String.

Now we shall make the doc string:

Code:
def average(list):
    """ Description Here
         Type
         Examples """

Lets fill up the description first! Our function outputs the average of all the values provided by the user so,

Code:
def average(list):
    """ Returns the average of the given values
         Type
         Examples """

Now for the type, As the output type would be different as compared to the input i.e Input is a list while output is a integer, we will write:

Code:
def average(list):
    """ Returns the average of the given values
         list -> int
         Examples """

Code:
list -> int

It means that this function takes a list of integer as input and the output is the average of the values in the list which is a type integer.

Lets write some case examples of our function, examples give an idea to the user about what it takes as an input and what it gives as a result.

For our Average function, we will write three examples with:

1) 4 Values
2) 2 Values
3) Invalid Input (Not an integer)


Code:
def average(list):
    """ Returns the average of the given values

         list -> int

         >>> average([2, 4, 6, 8])
         >>> 5

         >>> average([2, 4])
         >>> 3

         >>> average([a, b])
         >>> Error
        """

When

Now add your complete Code:

Code:
def average(list):
    """ Returns the average of the given values

         list -> int
       
        >>> average([2,4,6,8])
        >>> 5

        >>> average([2,4])
        >>> 3

        """
    val = 0

    for i in range(len(list)):

        val = val + list[i]

    return int(val / len(list))

If you import this function and run help(average) in your python console, you'll get:

[Image: 5SbbYuk.png]

In this section you have now learned how to craft a good function using function recipe

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...