List,Tuple,Set and Dictionary in Data type models - Python

 Data type models in python:

  • The data type is nothing but, it tells about kinds of data.
  • The data type models are used to store collection of data under a common name.

Type’s data type model:

  • List
  • Tuple
  • Set
  • Dictionary

1. List:

  • The list data type is used to store the collection of an item in an ordered sequence.
  • These items are mutable, which means changeable as possible.
  • It is denoted by square bracket [].
  • Its index value is started with 0 and ends with list_length-1.

Syntax:

  1. Declaring list:

    Variable_name=[]

    Example:

    List=[]

    Declaring value into the list:

    Variable_name=[item1,item2,...item n]

    Example:

    a=[1000,’Kurshitha’,’female’,450]

Example program:

  1. a=[5,1,8,3]

    print("Fist value : ",a[0])

    print("Last value : ",a[len(a)-1])

    print("Another method to print last value : ",a[-1])

    print("List of elements : ",a)

Output:

Print list in looping statement:

  1. a=[5,1,8,3]

    for i in a:

        print(i)

Output:

Insert or append an item into the list:

  • To insert an element in the list is used append() function.

  1. pin=[1234,1111,1211,1457]

    p=int(input("Enter an item to add in list : "))

    pin.append(p)

    print("Your list of items are: ")

    for i in pin:

        print(i)

Output:

2. Tuple:

  • The tuple data type is used to store collection of item in unordered and it allows duplicate values same as a list.
  • These items are immutable, that means cannot be changed tuple.
  • It is denoted by parentheses () but if calling the index value means using square brackets [].
  • Its index value is started with 0 and end with list_length-1.

Syntax:

  1. Declaring tuple:

    Variable_name=()

    Example:

    t=()

    Declaring value into the list:

    Variable_name=(item1,item2,...item n)

    Example:

    a=(1000,’Kurshitha’,’female’,450)

Example program for print tuple elements:

  1. a=(5,1,8,3)

    print("Fist value : ",a[0])

    print("Last value : ",a[len(a)-1])

    print("Another method to print last value : ",a[-1])

    print("List of elements : ",a)

Output:

3. Set:

  • The set data type is used to store unique values and displayed by ordered sequence manner.
  • These items are mutable, that means can change the sets.
  • It is denoted by curly braces {} but if calling the index with value means not possible.

Syntax:

  1. Declaring value into the set:

    Variable_name={item1,item2,...item n}

    Example:

    a={1000,’Kurshitha’,’female’,450}

Example program for print the set of elements:

  1. a={8,5,1,3,7}

    print(a)

Output:

Insert an item into the set:

  • To insert an element in the set is used add() function.

  1. a={8,5,1,3,7}

    a.add(15)

    print(a)

Output:

Insert number of items at a time into the set:

  • To insert number of element in set is used update() function.

  1. a={8,5,1,3,7}

    a.update([15,10,11])

    print(a)

Output:

4. Dictionary:

  • The dictionary data type is similar to the sets but a little bit different and the dictionary are also mutable.
  • It contains pair of parameters. i.e, keys and values.
  • Key is used to store element names.
  • Value is used to store element values.

Syntax:

  1. Declaring dictionry:

    Variable_name={}

    Example:

    dict={}

    Declaring value into the list:

    Variable_name={item_name 1: item_value 1,

                               item_name 2: item_value 2,

                               item_name n: item_value n}

    Example:

    std={"Roll_num":1000,'Name':'Kurshitha','Gender':'Female','mark':450}

Example program for print the dictionay of elements:

  1. std={"Roll_num":1000, 'Name':'Kurshitha','Gender':'Female','mark':450}

    print("Student name: ",std['Name'])

    print("Elements in dictionary:")

    print(std)

Output:

Print element name in for loop using keys() function:

  1. std={"Roll Number":1000,'Name':'Kurshitha','Gender':'Female','Mark':450}

    for i in std.keys():

        print(i)

Output:

Print element values in for loop using values() function:

  1. std={"Roll Number":1000,'Name':'Kurshitha','Gender':'Female','Mark':450}

    for i in std.values():

        print(i)

Output:

Print key and values in for loop using item() function:

  1. std={"Roll Number":1000,'Name':'Kurshitha','Gender':'Female','Mark':450}

    for k,v in std.items():

        print(k,":",v)

Output:

Share:

Break,Continue and Pass in Python

  Looping control statements or Unconditional control statement in Python:

  • Unconditional control statement is also called a jump statement.
  • There are three kinds of jumping statements,

*Break

*Continue

*Pass

Break statement:

  • The break statement is used to execute particular blocks only.
  • If give break statement then it stops the process.

Syntax:

  1. Loop or if conditions:

             break

Example program:

  1. #Write a program to check pin number until it becomes correct

    pin=1234

    while True:

        p=int(input("Enter pin number: "))

        if(p==pin):

            print("you can choose the below options: \n1.Cash withdrawal \n2.Cash deposit \n3.Mini Statement")

            break

        else:

            print("Sorry try again!!!")

Output:

if-condition with break:

else-condition:

Continue statement:

  • The continue statement is used inside loops.
  • Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for the next iteration, skipping the execution of statements inside the loop’s body for the current iteration.
  • The continue is a special statement which is used within to force the next iteration to happen.

  • It is syntactically allowed to appear only within a for or while loop.

Syntax:

  1. Loop or if conditions:

             continue

Example program:

  1. for i in range(10):

        if i%2 == 0:

            continue

        print(i,end=" ")

Output:

Pass statement:

  • It is a null operation or default statement.
  • It is typically used when an empty need function is required that time use the pass statement.
  • It basically the pass statement give or not, working as normal. i.e, with pass and without pass are the same.

Syntax:

  1. Loop or if conditions:

             pass

Example program:

  1. for i in range(1,11):

        pass

        print(i,end=" ")

Output:

Share:

Conditional control statement type two in Python

 Looping statements in python:

  • It is used to execute continually until the condition becomes false.
Types:
  • For
  • While
1. for loop:
  • It is used to execute a set of instructions repeatedly until the condition becomes false.
Syntax:

 for variable_name in sequence or range(start,end,step):
          Statement

Example program for for loop using sequence:

#Write a program to given word has vowels or not

count=0

a=input("Enter any word : ")

for i in a:

    if i in 'AEIOUaeiou':

        count+=1

print("This word contain vowels of count is : ",count)

Output:
Example program for for loop using start value:

#Write a program to print 1 to 10

for i in range(10):

    print(i)

Output:
Example program for for loop using start and stop value:

#Write a program to print 1 to 10

for i in range(1,11):

    print(i)        

Output:
Example program for for loop using step value:

#Write a program to print 1 to 10 by even number only

for i in range(2,12,2):

    print(i)

Output:
2. While:
  • It first checks the condition then executes the result until becomes false.
  • While True condition is acts as a switch statement in c++ or java.
Syntax:

 while (condition) or True:
          Statements

Example program for while condition:

#Write a program to print 1 to 10 by even number only

i=1

while i<=10:

    print(i)

    i+=1

Output:
Example program for while condition:

l=[]

ans='y'

while ans=='y':

    bno=int(input("Enter book number :"))

    bname=input("Enter book name :")

    author=input("Enter Author Name :")

    price=float(input("Enter book price :"))

    brec=str(bno) + " \t" + bname + " \t" + author + " " + str(price)

    l.append(brec)

    ans=input("Add more records?")

print("Book details :\nNumber\tName\tAuthot\tPrice")    

for i in l:

    print(i)

Output:
Example program for while condition with true statement:

#Write a program to print 1 to 10 by even number only

a,b=input("Enter two value: ").split()

choice=1

while True:

    choice=int(input("1.Add \n2.Sub \n3.Mul \n4.Div\n5.Exit 

\nEnter your choice(1 to 4):"))

    if choice==1:

        print("Add of "+a+" and "+b+" value is: ",int(a)+int(b))

    elif choice==2:

        print("Sub of "+a+" and "+b+" value is: ",int(a)-int(b))

    elif choice==3:

        print("Mul of "+a+" and "+b+" value is: ",int(a)*int(b))

    elif choice==4:

        print("Div of "+a+" and "+b+" value is: ",int(a)/int(b))

    elif choice==5:

        break

    else:

        print("Please enter correct choice...")

Output:
Share:

Conditional control statement type one in Python

 Branching statement in python:

  • All the instructions are executed sequentially by default when no repetitions of some calculations are necessary.
  • In some situation, we may have to change the execution order of statements based on condition or to repeat a set of the statement until certain conditions are met.
  • These conditions are followed by indented space.

Tyes of branching statements:

1. If statement
2. If – else statement
3. Nested if....else statement
4. If ....else ladder

1. If statement:
  • It is used to check the condition and if true then it executes.
Syntax:

 if condition:
            True statement

Example program for if:

x=int(input("Enter any value: "))

if (x%2==0):

    print("Entered value is even")

Output:
if condition:
False case:
2. If – else statement:
  • It is used to check both conditions i.e. true and false.
  • It executes only one condition at a time.
Syntax:

if (condition):
          True statement
else:
          false statement

Example program for if-else:

x=int(input("Enter any value: "))

if (x%2==0):

    print("Entered value is even")

else:

    print("Entered value is odd")

Output:
if condition:
else condition:
3. Nested if....else statement:
  • Multiple if-else conditions are validating i.e. within condition check first after that execute.
Syntax:

if(condition 1):
          True statement1
          if(condition 2):
                   True statement2
          else:
                   False statement2
else:
          False statement1

Example program for nested if...else:

#write a program based on 11th group selection

x=input("Enter pass or fail in 10th standard: ")

if x in 'pass,Pass':

    mark=int(input("Entered total mark:"))

    if(mark>=450):

        print("You can choose all groups")

    else:

        print("You can also choose all group except first group")

else:

    print("Entered correct spelling of pass")


Output:
if-if condition:
if-if-else case:
else condition:
4. The if...else ladder:
  • It is similar to nested if but it checks continually.
Syntax:

if(condition):
          Statement1
elif(condition 2):
          Statement2
elif(condition 3):
          Statement3
else:
          Statement4

Example program for if...else ladder:

#Write a program to find biggest value among three numbers

a,b,c=input("Enter three value : ").split()

if a>b and a>c:

    print(a+" is biggest value.")

elif b>c:

    print(b+" is biggest vaue.")

else:

    print(c+" is biggest value.")


Output:
if condition:
else if  condition:
else condition:
Share:

Decision making in Python

Control statements in Python:

  • The control statement is nothing but, is used to control your program.
  • That means you are having control over how it executes based on logic and based on your requirements.

Types of control statement:

There are two types of control statements,

1. Conditionalcontrol statement

1.1. Branching statements

*If statement

*If – else statement

*Nested if....else statement

*If ....else ladder

1.2. Looping statements

*for

*While

2. Unconditional control statement or looping control statement

*Break

*Continue

*Pass

Note:

Each type has links, so please press the link to learn deeply.

Share:

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me