Sunday, 27 October 2019

Python program to display Good Morning message based in given time

Python program to display Good Morning message based in given time.


time = int(input("Enter your time:"))

if time < 12:
    print ("Good Morning...")

print("Have a nice time...")

Output of Program

Enter your time:5
Good Morning...
Have a nice time...

Note: If user enters time greater than 12 then program will display only "Have a nice time..." message.

Python program to check odd even number

Python program to check odd even number


Following Python program will read a number from user and will display whether it is odd or even.

To check whether given number is ODD or EVEN, program uses modulus operator (%) and divides given number by 2. If the answer of modulus operator is 0; it means given number is  completely divisible by 2, hence we can display that "It's even number". If answer of modulus operator is not zero, it means number is Odd.


#Python program to check odd-even number.

number = int(input("Enter your number:"))

if (number%2 == 0):
    print("It's even number")
else:
    print("It's odd number")


Output of program

Enter your number:101
It's odd number


* * * * *

Sunday, 20 October 2019

Python Tuple

Python Tuple


Tuple is an ordered sequence of items. Tuple in python are very similar to  List. The only difference between Tuple and List is that tuples are immutable. Values cannot be modified in Tuples once created.

Tuples are used to create a data which we don't want to change after it's creation. Values inside tuples are like protected data and are usually faster than list as it cannot change dynamically.

Tuples are defined using parentheses (). Items inside tuples are separated by commas. Example of tuple is shown below:


>>> myTuple = (101,'PythonPracticals', 'KPatel')
>>> print(myTuple)
(101, 'PythonPracticals', 'KPatel')


We can refer individual elements of Tuple as shown below:

>>> print(myTuple[0])
101

We can use the slicing operator [ ] to extract items from Tuple but we cannot change its value. For example:


# Using Slicing Operator with Tuple

>>> print(myTuple[0:2])
(101,'PythonPracticals')

# Editing value of Tuple

>>> myTuple[0]=105
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    myTuple[0]=105
TypeError: 'tuple' object does not support item assignment




* * * * *

< Back to Home Page >

Tuesday, 17 September 2019

Operations on Python Lists

Operations on Python Lists

It is possible to perform operations like addition, multiplication and searching on Python Lists. 

Addition Operation on Python Lists


Addition operation on Lists is possible using + operator:

>>> list1 = [1, 2] 
>>> list1
[1, 2]

>>> list2 = [3, 4] 
>>> list2
[3, 4]

>>> list1 + list2
[1, 2, 3, 4]

Multiplication Operation on Python Lists


Multiplication operation on Lists is possible using * operator:

>>> mylist = [1, 2] 
>>> mylist
[1, 2]

>>> mylist * 3 
[1, 2, 1, 2, 1, 2]

Note: The + and * operations do not modify the list. The original list will remain same even after use of + and * symbols on it. 

Search operation in Python Lists

in keyword can be used to search an element in the given list.

>>> insurance = ['sbi', 'icici', 'hdfc', 'hsbc'] 
>>> insurance
['sbi', 'icici', 'hdfc', 'hsbc']

>>> 'sbi' in insurance 
True

>>> 'seas' in insurance 
False

Assignment operation to Slices


Use of assignment operator to slices is possible. It can even change the size of the list or clear it entirely:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']

# replace some values of lists
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']

# remove elements from list
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']

# clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

Built-in Functions for Python Lists

Built-in Functions for Python Lists



len( ) function with List


len ( ) finds the number of items or elements in a list. Following code will return the length of the list - insurance. 


>>> insurance = ['sbi', 'icici', 'hdfc', 'hsbc'] 
>>> print(len(insurance))
4

min() and max() functions with Lists


Mininum and Maximum value can be identified using min() and max() function from the lists as shown below:

>>> list1 = [1, 2, 5, 10, 8] 
>>> print(min(list1))
1

>>> print(max(list1))
10

Built-in Methods for Python Lists

Python Lists - Built-in Methods


Let's learn some of the top built-in methods available for Python - lists.

Using append() with List

append() function can be used to add new items at the end of the list:
>>> cubes = [1, 8, 27, 64, 125]
>>> cubes
[1, 8, 27, 64, 125]

# append 216 at the end
>>> cubes.append(216)

# append cube of 7 at the end
>>> cubes.append(7 ** 3)
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Using insert() with List

insert() function will add element to a list at specified position(index number). Check the following example:


>>> list1 = ['a', 'b', 'c']
>>> list1.insert(2, 'kp')
>>> list1
['a', 'b', 'kp', 'c']



Using extend() with List

Python extend() function combines two lists. Check the following example:


>>> myList1 = ['a', 'b', 'c']
>>> myList2 = [1, 2, 3]
>>> myList1.extend(myList2)
>>> print(myList1)
['a', 'b', 'c', 1, 2, 3]



Using pop() and remove() with List

pop() function will get the value of an item and remove it from the given list. pop() function needs index number of a list as a parameter. Check example of pop():


>>> list1 = ['a', 'b', 'c', 'd']
>>> list1
['a', 'b', 'c', 'd']
>>> list1.pop(2)
'c'
>>> list1
['a', 'b', 'd']

Using remove() with List

remove() function deletes an item from a list. remove() function needs actual value of an item as a parameter. Check following example of remove():

>>> list1 = ['a', 'b', 'c', 'd']
>>> list1.remove('d')
>>> list1
['a', 'b', 'c']

Using reverse() with List 
Reverse the elements of a given list.


>>> list1 = ['a', 'b', 'c', 'd']
>>> list1
['a', 'b', 'c', 'd']
>>> list1.reverse()
>>> list1
['d', 'c', 'b', 'a'] 

Using sort() with List 
Sort the elements of a given list alphabetically or numerically.


>>> list1 = ['c', 'b', 'a', 'd']
>>> list1
['c', 'b', 'a', 'd']
>>> list1.sort()
>>> list1
['a', 'b', 'c', 'd']


Python Lists

In Python, list is one of the basic data structure useful to store multiple data items. 

  • Python list is the compound data types which can be used to group values
  • List is a kind of collections in Python. 
  • The list can be written as a list of comma-separated values (items) between square brackets
  • Lists might contain items with different data types. Let’s use Python’s List.

Creating a Python's List


Following example will create a list of characters, numbers and words.

# List of characters

>>> myList = ['a', 'b', 'c', 'd', 'e']
>>> myList
['a', 'b', 'c', 'd', 'e']

# List of numbers

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

# List of words

>>> insurance = ['sbi', 'hdfc', 'icici', 'lic']
>>> insurance
['sbi', 'hdfc', 'icici', 'lic']


Accessing values from a List


Elements of List can be used by referring it's index number. For example, to print first value from list - insurance, use following code:

>>> insurance[0]
'sbi'

>>> print(insurance[0])
sbi


Like strings, lists can also be indexed and sliced:

# index 0 returns the first item
>>> squares = [1, 4, 9, 16, 25]
>>> squares[0]
1

# index -1 returns the last item
>>> squares[-1]
25

# slicing returns a new list
>>> squares[-4:]
[4, 9, 16, 25]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Lists are a mutable type; hence it is possible to change content of list. Check the following examples:


# something's wrong in following code; cube of 4 is not 65; let's change it.

>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
* * * * *


Sunday, 15 September 2019

Sub-string in Python using Slicing

Python - Sub-string Function using Slicing

Index number of a string can be used to obtain individual characters from a string. Slicing can be used to obtain a sub-string from the given string. Check the following examples:

>>> str = 'PythonPracticals'

#Code to refer position 0 (included) to 3 (excluded)
>>> str[0:3]
'Pyt'

# position 0 (included) to 6 (excluded)
>>> str[0:6]
'Python'

# position 4 (included) to 6 (excluded)
>>> str[4:6]
'on'

In slicing, the starting index number is included and ending index number is excluded in the result. 

If we omits the first index number in slicing, it will be considered as 0. An omitted second index will be considered as the size of the string being sliced. Observe following interesting string slicing examples:

>>> str = 'PythonPracticals'

# prints from beginning to index 6(excluded)
>>> str[:6]
'Python'

# prints from beginning to index 16(excluded)
>>> str[:16]
'PythonPracticals'

# prints from index -4 to end of string
>>> str[-4:]
'cals'

>>> str[:6] + str[6:]
'PythonPracticals'

>>> str[6:] + str[:6]
'PracticalsPython'

For non-negative indices, the length of a slice(substring) is the difference of the indices. If both are within proper boundary (limits), the length of str[1:4] is 3.

Attempting to use out of range index (too large/small) will result in an error as shown below:

>>> str = 'PythonPracticals'
>>> str[101]  # the str has only 16 characters
Traceback (most recent call last):
  File "< pyshell#1>", line 1, in <module>
IndexError: string index out of range

Out of range slice indexes are handled properly by Python interpreter. Check following example:

>>> str = 'PythonPracticals'
>>> str[6:30]
'Practicals'

Python strings cannot be changed — they are immutable. Therefore, assigning value to a specific index position will result in an error.

>>> str[0] = 'K'
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
       str[0]=’K’
TypeError: 'str' object does not support item assignment

If you want to modify your string, you should create a new one:

>>> 'K' + str[1:]
'KythonPracticals'

String Length using in-built function len()

Built-in function len() returns the length of a given string:
>>> str = 'PythonPracticals'
>>> len(str)
16

>>> str1 = 'K. Patel'
>>> len(str1)
8

>>> print(len(str+str1))
24

* * * * *


String and Index number in Python

Python - String and Index number

Strings can be used in Python using index (subscript).

Each character of a String is assigned an index number from left to right starting with number 0. For example, for a string “Python”, the index numbers are:


 +-----------------------+
 | P | y | t | h | o | n |
 +-----------------------+
   0   1   2   3   4   5  

0 to 5 are respective index number assigned to individual character of a string Python.

 +-----------------------+
 | P | y | t | h | o | n |
 +-----------------------+
  -6  -5  -4  -3  -2  -1  

-1 to -6 are the corresponding negative indices of a string “Python”.

The first character of a string is indexed as 0. Observe the following examples to understand string index numbers:

>>> str = 'PythonPracticals'

# prints character at position 0
>>> str[0]  
'P'

# prints character at position 1
>>> str[1]  
'y'

# prints character at position 2
>>> str[2]  
't'

# prints character at position 5
>>> str[5]
'n'

In Python string, index may also have negative numbers. To refer string from the end to first character of a string, negative index is useful. Check the following examples:


>>> str = 'PythonPracticals'

# prints last character
>>> str[-1]  
's'

# prints second-last character
>>> str[-2]
'l'

# third character from end of string
>>> str[-3]
'a'

Note that since -0 is considered as 0, negative index starts with -1 value.


Saturday, 14 September 2019

Python String Merge (Concatenation)

String Merge (String concatenation)


String concatenation means the operation of joining two strings. It is also known as string merge. In Python programming, two strings can be merged (concatenated) using the + operator.

>>> 'Python' + 'Practicals'
'PythonPracticals'

#Multiple strings are automatically merged

>>> 'Python''Practicals'  
'PythonPracticals'

>>> 'Ahmedabad''Gujarat''India'  
'AhmedabadGujaratIndia'

This works only with two literals; a variable and a string can’t be merged directly. Look at the example given below:


>>> str = 'Python'
>>> str 'Practicals'
SyntaxError: invalid syntax

>>> (str*2) 'Practicals'
SyntaxError: invalid syntax

To concatenate a variable and a string literal, use + operator as shown below:

>>> str = 'Python'
>>> str + 'Practicals'
PythonPracticals

expression + a string is valid

>>> (str*2) + 'Practicals'
'PythonPythonPracticals'

Multiplying String with * Operator

String can be repeated using * operator in Python. Check the following example:

>>> 3 * 'Python '
'Python Python Python '

>>> 2 * 'Practicals '
'Practicals Practicals '

* * * * *