Showing posts with label Methods. Show all posts
Showing posts with label Methods. Show all posts

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.

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.

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.