Wednesday 25 December 2019

Python program to read and print your name and address

Following python program will read and print name, address and mobile number of the user.


Concept to learn

input ( ) : Python input() function can be used to read user inputs. No need to specify variable data type as Python automatically identifies whether entered data is a string or a number.

Source code

# Python program to read and print your name and address using the input() function.
  
name = input("Enter your name: ") 
print(name)

address = input("Enter your address:")
print (address)

mobile = input("Enter your mobile number:")
print(mobile)

Program output

Enter your name: K Patel
K Patel
Enter your address: Ahmedabad, Gujarat, India
Ahmedabad, Gujarat, India
Enter your mobile number: 9898989898
9898989898



* * * * *


Sunday 22 December 2019

Print Hello World

Python program to print hello world message.

Following python program will print Hello World message on output screen.

Source code
>>> print('Hello World!!!')

Program output
Hello World!!!

* * * * *

Tuesday 3 December 2019

Python program to print square pattern of star

PYTHON PROGRAM TO PRINT Square Pattern of star


* * * *
* * * *
* * * *
* * * *

We can generate a square pattern using for loop and range() function. Number of lines to be printed will be taken from user.

Python program to print square pattern of star.


number_of_lines = int(input("Please Enter number of lines:"))

for i in range(number_of_lines):    

   for i in range(number_of_lines):        
      print('*', end = '  ')    
   print()

Program Output - 1

Please Enter number of lines:3

*  *  *  
*  *  *  
*  *  *

Program Output - 2

Please Enter number of lines:4
*  *  *  *  
*  *  *  *  
*  *  *  *  
*  *  *  *


Monday 2 December 2019

Python program to print A to Z alphabets

Python program to print A to Z alphabets


We can generate a sequence of characters between A to Z using range() function and for loop.

range() function will start from 65 (ASCII of A) and will stop at 90 (ASCII of Z). chr() function will help us in printing ASCII character of a given integer number.

Python program to print A to Z alphabets.


for i in range(65, 91):
    print(chr(i), end=' ')

Output of Program

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z



Python program to print Z to A alphabets.


for i in range(90,64,-1):
    print(chr(i), end=' ')

Output of Program

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A


* * * * *

Sunday 1 December 2019

Python program to print 1 to 10 numbers.

Python program to print 1 to 10 numbers


We can generate a sequence of numbers between 1 to 10 using range() function and for loop.

We can also define the starting, ending and step size as range(start,stop,step size) function parameters. By default step size is 1.

# Python program to print 1 to 10 numbers.

for i in range(1,11):
  print(i, end=' ')

Output of the program

1 2 3 4 5 6 7 8 9 10 

# Python program to print 10 to 1 numbers.

for i in range(10,0,-1):
    print(i, end=' ')

Output of the program

10 9 8 7 6 5 4 3 2 1 

Saturday 30 November 2019

Python Dictionary

PYTHON DICTIONARY


Introduction to Python – Dictionary


Dictionary is a collection of related data item pairs. 

A python dictionary is a collection of unordered items which are changeable and indexed. In Python dictionaries are written using curly brackets, and they have keys and values.


Important properties of Python - Dictionary


Un-ordered – Elements/items stored in a python dictionary are not kept in any particular order.
Changeable (mutable) – Structure and elements can be changed in place; elements can be added and removed.
Accessed by keys – Dictionary items are accessed by the keys, not by their position number (index).
Nesting Properties - Dictionaries can be nested, i.e. a dictionary can contain another dictionary in it.

Create a Python Dictionary


The dictionaries are created using curly brackets. Curly brackets contains pairs of key-value. 

>>> dist1 = {"brand":"Maruti", "model":"Desire", "year":2019}

>>> print(dist1)
{'brand': 'Maruti', 'model': 'Desire', 'year': 2019}

Accessing elements of a Python Dictionary


Following syntax can be used to access the individual elements of the python dictionary.

>>> print(dist1['brand'])
'Maruti'

>>> print(dist1['model'])
Desire

>>> print(dist1['year'])
2019

Following functions can be used to display all keys and values of the python dictionary.

>>> dist1.keys()
dict_keys(['brand', 'Model', 'Year'])

>>> dist1.values()
dict_values(['Maruti', 'Desire', 2019])


Sunday 10 November 2019

Python Set

Python Set


Introduction to Python – Set

A set is an unordered collection of elements. Every element is unique (no duplicate values in set) and are immutable (i.e. values cannot be changed). However, the set itself is mutable which means we can add or remove elements from set.

Sets is very useful to perform mathematical set operations like union and intersection.

Create a Python Set

A set is created by placing all the elements within curly braces { } and each elements separated by comma.

Set can have any number of elements with different data types like integer, float, string etc.

Example of set of an integers

>>> set1 = {1, 2, 3}
>>>set1
{1, 2, 3}

# set of mixed data types
>>>set2 = {101, "K Patel", 90.5}
>>>print(set2)
{'K Patel', 90.5, 101}

Set removes duplicate entries and arranges elements in order.

>>> set3 = {1,3,2,5,4,3}
>>> set3
{1, 2, 3, 4, 5}

Observe the following code:
>>> set2[0]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
set2[0]
TypeError: 'set' object is not subscriptable

Note: 'set' object does not support indexing in python. We can’t access an element of set using indexing or slicing concept.

Changing Python Set Elements

Add() method can be used to add single element in to a set.

>>> set4 = {3, 5, 7}
>>> set4
{3, 5, 7}

>>> set4.add(6)
>>> set4
{3, 5, 6, 7}

Removing elements from Set

>>> set4.remove(7)
>>> set4
{3, 5, 6}

Note: Trying to remove element which does not exists in set will result in error. Observe the following code:

>>> set4(2)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
set4(2)
TypeError: 'set' object is not callable

Python Set Operations - Union and Intersection

Python sets can be used to perform mathematical set operations like union and intersection.

Python Set Union

Union of Set A and Set B is a set of all elements from both the python sets. Union operation can be performed using union operator( | ) or the method union().

>>> set5 = {2, 4, 6, 8}
>>> set6 = {6, 8, 10, 12}
>>> set5.union(set6)
{2, 4, 6, 8, 10, 12}

>>> print(set5 | set6)
{2, 4, 6, 8, 10, 12}

Python Set Intersection

Intersection of Set A and Set B is a set of elements that are common in both sets. Python intersection can be performed using intersection operator ( & ) or using the method intersection().

>>> set5 & set6
{8, 6}

>>> set5.intersection(set6)
{8, 6}


* * * * *

<  Back to Home Page >

Sunday 3 November 2019

Positive negative or zero number

Following Python practical will check whether entered number is positive or negative or zero. This program uses the concept of Python's nested if statement.

# Program will check whether entered number is positive or negative or zero.

number = int(input("Enter a number: "))
if number >= 0:
    if number == 0:
        print("It's Zero")
    else:
        print("It's Positive number")
else:
    print("It's Negative number")

Output of program

Enter a number: 5
It's Positive number

* * * * *

<  Back to Home Page >


Wednesday 30 October 2019

python if else

Python provides following decision making statements (also known as conditional statements):

  • if statement
  • if..else statement
  • nested - if statement
Let's learn if..else statement of Python programming.

if..else statement


if..else statement is one of most commonly used conditional statement of Python programming. "if..else statement" is written by using the if and else keyword. if..else statement consists of a Boolean expression which is followed by one or more logical statements.

Example 1: Use of if..else statement to check greater number.

number1 = 201
number2 = 101

if number1 > number2:
    print ("number1 is greater than number2.")
else:
    print ("number1 is not greater than number2.")


Output of Program

number1 is greater than number2.

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

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

if time < 12:
    print ("Good Morning...")
else:
    print ("Have a nice time...")

Output of Program

Enter your time:5
Good Morning...


Example 3: Python program to check whether given number  is positive or not.

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

if number > 0:
    print ("It's positive number")
else:
    print ("It's not positive number")

Output of Program

Enter your time:5
It's positive number

#Note: If entered number is negative or zero then this program will print only "It's not positive number" message.

Sunday 27 October 2019

Python program to check whether given number is positive or not.

Python program to check whether given number is positive or not.

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

if number > 0:
    print ("It's positive number")
print("It's end of program")

Output of Program

Enter your time:5
It's end of program


Note: If entered number is negative or zero then this program will print only "It's end of program" message.

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]
* * * * *