Python for beginners- Dictionary Operations

 Dictionary is one of the type of collections in python. It combines variety of data items under a common name.

Syntax be like,

 Name={

              "Membername1":"Value",

              "Membername2":"Value",

               ........................................

              "Membernamen":"Value"

             }

An example is given below...

Eg:

Creating a dictionary named "sunglass"

 sunglass = {

                      "brand": "Suntrack"

                      "model": "Wideangle"

                      "Year " : "2023"

                     }

To print the dictionary, use the below code.

print(sunglass)

It displays the output as follows.

{'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}

The operations on the dictionary are

  • get()
          This method is used to get a value from dictionary. For getting a value from above example, the              following code is used.
          print(sunglass.get("model")) -This displays Wideangle          
  • keys()
          keys are the members in the dictionary. This method is useful to get the keys in the dictionary.

           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.keys()
         
           When you execute this, you will get the below output.
            dict_keys(['brand','model','Year'])     
  • values()
           These are the data assigned to the keys. To get the values assigned for the keys, use the below                 code.
           sunglass = {"brand": "Suntrack", "model": "Wideangle", "Year ": "2023"}
           sunglass.values()
           The output is
                 dict_values(['Suntrack','Wideangle','2023'])    
  • copy()
           This method is used to copy a value to another variable. For eg,
            sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
            a=sunglass.copy()
            print(a)
           when you run this code, you get the copied value.
            {'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}
  • pop()
          This method is used to extract a value from the dictionary.
           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.pop("Year")
           It gives you the year value as output.
           '2023'
  • clear()

             Do you want to empty the dictionary, use this method.

              sunglass = {"brand":"Suntrack","model": "Wideangle","Year ": "2023"}

              sunglass.clear()
              print(sunglass)

              It clears all the data in the sunglass dictionary. The output is {}

         These are operations performed for Dictionary.


 

How to add a value, remove a value and emptying a list???

 List has many operations to perform. The basic operations like creating a list, changing a value, displaying a list, searching an element in a list and finding length of a variable is explained in part 1.

https://www.blogger.com/blog/post/edit/5251857942821229/7649420483850529537

In part 2, the remaining operations are listed below.

  • Adding a value
  • Removing a value
  • Empty a list
  • Usage of constructor
 The operations are explained below.

  =>Adding a value:  

            This can be achieved by two ways. First one is adding a value in the end of the list. Second one  deals with adding in a specified index.

    Method1:Adding a value in the end of the list:

    colorlist=["Red", "Green", "Yellow" ]
    colorlist.append( "Orange")
    print(colorlist)

    While executing this code, you get the following output.
    [ 'Red', 'Green', 'Yellow', 'Orange' ]

    Method2: Adding an item at a specified index:

    colorlist=["Red", "Green", "Yellow" ]
    colorlist.insert( 1,"Orange")
    print(colorlist)

    The output is
     [ 'Red', 'Orange', 'Green', 'Yellow' ]   

=>Removing a value:

      When you want to delete an item, there are two method.Either ,you can delete the last item or you           can delete a specified item.

      Method1 : Remove last item:
       
      colorlist=["Red", "Green", "Yellow" ]
      colorlist.pop()
     
       It displays the output as : ['Yellow']

      Method2 : Remove a item by specified value:

      colorlist= ["Red" ,"Yellow", "Green"]
      colorlist.remove("Yellow")
      print(colorlist)

      The output is : ['Red' ,' Green' ]
       
       Method3: Remove a item by index value:

       colorlist= ["Red" ,"Yellow", "Green"]
       del colorlist[0]

       it displays [ 'Yellow', 'Green' ]    

  => Empty a list:

        When you want to clear the data in the list, use the following code.

       colorlist = ["Red", "Yellow", "Green"]
       colorlist.clear()
       print(colorlist)
 
       It clears all data in the list and prints [].

 => Usage of constructor:

        Constructor is a simple method to initialize an object. 

         colorlist= list(("Red","Green", "Yellow" ))
         print(colorlist)
     
         The output is   ['Red' ,'Green', 'Yellow']

These are second level of list operations in python.

How to create a list and its operations???

Python collections

    Collection is a set of elements stored in a sequence. In python, there are 4 types of collections.

They are

  • List
  • Tuple
  • Set
  • Dictionary

In the above collections, list has variety of operations to do.

Lists

 List is a collection in python. It can store any type of data. It has variety of operations to perform like creating, displaying, access, add, delete, search and so on.

1.Creating a list

 This is the way of creating a new list in python. Colorlist is the list name. Red,Green,Yellow are the values. 

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist)

 When you execute this code, you get the following output.

['Red', 'Green' ,'Yellow']

2.Access the list items

  After creating the list, you can access the items. Here,it displays the data in first position. list is always starts from index 0.

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist[1])

 The output is:

  Green

3.Change the value:

If want to change a particular value in the list, you can assign it with another value. Here, is the code...

colorlist=[“Red”,”Green”,”Yellow”]

colorlist[2]=”Blue”

print(colorlist)

while you execute this code, you can get the following output.

['Red', 'Green', 'Blue']

4.Search an item in the list:

 If you want to find an item in the list, use the below code.

colorlist=[“Red”, “Green”, ”Yellow”]

if “Red” in colorlist:

   print(“ Yes, ‘Red’ is in the colorslist”)

 output is:

 Yes, ‘Red’ is in the colorslist

5.Finding length of the list

To find the length of the list,  use the code given.

colorlist=[“Red”, “Green”, ”Yellow”]

print(len(colorlist))

The output is given below.

3

These are the basic operations performed in the list.


Python program for beginners - String operations.

 String is a collection of characters. It is stored in sequence as an array. Normally a string in python is assigned a value by the following syntax.

Syntax:

String_Variable= " String value "

Eg:

a= " Best wishes"

where, a is a variable that represents string. "Best wishes" is the value assigned to string.

Next, a simple python program to display this string is given below.

a="Best wishes"

print(a)

The Program and its output are like this.


The operations on a string variable are listed here.
  • Extracting a character or set of characters.
  • Finding the total number of characters (Length) in a string
  • Converting upper case to Lowercase and vice versa.
  • Adding two strings
  • Replacing characters
  • Splitting the string into sub string
  • White space removing
The sample code is given as below.
  • Extracting a character or set of characters.
          a="Best Wishes"
          print (a[5:11])
         
          It extracts "Wishes" from String a and displays it on the screen.
  • Finding the total number of characters (Length) in a string
          a="Best Wishes"
          print(Len(a))

         This code gives the output as 11.
  • Converting upper case to Lowercase and vice versa.
          a="best wishes"
          print (a.upper())
          This gives the uppercase of the string a. That will be "BEST WISHES".

          b="WELCOME"
          print (b.lower())

          output is "welcome".
  • Adding two strings
         a="Hi"
         b="Hello"
         print(a+b)

         It gives you  "HiHello" as output.
  • Replacing characters
          a="Good"
          print(a.replace("G","F"))

          This code replaces the "G" to "F". Hence the output is "FOOD"
  • Splitting the string into sub string
          a="Best wishes"
          b=a.split(" ")
          print (b)
    
         split function splits the string based on the white space in the string here. 
         The space is between Best and wishes. So, the output is [ 'Best'  'wishes'] 
  • White space removing
          a=" Welcome "
          print(a.strip())

          This code removes the white space in the beginning and the end. Here, the output is " Welcome".

 These are the basic string operations in python.





Python program to generate fibonacci series

 Maths has some wonderful sequences of numbers. one among that is Fibonacci series.

The logic behind Fibonacci series is very simple. It starts with two numbers 0,1 as the first and second elements. the next number is the sum of the previous two numbers. Likewise ,it goes on until it reaches the number of the elements in the series.

In python, it has following steps.

  • This Fibonacci series program starts with getting the number of elements for the series. 
  • Next, it assigns the values to the first two numbers. 
  • It checks the number of elements is less than zero. If yes means, the number is a negative value. So, it prints a message that enter a positive number.
  • Else if the number of elements is equal to 1, it print the the first number alone.
  • Else, it starts a loop. It prints the first value.
  • It adds the previous two numbers and store it into third variable.
  • It exchanges the value of  second variable to first variable and  the value of third variable to second variable.
  • The Loop repeats until n value is zero.

The program is given below.

"Fibonacci.py"

#Python program to generate fibonacci series

#Getting the number of elements for fibonacci series

n=int(input("enter the number of elements:"))

#Assigning values to start fibonacci series x to 0 and y to 1

x,y=0,1

#Check whether the given number is less than zero

if n<=0:

 print("Enter a positive number")

#Check whether the given number is equal to one

elif n==1:

 print("fibonacci sequence  is",n)

 print(x)

else:

 print("The Fibonacci sequence is:")

 for i in range(n):

  print(x)

  z=x+y

  x=y;

  y=z;


Execute this program in any command prompt. You will  get the following output.

This is the simple python program to generate fibonacci series.

Java Script program to display current date and time using HTML.

 Date and time are the important factors for real time applications. JavaScript includes inbuilt class to get the date and time.

date() is the inbuilt class. 

This inbuilt class has many functions listed below.

 getDate() - it provides the date as number(1-31)

 getMonth() - it displays the month as number

getFullYear() - it gives the year in four digit number

getDay() - it shows the day of the week in number(0-6)

getHour() - it displays the hour information(0-23)

getMinutes()- it gives the minutes details( 0-59)

getSeconds() -it provides  the seconds details (0-59)

getMilliseconds() -it finds the milliseconds details and gives the information( 0-999)

getTime()- it shows the time.

these are the inbuilt functions available in date().


Next, create a file in notepad ,save it as "DateDisplay.html" .

The program is given below.

The <head> tag  is used to set the heading as "Display current date and time" with <h1> tag.

where <head> tag is for heading

<h1> tag is for heading style1 with  red color 

<body bgcolor="yellow"> - it sets the background color as yellow.


"Datedisplay.html"

<html> 

<head> <h1 style="color:red;"> Display current date and time </head>

<body bgcolor="Yellow"

<br>

< !-- This set the heading style as 2 with text color as blue -->

<h2 style="color:blue;"> <marquee> Current date and time is:</marquee>

<br>

<!-- Scripting code  -->

<script> function display()

{

 var a="You have clicked"; 

<!-- creating object for Date() -->

var date=new Date(); 

<!-- using date.getData() ,date1 retrieve the value of current date -->

var date1=date.getDate();

<!--  using date.getMonth(),month1 is assigned with current month value-->

 var month1=date.getMonth();

<!-- month value is always 0 to 11 as default. so we increase one by getting exact month --> 

 month1++

<!-- year1 is assigned the current year value -->

var year1=date.getFullYear(); 

<!-- This executes when the button is presses -->

document.getElementById("dis").value=date+"/"+month1+"/"+year1;

 } 

</script> 

<form> 

<!-- This creates a text box and a button -->

<input type="text" id="dis" /><br /> 

<input type="button" value="Display Date" onclick="display()" /> 

</form> 

<body> </html> 

Once you completed it, just open a browser and type the URL of the file and click it.

It shows the output.


This is a simple html program with java script to display current date and time.  Try do it some more programs using the above inbuilt functions.





 

how to create About us and enquiry page using HTML coding???

 when user wants to know about the author’s details and enquire about the recipes, the following codes are used.

About us page:

This page contains basic information about foodie website. The html code for about us page is given below.

“Aboutus.html”

<html>

<head> <title> Foodie </title></head>

<style>

p {

color: navy;

text-indent: 30px;

}

</style>

<body bgcolor="lightgreen">

<h1> Foodie </h1>

     <p> Foodie is a great collection of mouth watering receipes. It has variety of receipes in different categories. South special,North Indian combo,Continental menus and Italy receipes </p>

</body>

</html>

the about us page is like as follows


Next,enquiry page code is given below.

 

Enquiry page

            When someone wants to find some recipes or doubts in the recipes, this enquiry form helps to find the solution. User enters the name, contact mail id and queries. The coding is given below.

“Enquiry.html”

<html>

<head><title> Foodie </title></head>

<body bgcolor=”yellow”>

<form action="output.html" method="get">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>
  <label for="mailid">Mail id:</label>
 <input type=”text” id=”mailid” name=”mailid”><br><br>

 <label for="Query"> Query:</label>

 <input type=”text” id=”query” name=”Query”><br><br>
  <input type="submit" value="Submit">
</form>

</body>

</html>

when you execute this code, you will get a window like below…


 These are simple design of about us and enquiry page. 

how to create a simple,elegant food receipe website????

 Food… Its one of the basic needs of our life. without food,we cant live. If you know cooking, then its fine. We design a food receipe website with following features.

Here, a food receipe website. let us name it as “foodie”. It has Home page, about us,enquiry form and receipes page.

Home page displays the title, logo and categories along with a welcome message.About us page displays the details of the website owning authority.

Receipes page has many categories. They are divided into 4 types as follows…

  • ·       South special
  • ·       North Indian combo
  • ·       Continental menus
  • ·       Italy receipes

At last, enquiry form is used to collect the user queries.

Steps to follow:

  1. ·       Create a folder and name it as “foodie”.
  2. ·       Create a two logos. one for the top and another one for the welcoming page.
  3. ·       Now, create a file “home.html” which divides the webpage into three parts. first part is “top.html”. it displays the logo and title with menu’s like home, About us and enquiry.
  4. ·       Left part of the web page includes the receipe categories.
  5. ·       Right part of the web page includes the welcoming message.  

Html coding is given below.

“home.html”

<frameset rows="30%,*"> 

<frame src="top.html" noresize scrolling="NO" name="topframe"> 

<frameset cols="15%,*"> 

<frame src="left.html" noresize scrolling="NO" name="leftframe"> 

<frame src="right.html" noresize name="rightframe" scrolling="auto">  </frameset> 

</frameset>

 

“top.html”

<html> 

  <head> 

      <title>Top Frame</title> 

  </head> 

 <body bgcolor="Skyblue "> 

      <img src="foodie.jpg" width="125" height="115" align="left"> 

      <marquee bgcolor="yellow" width="650" behavior="alternate"> 

    <font face="Brush Script MT" size="8" color="green"><b><i>Foodie- Receipes encyclopedia</i></b>  

         </font>

     </marquee> <br>

<font face="Brush Script" size="4" color="white"><b>Created & Maintained By

rajeeva84@blogspot.com</b></font> 

   </center>

<br> 

<table width="100%" height="50%" cellspacing=10> 

<tr align="center"> 

 <td>  <a href="Home.html" target="_parent"><font face="Brush Script" size="6" color="navy">HOME </a> </td>

 <td> <a href="Aboutus.html" target="rightframe"> <font face="Brush Script" size="6" color="navy">ABOUT US</a> </td>

 <td> <a href="Enquiry.html" target="rightframe"> <font face="Brush Script" size="6" color="navy">ENQUIRY</a>

</td> 

    </tr>

   </table>

  </body>

 </html>

 

“Left.html”

<html> 

   <body align="center" bgcolor="bisque"> <br> 

      <a href="SouthSpecial.html" target="rightframe"><font size="6">Southindian Specials</font></a><br><br> 

      <a href="Northindiancombo.html" target="rightframe"><font size="6">Northindian Combo</font></a><br><br> 

      <a href="Continentalmenu.html" target="rightframe"><font size="6">Continental Menu</font></a><br><br> 

      <a href="Italyreceipes.html" target="rightframe"><font size="6">Italy Receipes</font></a><br> 

    </body> 

</html>

 

“Right.html”

<html>

   <body bgcolor="yellow">

     <center>

       <img src="Healthy food.jpg" height="170"><br> 

        <font face="Brush Script MT" size="5" color="blue">

          <h1><b>Welcome to foodie!!!</b></font><br /> 

        <font face="Brush Script MT" size="5" color="red">

          <h2><b> "A Huge Collection Of receipes of delicious foods"</b></h2></font>

     </center> 

   </body>  

</html>

 

The output is


Image: Output for foodie 
This is a simple,elegant website for a food receipe .

How to create Login form using HTML?

Login is mandatory for any websites nowadays. Here, a login form is designed to get the input from the user. The user has to enter the login id and password.

 Html program to create a login form:

Simply open an editor like notepad. create a new file and save it as "loginform.html". Type the below coding.

<!DOCTYPE html>  

<html>  

<head> 

<meta name=” Description" content="HTML programs">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title> It’s Login page </title> 

<style>  

<!-- This block defines the style properties  -->

Body { 

<!-- This defines the font family and sets the background as cyan -->

  font-family: Times New Roman, Arial, sans-serif; 

  background-color: cyan; 

} 

<!-- This block defines the properties for the button -->

button {  

       background-color: #4CAF50;  

       width: 10%; 

        color: white;  

        padding: 10px;  

        margin: 10px 0px;  

               }  

<!--  this below code defines the border of the form -->

 form {  

        border: 4px solid #ff1111;  

    }  

<!-- This block sets the text box properties-->

 input[type=text], input[type=password] {  

        width: 100%;  

        margin: 8px 0; 

        padding: 12px 20px;  

        border: 2px solid green;  

        box-sizing: border-box;  

    } 

 </style>  

</head>   


<body>   

    <center> <h1> Login Form </h1> </center>  

    <form> 

        <div class="container">  

            <label>Username : </label>  

            <input type="text" placeholder="Enter Username" name="username" required> 

            <label>Password : </label>   

            <input type="password" placeholder="Enter Password" name="password" required> 

            <button type="submit">Login</button>  

            <input type="checkbox" checked="checked"> Remember me  

            <button type="button" class="cancelbtn"> Cancel</button>  

             <a href="#"> Forgot password? </a>  

        </div>  

    </form>    

</body>    

</html> 

 

Here, 

<meta name=” Description" content="HTML programs">

This meta tag is used to describe about the page.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

This  tag is used to set the viewport. This makes the web page to display good in all types of devices.


The output is shown below...


This is simple login form using HTML .

Java script – conditional statement

Java script has many conditional statements. It is used to check whether the given condition is true or false.

It has following type.

  • ·       If
  • ·       If else
  • ·       If else if

Each one is explained as follows.

1.    If statement:

This is a simple condition checking statement. It has a syntax to follow.

Syntax:

If (condition)

{

Code….

}

 Example:

  if( a>10)

   {

        document.writeln(“The number is greater than 10”);

   }

This example checks the given number is greater than 10. If the condition is true,it prints the number is greater than 10.

Next, a simple example which checks the given number is greater than 10 or not is shown below.

2.    if  else:

This type of conditional statement is used to check the condition. if the condition is true,it goes to the if block. otherwise, the control is transferred to else block.

Syntax:

if (condition)

{

Code….

}

else

{

Code….

}

 

Example:

if(a>10)

{

  document.write(“the number is greater than 10”);

}

else

{

 document.write(“The number is less than 10”);

}

 

3.    if else if:

This is the third type of conditional statement. It is used to check many conditions.

Syntax:

if (condition)

{

Code….

}

else if( condition)

{

Code….

}

else

{

Code…

}

Example:

if( a >10)

{

  document.write(“the number is greater than 10”);

}

else if (a == 0)

{

 document.write(“The number is equal to 10”);

}

else

{

 document.write(“The number is less than 10”);

}

These are the three different ways of conditional statement in java script.