Friday, March 30, 2012

Multiple Parameters


Hello Everyone, in this post, we will check how to add multiple parameters to a functions, we need to this trick many a time while programming a script..

Okay lets get started.

First lets make a function

>>> def python(name):
           print name


>>> python('PythonGame')
PythonGame
>>> python('Python', 'Game')

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    python('Python', 'Game')
TypeError: python() takes exactly 1 argument (2 given)
>>>

Well what happened is, we made a function take takes only one argument, and if we pass, more than one argument, it gives an error, as it cannot handle more than one.

Now, lets see how can we make it work, i.e to accept multiple arguments..

>>> def python(*name):
           print name

>>> python('Python', 'Game', 'Snake')
('Python', 'Game', 'Snake')
>>>

It it took three arguments and worked absolutely fine, and returned a Tuple. So this is the trick, we need to add a * symbol while defining the argument of the function.

Now, to clear the confusion, if you have any, lets check one more example

Lets say, we have been given a task, where the output should display software/application name along with platform supported.

>>> def soft(name, *support):
          print name
          print support

>>> soft('Python', 'Windows, Linux, MAC')
Python
('Windows, Linux, MAC',)
>>> soft('Python', 'Windows', 'Linux', 'MAC')
Python
('Windows', 'Linux', 'MAC')
>>>

Well I guess this should be clear with you, and these posts are very important, please try to understand them well.

Thank You and Don't forget to check my next post.

Wednesday, March 28, 2012

How to add Default Parameters


Hello Everyone, In This post we will see how to add default parameters to functions that we define in a Python Script. You might have noticed I have started using the word script, instead of Python Program, Yes, technically Python Programs are known as Scripts, which are heavily used in Desktop Applications and Web Development Applications. As a matter of fact, Web Browser Opera is made in Python, so as the application Google Earth, there are many more examples, we are yet very far from those topics.

Lets get back to the topic.

Suppose we write a script and define some functions, and the script is used by system administrators or network administrators for some automated tasks, like bulk copying or deleting or sharing, etc, etc. So what if the user dsnt inputs anything for the parameters of the functions defined? The script will choke and We don't want that isn't it?

So here is what we do, we add some default values to the functions:



>>> def name(first,last):
              print '%s  %s' % (first,last)

>>> f = 'Python'
>>> l = 'Script'
>>> name(f,l)
Python Script
>>> name()

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    name()
TypeError: name() takes exactly 2 arguments (0 given)
>>>

So we see here, if there is no arguments passed for the function, it choked

What we can do is, just modify and add a default value to the arguments of the functions:

>>> def name (f_name='Fatal', l_name='Error'):
              print "%s %s" % (f_name, l_name)

   
>>> name()
Fatal Error
>>>  name('Hello', 'World')
Hello World
>>> name(f,l)
Python Script
>>>


So we see here that, when no arguments is passed, it returns or displays the default value.

And when argument is passed, it displays the arguments that has been passed.


So I hope This Has been Informative To you, Practice it, And Don't forget to check the next Post.

Thank You.

Tuesday, March 27, 2012

How To Build Own Functions


Hello everyone, in this post we will see how to make our own functions, till now we have used functions that were built-in to Python. But many a times while writing a script we need to repeat certain things over and over again, wish there was something that would make life easy...Yes this is where building own functions comes handy.


How do you create own functions?

Its simple, we just need the key word def and the syntax is:

def function_name(arguments):
    statements

Note: User-Defined Functions are valid only for one script. Function created for one script is not valid for other script.

Now lets check out some created functions

>>> def var_a(x):
            return "Whats Your Social Security Number, "+x+"?"

>>> print var_a("Python")
Whats Your Social Security Number Python?

So whenever we call the defined function "var_a" with an argument, it returns the result after executing the codes under functions.

Okay, so by now I am guessing why no one asked how to clear the shell while working with the Python Shell. When I was learning python, I wanted to know how to clear the window of the Python Shell. In Windows Command Shell, when we type "cls" it clears the Window, In Linux Shell when we type "clear" it clears the window, but unfortunately, Python doesn't have such command, but programmers are genius, there is a trick which can clear up the window for you, and guess what its by the user-defined function, lets check it out how.

>>> def clearpy():
             return "\n"*50

>>> print clearpy()

So when we call the defined function clearpy(), as expected it will print 50 new blank lines, thus making the Shell looking decent and clean.

Okay, So I Hope This was Informative For you, practice this and make sure you will not be surprised when I use the def functions in future posts.

Thank You!

Monday, March 26, 2012

Looping Statement: For Loop with Dictionary and While

Hello everyone in this post, we will discuss how to loop through a Dictionary.

I guess we are clear about what dictionary is, if not please look at the blog archive and go through the Dictionary Post.

Lets make a Quick dictionary

>>> things = {'Socks':50, 'Shirt':550, 'Trouser':995, 'Shoes':780 }
>>> things
{'Trouser': 995, 'Shirt': 550, 'Socks': 50, 'Shoes': 780}

Now lets say we want the Dictionary to display the keys with its respective key_values

This is where the For Loop comes handy

The For Loop loops a variable with every elements in a list or dictionary.

>>> for purchase in things:
             print "Price of "+purchase+" is Rs.",things[purchase]


Price of Trouser is Rs. 995
Price of Shirt is Rs. 550
Price of Socks is Rs. 50
Price of Shoes is Rs. 780
>>>

Here purchase is a variable that is looped with the dictionary. On executing, the variable purchase is assigned the key Socks, and things[purchase] which at the first loop is, things[Trouser] returns the key_value 995. and on the second loop, things[purchase] means, things[Shirt] and it returns its key value 550, and it goes on, until all the keys in the dictionary has been looped.


Now, here is another Loop with While, which will be very helpful in future, lets first check the code, then will explain:

>>> password = "welcome"
>>> while True:
              pass1 = raw_input("Enter the Password: ")
              if pass1 == password:
                    print "Password Accepted"
                    break

Enter the Password: garry
Enter the Password: tom
Enter the Password: letmein
Enter the Password: welcome
Password Accepted
>>>

Explanation: while True:(Alternate while 1:) means asking the python to keep looping the statements under the while, until the loop is broken by some event.

So we assigned the password "welcome" to variable password, then we asked the python to keep looping the statement under while. Next, allows user to type a password and the user input is assigned to variable pass1, then the value of pass1 is matched with the value of password, and according to the condition, if values of both the variable match, then print "Password Accepted", and break is the keyword, which breaks the whole Loop and exits out of the loop.

Okay, So I Hope this has been informative, Practice them, as it will be used many times with the future posts.

Thank You and Don't forget to check my next post.

Sunday, March 25, 2012

Looping Statement: For Loop

Hello everyone, in this post we will discuss another Looping statement, which is the For Loop.

What is For Loop?

From the last post we know what are Looping statement, For loop statement is similar to while. While constructing a For Loop, you just need to remember this line. "FOR something IN something, keep doing something"

Lets check it out:

First lets make a List,

>>> behavior = ['good', 'not bad', 'crazy', 'not selfish', 'innocent', 'kind to all']
>>> for python in behavior:
             print "I am "+python

I am good
I am not bad
I am crazy
I am not selfish
I am innocent
I am kind to all
>>>

What happened exactly?

In the for statement, it says  for python in behavior, here python is a variable that is to be looped with list behavior.

If have done some other other programming language, you will notice that the python for loop statement is little different, but this is how it works, cant help it.

In Python the variable is looped with every element of a List from Left to Right.

Its little confusing, I know, but don't give up on it, practice it, make your own programs with the For Loop and you will get out of confusion.

However the later posts will make the things more clear.

Thank You and Don't forget to check the next post.

Saturday, March 24, 2012

Looping Statement: While Loop

Hello everyone, in this post we will Discuss about Loops.

What is a Loop?

Anything which keeps on repeating, based on a certain condition, is known as Loop.

In Python, Like other Programming Language, we have several looping statements, We will start with the While Loop


>>> x = 1
>>> while x <= 10:
           print "I Am ",x
           x = x + 1

I Am  1
I Am  2
I Am  3
I Am  4
I Am  5
I Am  6
I Am  7
I Am  8
I Am  9
I Am  10
>>>

Explanation: We have initiated the variable x, so the value of x is 1, next statement, while x <= 10: means keep doing the statements you have under while until x becomes less than or equal to 10. But as of now the x is 1, so it needs to execute the statements under the while statement, the print statement is pretty clear, which says print "I Am", x means print I Am x (x = present value of x), so it prints out I Am 1, next statement it find x = x + 1, means add one to the present value of x, so x becomes 2, x + 1(1 + 1) = 2, it returns to the while statement, checks the condition, present value of x is 2, since x is less than 10, it will again execute the statements under the while, in this way when the value of x becomes 11, and it returns to the while statement and the condition becomes false, it skips the statements under the while statements.


Lets Make a small Program

# Program to display the multiplication table of any given number upto 10.
num = input("Hey You! Give Me A Number \nAnd I Will Display The Multiplication Table Upto 10, Faster Than You Can Write: ")
count = 1
while count<=10:
    print num, " * ", count, " = ",  num*count
    count +=1
raw_input("Press Enter To Exit")

Output:

>>>
Hey You! Give Me A Number
And I Will Display The Multiplication Table Upto 10, Faster Than You Can Write: 8
8  *  1  =  8
8  *  2  =  16
8  *  3  =  24
8  *  4  =  32
8  *  5  =  40
8  *  6  =  48
8  *  7  =  56
8  *  8  =  64
8  *  9  =  72
8  *  10  =  80
Press Enter To Exit

Okay Interesting, isn't it?

I hope this is Informative For You, Practice it, And Here is a Task For You:

Question:

Write a Program which would display the Multiplication Table Of Any Given Number, Upto Any Given Point.

Example:
Give me a number to multiply: 9
How Far Should I Show you The Table: 20

and then it should display the multiplication table upto 20.

Good Luck!

Friday, March 23, 2012

Comparison Operator II


Hi, In this post I will show you some more ways of comparing.


1. '<' --> comes before?

>>> 'd' < 'a'
False
>>> 'a' < 'd'
True
>>> 'a' < 'D'
False
>>> 'a' < 1
False
>>> 'A' < 1
False
>>> 1 < 'a'
True
>>> 1 < 'A'
True
>>> 1<5
True
>>>

When we use '<' for int type data, it uses the regular maths comparison, but when we use with characters, the sequence is

[Numbers < Uppercase Letters < Lowercase Letters]

>>> 'a' < 'A'
False
>>> 'A' < 'a'
True
>>>

[The opposite is for '>' which means 'comes after', I leave this for you to check on your own]


2. 'and' --> executes the body of the conditional statement, if the all the conditions in a statement are True.

>>> python = 'program'
>>> var1 = 'good'
>>> if python=='program' and var1=='good':
    print "You are Good"

You are Good
>>> if python=='program' and var1=='bad':
    print "You are Good"

   
>>>

Okay so see here since one of the condition was not true hence it dint execute the print statement.


3. 'or' --> executes the body of the conditional statement, if one of the condition or all the condition in a statement is True.

>>> python = 'program'
>>> var1 = 'good'
>>> if python=='program' or var1=='bad':
    print "You are Good"

You are Good
>>> if python=='program' or var1=='good':
    print "You are Good"

   
You are Good
>>>

Here in both case the print statement was executed because one or both the condition was true.

Now lets make a small program.

#program to check the usage of and/or operators
ch = raw_input("Enter Name: ")
age = input("Enter You age: ")
code = raw_input("Enter the VIP Code, If you have(Type No, if you dont have): ")
code1 = code.lower()
if age > 20 and age < 35:
    print "You are allowed to enter in the bar"
elif code1=='vip' or code1=='premiummember':
    print "You are allowed to enter in the bar"
else:
    print "You are not allowed"
raw_input("Press Enter to Exit")


Output:

>>>
Enter Name: Whiskey
Enter You age: 25
Enter the VIP Code, If you have(Type No, if you dont have): No
You are allowed to enter in the bar
Press Enter to Exit
>>>
>>>
Enter Name: Whiskey
Enter You age: 40
Enter the VIP Code, If you have(Type No, if you dont have): VIP
You are allowed to enter in the bar
Press Enter to Exit
>>>
Enter Name: Whiskey
Enter You age: 17
Enter the VIP Code, If you have(Type No, if you dont have): PremiumMember
You are allowed to enter in the bar
Press Enter to Exit
>>>
>>>
Enter Name: Whiskey
Enter You age: 17
Enter the VIP Code, If you have(Type No, if you dont have): no
You are not allowed
Press Enter to Exit
>>>

Okay I hope This example Makes It Clear about the usage of 'and' and 'or'

Hope you liked the post and was informative. Practice this, make your own program, and Dont forget to check my next post.

Thank You.

Thursday, March 22, 2012

Comparison Operator


Hi, in this post we will discuss the comparison operator which is used in conditional statements for testing condition.

1. '>'  ---> Checks if something is greater than something

>>> 4 > 5
False
>>> 6>4
True
>>>

2. '<' --> Checks if something is Lower than something

>>> 4 < 9
True
>>> 9 < 4
False
>>>

3. '>=' --> Checks if something is greater than or equal to something.

>>> 6>=6
True
>>> 6>=7
False
>>>

4. '<=' --> Checks if something is lower than or equal to something

>>> 4 <= 4
True
>>> 4 <= 2
False
>>>

5. '==' --> Checks if something is equal to something.

>>> 28 == 28
True
>>> 28 == 45
False
>>>

6. '!=' --> Checks if something is not equal to something.

>>> 28 != 45
True
>>> 28 != 28
False
>>>

7. 'is' --> Checks if a list is exactly equal to another list.

>>> ex1 = [1,2,3]
>>> ex2 = [1,2,3]
>>> ex1 == ex2
True
>>> ex1 is ex2
False
>>>

Its because the only the elements are same, and they are not exactly duplicate.

>>> ex3 = ex4 = [10,20,30]
>>> ex3 == ex4
True
>>> ex3 is ex4
True
>>>

8. 'in' --> Checks if something is in something.

>>> p = 'python'
>>> 'l' in p
False
>>> 'h' in p
True
>>>

Okay, So these are the basic simple things which would be required every now and then in our next posts. Practice them and Make sure that you know when to use what operator. And Dont Forget to Check The next Post.

Thank You!

Wednesday, March 21, 2012

Nested If Statement

In this Post, we will discuss about the Nested If Statement.

From the earlier post, we know that in an If-Else Statement, the statements inside the If body, executes only if the condition is true, otherwise it jumps to the Else statement or the Elif Statement.

Now Think Like This, what if we want the python to test a condition, and if the condition is True, we want Him to test another condition, and again if that's true, we want to test another...and it goes on. This is where we use Nested If Statements. In Other words, If Statements inside If Statements.

Lets check it out with a script, open up the Python Shell, and then the IDE by pressing Ctrl+n

Now lets type a small script to check this out.

foo1 = "python"
foo2 = "program"
if foo1 == "python":
    if foo2 == "program":
        print "Python is a Program"
    else:
        print "Maybe a Snake then"
else:
    print "I have no idea what it is then"

Save it as anything.py and execute the script, and it displays:

>>>
Python is a Program
>>>

Explanation:

Python knows that the value of foo1 is "python" and foo2 is "program", now when it comes to the if statement it checks the condition, and the condition is true, so python has to execute the the body of the if(Statements inside the If statement), but here again a testing condition, when tested the condition, the result is true, hence it has to execute the body of the If statement(The If Statement for which the condition was checked), since condition is true it prints out "Python is a Program"

Now lets change the script, and make the value of foo1 = "chocolate", and after executing, the display will be:

>>>
I have no idea what it is then
>>>

Now if we make the value of foo1 as "snake" and foo2 = "chocolate", the output will be:

>>>
Maybe a Snake then
>>>

[I Leave It To You, as why the output varied, Try to understand, but if you face any problem, leave a comment]

Now lets make a useful script:

# Program to check the usage of nested-if statement
nam = raw_input("Enter Your Name:  ")
marks = input("Enter Your Percentage:  ")
if marks < 100:
    print "\nHere is the comment for your percentage"
    if marks < 80:
       
        if marks < 60:
           
            if marks < 40:
               
                if marks < 30:
                    print "\nPoor! You Failed. "
            else:
                print "\nBad"
        else:
            print "\nGood"
    else:
        print "\nExcellent!!"
else:
    print "\nIdiot, Go and Do some Maths, percentage cannot be more than 100"
raw_input("\nPress Enter To Exit")

Outputs:

>>> ============= RESTART ================
>>>
Enter Your Name:  Whiskey
Enter Your Percentage:  200

Idiot, Go and Do some Maths, percentage cannot be more than 100

Press Enter To Exit
>>> ============= RESTART ================
>>>
Enter Your Name:  Whiskey
Enter Your Percentage:  25

Here is the comment for your percentage

Poor! You Failed.

Press Enter To Exit
>>> ============= RESTART ================
>>>
Enter Your Name:  Whiskey
Enter Your Percentage:  80

Here is the comment for your percentage

Excellent!!

Press Enter To Exit
>>>

Note:  We can see \n in the print statements...what is it?? \n means we are asking the Python to go to a new line.


Okay... I hope This should be clear with you, practice it, make your own programs, and Don't Forget to Check My next Post.

Thank You!

Tuesday, March 20, 2012

Dictionary

In this post we will discuss, one more method known as Dictionary.

* What is a Dictionary?

Well, it is pretty much like Lists and Tuples as we discussed earlier, but the structure of Dictionary makes itself different from other. Its a collection or group of any data type value. Dictionary has a 'key' and a 'key-value'

* How to Identify a Dictionary?

By its structure ie by its syntax, and of course we have the built-in keyword type() to reveal what it is. Elements of Dictionary are enclosed within curly brackets.

Syntax: variable_name = {key1:value1, key2:value2, . . . . . keyn:valuen}

Lets Open up the Python Shell and check with an example.

>>> subject = {1:'Science', 2:'Maths', 3:'Computer', 4:'Literature'}
>>> subject
{1: 'Science', 2: 'Maths', 3: 'Computer', 4: 'Literature'}
>>> type(subject)
<type 'dict'>
>>>
>>> #  To call any key_value we need to call by its key, Syntax: dictionary_name[key]
>>> subject[1]
'Science'
>>> subject[4]
'Literature'
>>> len(subject)
4
>>> subject.pop(2)
'Maths'
>>> # pop removes the value of the key_value given and displays what has been removed
>>> subject
{1: 'Science', 3: 'Computer', 4: 'Literature'}
>>> ages={'bob': 20, 'nancy': 18, 'sam': 24}
>>> # We have created another Dictionary named ages for the next examples here
>>> subject=ages.copy()
>>> # Copies elements from one dictionary and pastes it to another dictionary
>>> subject
{'bob': 20, 'sam': 24, 'nancy': 18}
>>> ages.clear()
>>> # clears all the elements from a dictionary.
>>> ages
{}
>>> subject.items()
[('bob', 20), ('sam', 24), ('nancy', 18)]
>>>  # Displays list of Subjects (key, value) pairs, as tuples
>>> subject.keys()
['bob', 'sam', 'nancy']
>>> subject.values()
[20, 24, 18]
>>> subject[5]='Python'
>>> # As of now just know that this adds an element to the dictionary
>>> subject
{'bob': 20, 'sam': 24, 'nancy': 18, 5: 'Python'}
>>>>>> subject.has_key(0)
False
>>> subject.has_key(5)
True
>>> # dictionary_name.has_key(key_value) returns true or false; True if the key value is present, and False if its not present


These are the basic things that you are supposed to know as of now, we will see more usage of Lists, Tuples and Dictionaries gradually in our Future Posts.

So, I Hope This was Informative for you, Practice it, and Don't Forget to check on my next post.

Thank You.

Monday, March 19, 2012

Quick Review to Lists and Tuples.

Lists and Tuples

This Post is a Quick Review to Lists and Tuples, as some readers had confusion differentiating Lists and Tuples. And as it is an important part of Python, so please make the Things clear by practicing it and understanding it as well.

* What is a List?

List is a group of elements and can store elements of any data type. With List we can do Slicing, Appending and many more as discussed earlier.

* How to identify if a given method is List or not?

First, In List, elements are placed within square brackets, and next we have the Python in-built function type(argument) to reveal the type of element the argument holds.

An Example of List with different functions:

>>> a = ['mon', 'tue', 'wed', 12, 12.23]
>>> a
['mon', 'tue', 'wed', 12, 12.23]
>>> type(a)
<type 'list'>
>>> # type() should be something new for you here, basically it returns you the data type
>>> type(a[1])
<type 'str'>
>>> type(a[3])
<type 'int'>
>>> type(a[4])
<type 'float'>
>>> a.append('thurs')
>>> a
['mon', 'tue', 'wed', 12, 12.23, 'thurs']
>>> a.pop(4)
12.23
>>> a
['mon', 'tue', 'wed', 12, 'thurs']
>>> a.remove('wed')
>>> a
['mon', 'tue', 12, 'thurs']
>>> a.append('thurs')
>>> a.append('thurs')
>>> a
['mon', 'tue', 12, 'thurs', 'thurs', 'thurs']
>>> a.count('thurs')
3
>>> len(a)
6
>>> a
['mon', 'tue', 12, 'thurs', 'thurs', 'thurs']
>>> a.insert(2, 'wed')
>>> a
['mon', 'tue', 'wed', 12, 'thurs', 'thurs', 'thurs']
>>> a.reverse()
>>> a
['thurs', 'thurs', 'thurs', 12, 'wed', 'tue', 'mon']
>>> a.sort()
>>> a
[12, 'mon', 'thurs', 'thurs', 'thurs', 'tue', 'wed']
>>> a.extend('sun')
>>> a
[12, 'mon', 'thurs', 'thurs', 'thurs', 'tue', 'wed', 's', 'u', 'n']
>>> a.index('s')
7
>>> a[1:6]
['mon', 'thurs', 'thurs', 'thurs', 'tue']
>>> a
[12, 'mon', 'thurs', 'thurs', 'thurs', 'tue', 'wed']


Okay Played Enough with Lists, now lets Play with Tuples.

* What is a Tuple?

A Tuple is a collection of objects which can hold elements of different Data Type.

* How is it different from List?

Well, Tuple is very Robust, we cannot play with different functions as we did with Lists. The only basic thing that we can do with a Tuple is check the number of times an element exists in a Tuple and check the index number of an element. And Things Like The Length of The Tuple and Slicing

*How to identify if a given method is Tuple or not?

First, In Tuple, elements are placed within round brackets, and next we have the Python in-built function type(argument) to reveal the type of element the argument holds.

Example of Tuple with different functions:

>>> tup = ('mon', 'tue', 'wed', 12, 12.23, 'thurs', 'thurs', 'thurs')
>>> tup
('mon', 'tue', 'wed', 12, 12.23, 'thurs', 'thurs', 'thurs')
>>> type(tup)
<type 'tuple'>
>>>
>>> tup.count('thurs')
3
>>> tup.index('wed')
2
>>> len(tup)
8
>>> tup[1:4]
('tue', 'wed', 12)
>>> tup
('mon', 'tue', 'wed', 12, 12.23, 'thurs', 'thurs', 'thurs')
>>>

Try Playing with the Other Functions and check what Python says. :)

Well that was a Quick Review of Lists and Tuples, there is one more known as Dictionary, which will be discussed on the next post.

I hope This makes all the confusion clear between Lists and Tuples.

Thank You!

Sunday, March 18, 2012

Conditional:Elif Statement

Hi In this post I will discuss about another Conditional Statement that is the Else If Statement.

In the last post, we have seen how the If-Else statement works, as A Quick Review, A certain block of codes under the If Statement is executed when the condition is true, and if the condition was false, it executed the block of codes under the Else Statement.

Here in this case, using the else-if statement, Python gets a list of choice to check for a condition, and if all the conditions in the choices are false, the codes under the else statement is executed.

Syntax:

if condition:
    #Executes this if the condition is true
elif condition:
    #Executes this if this condition is true and the above condition was false.
elif condition:
     #Executes this if this condition is true and the above condition was false.
else:
    #Executes this if all the condition above are false

Note: We can add as many elif statement as we want.

Lets check it out with a simple program, open up the Python Text Editor, and type:

p='food'
if p=='snake':
    print "Its a Snake"
elif p=='program':
    print "Its a Program"
else:
    print "I Dont know what it is"

Save it as 'anything.py' and then execute the program.

Output:

>>>
I Dont know what it is
>>>

Now if we change the value of 'p' to 'program':

p='program'
if p=='snake':
    print "Its a Snake"
elif p=='program':
    print "Its a Program"
else:
    print "I Dont know what it is"

The output we will get is:

>>>
Its a Program
>>>

Elif is pretty much self explanatory, there should not be any problem understanding it, if you have understood the earlier posts for If and If-Else.

Lets now make a Program, and check it out:

#Program to check the use of elif statement
ch=input("Enter 1 for add, 2 for Subtract, 3 for multiply: ")
if ch==1:
    a = input("Enter the First Number: ")
    b = input("Enter the Second Number: ")
    c = a+b
    print "The Answer is: ",c
elif ch==2:
    a = input("Enter the First Number: ")
    b = input("Enter the Second Number: ")
    c = a-b
    print "The Answer is: ",c
elif ch==3:
    a = input("Enter the First Number: ")
    b = input("Enter the Second Number: ")
    c = a*b
    print "The Answer is: ",c
else:
    print "Invalid Option"
raw_input("Press Enter To Exit")


Outputs:

>>> ================= RESTART ==================
>>>
Enter 1 for add, 2 for Subtract, 3 for multiply: 2
Enter the First Number: 20
Enter the Second Number: 10
The Answer is:  10
Press Enter To Exit
>>> ================= RESTART ==================
>>>
>>>
Enter 1 for add, 2 for Subtract, 3 for multiply: 1
Enter the First Number: 20
Enter the Second Number: 40
The Answer is:  60
Press Enter To Exit
>>> ================= RESTART ==================
>>>
Enter 1 for add, 2 for Subtract, 3 for multiply: 3
Enter the First Number: 50
Enter the Second Number: 5
The Answer is:  250
Press Enter To Exit
>>> ================= RESTART ==================
>>>
Enter 1 for add, 2 for Subtract, 3 for multiply: 4
Invalid Option
Press Enter To Exit
>>>

I Hope This wasn't difficult to understand, practice this, make own programs, to be a programmer, you have to be creative and make own programs.

Don't forget to check my next post.

Thank You.

Saturday, March 17, 2012

Conditional:If Else Statement

The If - Else Statement

In this post we will learn another conditional statement, The If-Else Statement

From the Last Post, we learnt that, when we use the If statement, certain block of code will execute only if the condition is true, and would do nothing if the condition is false, simply the piece of codes under If statement is skipped if the condition was false.

Here, in If-Else Statement, It almost same, its just that when the condition is True, the block of codes under the If statement is executed, and if the condition is False the block of code under the Else Statement will be executed.

Syntax:

if condition:
    #codes here will be executed if the condition is true
else:
    #codes here will be executed if the condition in the if statement is false.

So lets check it out with a simple program, open up the Python text editor, and type:

p='program'
if p=='snake':
    print "Hey its a Snake!"
else:
    print "Hey its a Programming Language"
print "You have reached the last line of the program"
raw_input("Press Enter to Exit")

Save it as "anything.py" and then execute the program.

This is the Output For me:

>>>
Hey its a Programming Language
You have reached the last line of the program
Press Enter to Exit
>>>

So what happened exactly, when the program was executed,

1. From the first line Python understood that 'p' is a variable, and a String type Value 'program' is assigned to it.
2. It encounters the if statement, where it has to check if 'p' has the value 'snake', which is false, because value of 'p' is 'program', so the codes under the If statement is skipped.
3. Next it comes to the else statement, and python knows that he has to execute the block of codes under the else statement, as the if condition was false.
4. After executing the block of codes under the else statement, next it encounters the normal print statement and prints it.
5. The Last Line, If you don't know what it is, probably, u have not went through the earlier posts.

So when working with an If-Else just remember this algorithm.

A block of code is executed if the condition in the If Statement is true, and if its false, the block of code under the else statement is executed.


Now lets make a Program to Make it More Clear.

#Program to show the usage of if-else statement
pwd='password'
print "Welcome To Computer Korner"
raw_input("Enter Username Name: ")
test=raw_input("Enter Password: ")
if test==pwd:
    print "Password Accepted"
else:
    print "WARNING: Wrong Password"
raw_input("Press Enter")

Output:

>>>
Welcome To Computer Korner
Enter Username Name: Whiskey
Enter Password: abc123
WARNING: Wrong Password
Press Enter
>>> ================= RESTART ==================
>>>
Welcome To Computer Korner
Enter Username Name: Whiskey
Enter Password: password
Password Accepted
Press Enter
>>>


Okay So I Hope This Was Informative, practice it, Make your own programs and Don't Forget to check my next Post.


Thank You.

Friday, March 16, 2012

Conditional-If Statement

The If- Statement

In This Post I will show how Python tests a condition. From this post onwards I guess things would be more interesting.

Whenever we test something in program, we test it with a Conditional Statement

There are many Conditional Statements, our first basic conditional Statement will be the "If" Statement.

The If statement would check for a certain condition, and if the condition is true, it will execute certain piece of code.

Syntax:

if condition:
    #the codes in this block will execute if the condition is true

Notice something here, after the If statement, the next line has some space, this is known as Indention, indention makes python understand that it needs to execute the codes in the block, if the condition is true, if we don't have an indention, python will give an error.

Lets check with a basic program

Open up the IDLE, and then Open the Pythons Text Editor and type

python="programming"
if python=="programming":
    # "==" means a conditional operator, which tests, whereas "=" is an assignment operator, which assigns values to a variable
    print "Python is a programming Language"
print "Program executed successfully"
#The last print statement is not a part of If statement as its not indented

Note: You can skip the statements which starts with "#", statement starting with # is a comment line, and python does not care about it.

Now save program as anything.py, i have saved it as iftest.py, and run the program by pressing F5

Output:

>>>
Python is a programming Language
Program executed successfully
>>>

Now lets see what happens if the condition is not true.

python="Snake"
if python=="programming":
    # "==" means a conditional operator, which tests, whereas "=" is an assignment operator, which assigns values to a variable
    print "Python is a programming Language"
print "Program executed successfully"
#The last print statement is not a part of If statement as its not indented

The if statement will be skipped here, because, python is declared as Snake, and the if statement checks if python is a programming, which is not true

Output:

>>>
Program executed successfully
>>>

So we see here the block of "If" Statement did not run, because the condition did not meet.

Now lets see what if the condition is true, but we don't indent.

python="Snake"
if python=="Snake":
print "Python is a Snake"
#This time condition is True, but the the statement is not indented
print "Program executed successfully"
#The last print statement is not a part of If statement as its not indented

And try to run the program, the following error would appear:



Okay, So I believe by now The If statement is quite clear and also how to use it.

Now Lets make a small program using the If Statement.

# Program to check the use of IF Statement
print "Hi, Am I Python"
review = raw_input("What is your thoughts about Me, Do You Love me or Hate me? ")
test = review.lower()
if test=="love":
    print "I Love You Too"
print "Anyhow I dont care, If people Loves Me or Hates Me, I Love Myself, and Loves those who Loves me"
raw_input("Press Enter to exit")

Outputs:

>>>
Hi, Am I Python
What is your thoughts about Me, Do You Love me or Hate me? LOVE
I Love You Too
Anyhow I dont care, If people Loves Me or Hates Me, I Love Myself, and Loves those who Loves me
Press Enter to exit
>>>
================== RESTART ===================
>>>
Hi, Am I Python
What is your thoughts about Me, Do You Love me or Hate me? Love
I Love You Too
Anyhow I dont care, If people Loves Me or Hates Me, I Love Myself, and Loves those who Loves me
Press Enter to exit
>>>
================== RESTART ===================
>>>
Hi, Am I Python
What is your thoughts about Me, Do You Love me or Hate me? HATE
Anyhow I dont care, If people Loves Me or Hates Me, I Love Myself, and Loves those who Loves me
Press Enter to exit
>>>
================== RESTART ===================
>>>
Hi, Am I Python
What is your thoughts about Me, Do You Love me or Hate me? HaTe
Anyhow I dont care, If people Loves Me or Hates Me, I Love Myself, and Loves those who Loves me
Press Enter to exit
>>>

This Was Fun, Isn't it??

Okay I hope now If Statement is clear with you, Practice This, Make Your own Programs. And Don't Forget to Check my Posts.

Thank You.

Thursday, March 15, 2012

Method Continues

In this post we will discuss some more methods

Lets open up the IDLE, and make a Sequence, like:

>>>  python=['I', 'You', 'He', 'She', 'Me', 'They', 'Python']
>>> python
['I', 'You', 'He', 'She', 'Me', 'They', 'Python']

First, lets say, we want to add the element 'Idiot', between all the elements, for this, we need to assign the element to a variable.

>>> attach='Idiot'
>>> attach
'Idiot'

And to insert the element we need to follow this syntax:
to_be_attached_var_name.join(Listname_where_element_is_to_be_attached)

>>> attach.join(python)
'IIdiotYouIdiotHeIdiotSheIdiotMeIdiotTheyIdiotPython'

Next lets say, we want to change all the characters in a string to lower case.
For this the syntax is:
variable_name.lower()

Ex:

>>> case="hI tHiS iS tO cHeCk iF pYtHon cAn ConvErT tHiS tO lOwEr cAsE aNd uPpEr cAsE"
>>> case
'hI tHiS iS tO cHeCk iF pYtHon cAn ConvErT tHiS tO lOwEr cAsE aNd uPpEr cAsE'
>>> case.lower()
'hi this is to check if python can convert this to lower case and upper case'

Okay we see here that everything is converted to lower case. For converting them to upper case, we need to replace the lower with upper.

Ex:

>>> case
'hI tHiS iS tO cHeCk iF pYtHon cAn ConvErT tHiS tO lOwEr cAsE aNd uPpEr cAsE'
>>> case.upper()
'HI THIS IS TO CHECK IF PYTHON CAN CONVERT THIS TO LOWER CASE AND UPPER CASE'

So we see here that everything is converted to Upper Case.

Next we will see how to replace an element,

>>> rep="People who hates Python, Python Hates Them"
>>> rep
'People who hates Python, Python Hates Them'
>>>

Lets say, we want to replace 'hates' with 'Loves'

For this we need to use the replace function, the syntax is:

listname.replace('what', 'with what')

>>> rep.replace('hates', 'Loves')
'People who Loves Python, Python Hates Them'
>>>

Whaat?? No, Python is not supposed to be that rude, Say what, we made a mistake here, we know python is case-sensitive, so for him, 'hates' is different from 'Hates'

So if we correct it we get:

Please Note the way I correct it, and try to understand, Don't give up on it, still if u face problem with this, feel free to comment.

>>> rep
'People who hates Python, Python Hates Them'
>>> rep=rep.replace('Hates', 'hates')
>>> rep
'People who hates Python, Python hates Them'
>>> rep=rep.replace('hates', 'Loves')
>>> rep
'People who Loves Python, Python Loves Them'
>>>

So Finally we are in a mutual understanding with Python, and made us love each other.

Hope, this was informative for you, practice this, and Don't forget to check my next post.

Thank You.

Wednesday, March 14, 2012

More Stuff on Methods

Hello Everyone, in this post I will discuss the use of some more stuff about methods.

Lets open up the IDLE.

We will create a string and assign it to a variable, like,

>>> python="Hey Visitor, how is your girlfriend?"
>>> print python
Hey Visitor, how is your girlfriend?
>>>

Now, what if we want the Python to use the Visitors name. Python should say Hey Thomas, how is your girlfriend?

If you have read the earlier posts, by now you should say, hey its possible in this way.

>>> name=raw_input("Enter Your name here: ")
Enter Your name here: Subir
>>> print "Hey "+name+" How is Your Girlfriend?"
Hey Subir How is Your Girlfriend?
>>>

Now lets see the other way.

Suppose we want the Python to display something like "Hey <name>, your age is <age>"
name and age is what the user enters prior to display.

>>> python = "Hey %s, your age is %d"     [%s declares that a string type data will go here, and %d declares that an integer type will go here]
>>> var = ('Subir', '24')  ['%s will be replaced with Subir, and %d will be replaced with 24']
>>> print python % var  [Indicates the Python that print the line python, and in the line wherever you see %, replace it with the elements of var]

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    print python % var
TypeError: %d format: a number is required, not str
>>> var = ('Subir',24)
>>> print python % var
Hey Subir, your age is 24
>>>

Note: %s is used for string type data, and %d is for integer type data, and we know that strings  are written inside quotes, and integers are not inside quotes.
This is the reason why i got an error, when i declared 24 inside quotes.

Lets make a small program, that would ask the user his name, age and country, and display the same.

Lets open up the Python text editor, and type

name = raw_input("Enter Your Name Here: ")
age = input("Enter Your Age Here: ")
country = raw_input("Enter your Country Name Here: ")
python = "Hello %s, If I understand you correctly, Your age is %d, and You are from %s"
varb = (name, age, country)
raw_input("Press Enter, to see if Python understood you correctly")
print python % varb
raw_input("Press Enter To Exit")

Now Save the file as anything.py, and execute the program by pressing f5, and This is what i get as my display.

>>>
Enter Your Name Here: Subir
Enter Your Age Here: 24
Enter your Country Name Here: India
Press Enter, to see if Python understood you correctly
Hello Subir, If I understand you correctly, Your age is 24, and You are from India
Press Enter To Exit
>>>

Now lets jump to another function known as "find", this helps to find the starting index number of a given string.

Example:

>>> python = "I knew Python was a Snake, but now i know Python is a Programming Language"
>>> python.find('Python')
7
>>> python.find('snake')
-1
>>> python.find('whiskey')
-1
>>> python.find('Snake')
20
>>>

If we count the characters(including spaces), starting from 0, as we know everything in Python, like most other programming language starts at index 0, we will find that the word Python starts at index 7.

And whenever Python cannot find the given word, it returns a negative 1, means I don't know what you are searching.

And notice that its case sensitive, finding snake is not equal to finding Snake.

Okay so I hope This was informative for you, practice this, and don't forget to check on my next post.

Thank You.

Tuesday, March 13, 2012

Sorts and Tuples

Hi, In This Post we will discuss something known as Sort and Tuples.

Sort is actually a method, to display the elements of a List from smaller to bigger, lets get it clear with an example.

Open up the IDLE, and create a List.

>>> python=[12,13,15,17,18,25,5]
>>> python
[12,13,15,17,18,25,5]

Okay we have created a List named python, now how do we use the "sort" method, the syntax is still the same for using methods.

list_name.method(), sort does not take any argument.

>>> python.sort()
>>> python
[5, 12, 13, 15, 17, 18, 25]
>>>

Ok so we see here, that the elements are nicely arranged from ascending to descending.

The method "sort" is also same for a String type Sequence.

>>> cobra=list("cobrasnake")
>>> cobra
['c', 'o', 'b', 'r', 'a', 's', 'n', 'a', 'k', 'e']
>>> cobra.sort()
>>> cobra
['a', 'a', 'b', 'c', 'e', 'k', 'n', 'o', 'r', 's']
>>>

The list "cobra" initially had elements 'c', 'o', 'b', 'r', 'a', 's', 'n', 'a', 'k', 'e', and after sorting the list is arranged in order from a-->z

Now here is a small thing to notice, when we use an element which is in capital letter or upper-case, while sorting, the upper case is sorted first, then the lower case is sorted. Check this example.

>>> python=list("PythoNiSasNakE")
>>> python
['P', 'y', 't', 'h', 'o', 'N', 'i', 'S', 'a', 's', 'N', 'a', 'k', 'E']
>>> python.sort()
>>> python
['E', 'N', 'N', 'P', 'S', 'a', 'a', 'h', 'i', 'k', 'o', 's', 't', 'y']
>>>

So we see here that the upper case gets arranged first, then the lower case are arranged in order from A-->Z, a-->z

You must also know that there ia another method os sorting a String, known as "sorted".

>>> sorted("AnnacOnDa")
['A', 'D', 'O', 'a', 'a', 'c', 'n', 'n', 'n']
>>>
>>> ann="AnnacOnDa"
>>> sorted(ann)
['A', 'D', 'O', 'a', 'a', 'c', 'n', 'n', 'n']
>>>

Notice what I did here, You can easily understand, what I did, If you Have read the earlier posts seriously.


Next let us see something known as Tuples, Tuples are more Like Sequences, but are not flexible like Sequences, we cannot add, delete, append a Tuple. I dont know why such a dumb thing is included in Python, but since it is included, so you have to know about it.

Lets see how to create a Tuple

>>> new=(23,45,78,90)
>>> new
(23, 45, 78, 90)
>>>

Looks like Sequence isn't it? There is a difference, can you make it out??

Look at the braces, Sequences are enclosed within Square Brackets, and a Tuple is enclosed within round brackets.

And this is what is done for creating a String type Tuple

>>> snake=('Python', 'Jython', 'Anaconda', 'Cobra')
>>> snake
('Python', 'Jython', 'Anaconda', 'Cobra')

The only thing we can do with a Tuple is call an element to be displayed by referring to its index number.

>>> new1[2]
'Anaconda'
>>> new1[3]
'Cobra'
>>> new1[4]

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    new1[4]
IndexError: tuple index out of range
>>>

Oh It gave an error, any reason?? I did it on purpose, to show you the error type which says out of index range, i asked python to return me the element in index number 4, and there is no element in index number 4, hence it gave an error.

Ok So i hope this was informative, and Practice it play with the methods, and Don't forget to check my next post.

Thank You.

Monday, March 12, 2012

More Methods

In this post, I will show you use of some more methods. By now we should know the general syntax of writing a method which is:

Syntax: object_name.method_name(argument)

So at First Open up the IDLE, and Lets create a List,

>>> wish = ["Hello", "Visitor", "how", "are", "you", "?"]
>>> wish
['Hello', 'Visitor', 'how', 'are', 'you', '?']
>>>

Ok The First Method is "index", which returns the index number of an element in the list.

Lets say we want to know the index number of "are"

Syntax: object-name.index(argument)

>>> wish.index('are')
3
>>>

Next we will see the use another method known as "insert", this method is used to insert an element in a List, at a given index.

Syntax: Object-name.(index_number, "argument")

Lets insert the word "Dear" after "Hello", so the index number of the place where we want to insert is 1.

>>> wish.insert(1, 'Dear')
>>> wish
['Hello', 'Dear', 'Visitor', 'how', 'are', 'you', '?']
>>>

Next Lets see how to remove an element from a list with another method which is "pop". Lets try to remove the word "Visitor"

Syntax: Object-name.pop(argument)

>>> wish.pop(2)
'Visitor'
>>> wish
['Hello', 'Dear', 'how', 'are', 'you', '?']
>>>

Noticed something here?? Unlike other methods, it returns what has been removed, so index number of "Visitor" was 2, so pop takes the argument as index number of the element to be removed.

There is another method of removing an element, known as "remove", this removes/deletes an element but it will not return what has been deleted, like the method 'pop'.

Lets try to remove the word "Dear"

>>> wish.remove('Dear')
>>> wish
['Hello', 'how', 'are', 'you', '?']
>>>

Ok So we have seen the difference between the methods 'pop' and 'remove'.

Lets jump to another Method, which is "reverse", which is Last for the post but not the least.

The method "reverse", as the name suggests reverses a list.

Syntax: object-name.reverse()

>>> wish.reverse()
>>> wish
['?', 'you', 'are', 'how', 'Hello']
>>>

Notice something here, reverse did not take any argument to reverse the string.


Okay, i hope this was informative, and practice this, and don't forget to check on my next post.

Thank You!

Sunday, March 11, 2012

Introduction to Methods

In this post I am going to discuss how Methods work in Python.

What are Methods?
In simple words, methods are something that can be done to an object. By something I meant anything that can be done to an object like delete, append, count, etc.

Lets take help of an example. Lets say "Driving a Car Fast"

Here driving would be a method(Action), Car would be an Object, and Fast would be an argument.

So we would write it in this way.
car.driving(fast)

So the syntax is : objectname.action(argument)

Now lets check with few examples in IDLE, lets create a List.

>>> py1 = [12,45,78,90]
>>>

append is a built in function, and this adds elements to the end of a List

>>> py1 = [12,45,78,90]
>>> py1.append(50)
>>> py1
[12, 45, 78, 90, 50]
>>>

So we see here that 50 is added to the end of the List

Lets see one more example.

count is a function, which basically counts the number of time an element is present in a List.

We will create another List.

>>> python = list("I am Whiskey, and I Like to Program in Python")
>>> python
['I', ' ', 'a', 'm', ' ', 'W', 'h', 'i', 's', 'k', 'e', 'y', ',', ' ', 'a', 'n', 'd', ' ', 'I', ' ', 'L', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', ' ', 'i', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
>>> python.count('i')
3
>>> python.count('a')
3
>>> python.count('w')
0
>>> python.count('W')
1
>>> python.count('x')
0
>>>

Okay we see here that count, check how many times an element appears in a List. Also note that its case - Sensitive, check in case of W, lower case w, was not there in the List hence is returned 0, but upper case W appeared once, hence it returned 1.

Lets check one more example.

extend is a function, which is almost similar to append.

Lets Make Two List.

>>> list1 = [10,20,30]
>>> list1
[10, 20, 30]
>>> list2 = [40,50,60]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50, 60]
>>> list1 = [10,20,30]
>>> list2 = [40,50,60]
>>> list2.extend(list1)
>>> list1
[10, 20, 30]
>>> list2
[40, 50, 60, 10, 20, 30]
>>>

So we see here that extend function, appends another list to a list.

I hope this was informative for you, and now we know the basics of Method and how it works.

Task: Make 4 Lists and practice with the functions given in this post.

Thank You and Don't forget to check my next post.


Saturday, March 10, 2012

Slicing with Lists

In in this Post I will show you how to play with Lists by Slicing. The basics of Slicing were given in the earlier posts, If you are not sure what Slicing is, click here Slicing

As usual open up the IDLE and create a List.

>>> python=list('Pythonishard')
>>> python
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'h', 'a', 'r', 'd']
>>>

Ok so we have create a list and assigned it to variable python.

Now we will see how to edit this list, this list says Pythonishard, but I dont think so, and i will change it to Pythoniseasy, lets see how..

>>> python=list('Pythonishard')
>>> python
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'h', 'a', 'r', 'd']
>>> python[8:]='easy'
>>> python
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'e', 'a', 's', 'y']
>>>

Here we wanted to change the characters from index number 8, so python[8:0] means start overwriting from index number 8 and go till end, as the end index number is not specified.

Now lets see how to add elements to the end of the list.

>>> len(python)
12
>>>

So the Length of the List is 12, so we need to start adding from the index number 12.

>>> python[12:]=', lets start'
>>> python
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'e', 'a', 's', 'y', ',', ' ', 'l', 'e', 't', 's', ' ', 's', 't', 'a', 'r', 't']
>>>

Now lets see how to insert elements at a certain place. lets create another List.

>>> test=list('GodGreat')
>>> test
['G', 'o', 'd', 'G', 'r', 'e', 'a', 't']
>>> test[3:1]='is'
>>> test
['G', 'o', 'd', 'i', 's', 'G', 'r', 'e', 'a', 't']
>>>

So we wanted to insert 'is' before 'Great' index number of G is 3, so we need to to find the index number of the element before which we need to insert, so test[3:1]='is' means add 'i', 's' before index number 3 and 1 means from index 3 start in count of 1.

Now lets see how to delete elements from a List, we can very well do with the function del(index num), but here is one more way.


Lets create another list

>>> whiskey=list('PythonScript')
>>> whiksey

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    whiksey
NameError: name 'whiksey' is not defined



Its so embarrassing, i spelled the variable wrong and python gave me an error, sorry about that
>>> whiskey
['P', 'y', 't', 'h', 'o', 'n', 'S', 'c', 'r', 'i', 'p', 't']

Okay lets say we want to delete 'c','r','i','p'

So if we count we see that it 'c' starts with index number 7

So what we can do is:

>>> whiskey
['P', 'y', 't', 'h', 'o', 'n', 'S', 'c', 'r', 'i', 'p', 't']
>>> whiskey[7:11]=[]
>>> whiskey
['P', 'y', 't', 'h', 'o', 'n', 'S', 't']
>>>

whiskey[7:11]=[], means start from index number 7, and delete everything till index number 10(One less than the defined)

Okay so now we got some more information about how to play with Listing by Slicing. I Hope This was Informative For You.

Here is a Task For you, Make a List, and use all the functions described in this post.

Thank You for Reading this and Don't forget to check my next post.

Friday, March 9, 2012

More List Functions

In this post, I will show some more functions about lists

So as usual, open up the IDLE, and then let us create a list

>>> python = [3,5,1,75,35,0,45]
>>>

So here we created a list named "python" now we will work with this list.

First we will see how to find the length of a given list

Syntax: len(listname)

>>> len(python)
7
>>>

Ok here we have seen it replied that there are 7 elements in the list 'python'

Next, we will see how to find the biggest number in a given list

Syntax: max(listname)

>>> max(python)
75
>>>

Next we will see how to find the smallest number in a given list.

Syntax: min(listname)

>>> min(python)
0
>>>

So it returned '0' because the smallest number is 0 in the list

Next, we will see how to replace any particular element of a given list.

Syntax: listname[index_number of the element to be changed] = replace with number

>>> python
[3, 5, 1, 75, 35, 0, 45]
>>> python[4]=165
>>> python
[3, 5, 1, 75, 165, 0, 45]
>>>

Okay here 35 was was on the index number 4, and we replaced it with 165.

Next, lets see how to delete a particular element of a given list.

Syntax: del listname[index number]

>>> python
[3, 5, 1, 75, 165, 0, 45]
>>> del python[5]
>>> python
[3, 5, 1, 75, 165, 45]
>>>

So we see that '0' has been deleted from the list

Okay here is one more important function, it converts a string to a list.

Syntax: list(String)

>>> name = "Python"
>>> list(name)
['P', 'y', 't', 'h', 'o', 'n']
>>> list('Programming')
['P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
>>>

Now here I wil just show a summary of the functions that we learnt here.

>>> name = "Python"
>>> list(name)
['P', 'y', 't', 'h', 'o', 'n']
>>> list('Programming')
['P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
>>> array = list(name)
>>> array
['P', 'y', 't', 'h', 'o', 'n']
>>> len(array)
6
>>> del array[5]
>>> array
['P', 'y', 't', 'h', 'o']
>>> array[4]='m'
>>> array
['P', 'y', 't', 'h', 'm']
>>> name
'Python'
>>>

Okay, I hope This was informative and clear

Here is a task for you, make a list of numbers and show the use of all the functions that has been discussed.

Thank You.