Tag Archives: python basics

Python- Swap two number

We can now start to write simple programs in Python, which is really the best way to learn a language.

An easy program to swap two numbers. Python has a simple construct which enables to easily swap two numbers.

 

x = 10
y = 15

x,y=y,x

print(‘The value of x after swapping: {}’,format(x))
print(‘The value of y after swapping: {}’,format(y))

The output of the above program:

The value of x after swapping: {} 15
The value of y after swapping: {} 10
>>>

Advertisements

Python- The Dictionary

This is the implementation of the ‘key-value’ pair in Python. Each key and value is separated by a colon :

dict = {‘Color’: ‘Red’,’Value’:’255,0,0′}

The value of the dict can be updated as follows:

dict[‘Color’] = ‘Green’
dict[‘Value’] = ‘0,255,0’

You can delete individual pair using the del statement.

Len gives the length of the dictionary.

dict = {‘Color’: ‘Red’,’Value’:’255,0,0′}
print(dict)
print (“dict[‘Color’]”,dict[‘Color’])
print (“dict[‘Value’]”,dict[‘Value’])

dict[‘Color’] = ‘Green’
dict[‘Value’] = ‘0,255,0’

print (“dict[‘Color’]”,dict[‘Color’])
print (“dict[‘Value’]”,dict[‘Value’])

del dict[‘Color’]
print(dict)

del dict[‘Value’]
print(dict)
dict = {‘Color’: ‘Blue’,’Value’:’0,0,255′}

print(len(dict))

print(‘Str produces a printable string reprsentation of %s’ % str(dict))

The output of the above program:

Output :

{‘Color’: ‘Red’, ‘Value’: ‘255,0,0’}
dict[‘Color’] Red
dict[‘Value’] 255,0,0
dict[‘Color’] Green
dict[‘Value’] 0,255,0
{‘Value’: ‘0,255,0’}
{}
2
Str produces a printable string reprsentation of {‘Color’: ‘Blue’, ‘Value’: ‘0,0,255’}

Python- The Tuples

Since list used the square brackets [], tuple had to do with the paranthese ()

The next big difference between list and tuple is that tuples are immutable. That means the value of the tuple cannot be changed.

We can change the value of list, but we will get an error ‘object does not support item assignment’ when we try to do the same for a tuple.

 

 

We cannot delete individual elements as we did in lists.

But, we can delete the entire tuple using the method ‘del’

Some of the others methods in tuple are : min,max,len

 

tuple = (‘0′,’1′,’2’)
print(‘Print the tuple :’,tuple)
del tuple
print(‘Tuple has gone empty :’,tuple)

tup2 = (‘0′,’1′,’2’)
tuple = tup2
print(‘Print the tuple :’,tuple)
print(‘Length of the tuple is now ‘,len(tuple))

tuple = tuple + tup2
print(‘Print the tuple :’,tuple)
print(‘Length of the tuple is now ‘,len(tuple))

tup3 = (‘-1′,’7’)
tuple = tuple + tup3

print(‘Maximum value in the tuple is ‘,max(tuple))
print(‘Minimum value in the tuple is ‘,min(tuple))

 

The output of the above program

 

Print the tuple : (‘0’, ‘1’, ‘2’)
Tuple has gone empty : <class ‘tuple’>
Print the tuple : (‘0’, ‘1’, ‘2’)
Length of the tuple is now 3
Print the tuple : (‘0’, ‘1’, ‘2’, ‘0’, ‘1’, ‘2’)
Length of the tuple is now 6
Maximum value in the tuple is 7
Minimum value in the tuple is -1

Python- The Lists

LIST

List is a built-in data type where the literals are enclosed within the square brackets []

To declare a list, put the list of literals in a square bracket:

fruits = [‘Mango’,’Apple’,’Orange’]

 

We can access the list using indexes, starting from 0 or using a for loop.

The IN operator lets us check if an element appears in the list.

The output once you run the above program:

 

Some of the common methods to manipulate the list are:

list.append(element) : Adds a single element to the end of the list.

list.reverse : Reverses the list.

list.sort : Sorts the list

list.remove(element) : Removes the first instance of the element

list.insert(index,element) : Inserts the element at the given index

list.extend(list2) : Adds all the elements of list2 at the end of list. Similar to list+list2

list.pop(index) : Removes and returns the element at the given index

list.index(element) : Returns the index of the given element, starting from first.

We can test for all of the above methods using the simple program:

fruits = [‘Mango’,’Apple’,’Orange’]
veg =[‘Potato’,’Cabbage’]

print (fruits)

fruits.append(‘Banana’)
fruits.reverse()
print (‘After reverse and append :’,fruits)

fruits.sort()
print (‘After Sort :’,fruits)

fruits.remove(‘Mango’)
print (‘After Remove :’,fruits)

fruits.insert(0,’Grapes’)
print (‘After Insert :’,fruits)

fruits.extend(veg)
print (‘After Extend :’,fruits)

fruits.pop(4)
print (‘After Pop :’,fruits)

print(‘Orange is at position : ‘,fruits.index(‘Orange’))

The output of the above program:

 

[‘Mango’, ‘Apple’, ‘Orange’]
After reverse and append : [‘Banana’, ‘Orange’, ‘Apple’, ‘Mango’]
After Sort : [‘Apple’, ‘Banana’, ‘Mango’, ‘Orange’]
After Remove : [‘Apple’, ‘Banana’, ‘Orange’]
After Insert : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’]
After Extend : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’, ‘Potato’, ‘Cabbage’]
After Pop : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’, ‘Cabbage’]
Orange is at position : 3

Python- The Strings

Strings in Python can be created by enclosing characters in either single quotes ‘example ‘  or in double quotes “example”

It’s easy to declare a string as shown below:

str1 = ‘hello world’

str2 =  “hello world”

 

 

To concatenate two strings we can use the ‘+’  operator

 

 

You can use brackets for slicing the string between indexes:

 

When you run the final program, you should get the output as below:

Python- The Decisions

  IF..ELSE

  1. We will start with the simple if..else statement in Python.
  2.  Create a new file ifelse.py and enter the below lines:num = 100
    if (num == 100) : print(“Value of the number is 100”)
    else :
    print (“Value of the number is not equal to 100”)print(“Exit”)                          
  3. Save the file and under Run menu, click on Run module. You should get the output as shown below:

 

All in One

  1. Next, we will see how to use the if, elif and else statements in one program.
  2. Type the code snippet as given below:

          

      3. Save the file and under Run menu, click on Run module. You should get the output as shown below: