Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Web Programming Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

1.

Lab Experiments-Java Script & HTML

Simple experiments
// Popup Window – onClick//

<!DOCTYPE html>
<title>My Example</title>

<input id="go" type="button" value="Open new window" onclick="window.open('/


javascript/examples/sample_popup.cfm','popUpWindow','height=500, width=400,
left=100, top=100, resizable=yes, scrollbars=yes, toolbar=yes, menubar=no,
location=no, directories=no, status=yes');">

// Alert Box - onClick//

<!DOCTYPE html>
<title>My Example</title>

<input type="button" value="Click me" onclick="alert('Thanks... I feel much better


now!');">

//Jump Menu with Conditional// 


<!DOCTYPE html>
<title>My Example</title>

<script>
// Wait for DOM to load
document.addEventListener("DOMContentLoaded", function(event) {

// Put the drop down into a variable


var e = document.getElementById("jumpmenu");

// Wait for user to select an option


e.addEventListener("change", function() {

// Put the selected value into a variable


selectedURL = this.options[this.options.selectedIndex].value;

// Check that the value is not null


if (this.value != "null") {

// Display the confirm box and put the response into a variable
varconfirmLeave = confirm("Are you sure?");

// If user clicked "OK"


if (confirmLeave==true) {

// Load the selected URL


document.location.href = selectedURL;
}
// If user clicked "Cancel"
else {
return false;
}
}
});

});
</script>

<!-- Replace '{action page}' with your own action page to support non-JavaScript
users -->
<form name="navForm" action="{action page}">
<select name="jumpmenu" id="jumpmenu">
<option>Jump to...</option>
<option value="http://www.zappyhost.com">ZappyHost</option>
<option value="http://www.html.am">HTML</option>
<option value="http://www.database.guide">Database Guide</option>
</select>
</form>

Program1

Write a JavaScript to design a simple calculator to perform the following


operations: sum, product, difference and quotient.
<html>
<head>
<title>My calculator</title>
<script type="text/javascript">
function call(click_id)
{
var v1=parseFloat(document.getElementById("ip1").value);
var v2=parseFloat(document.getElementById("ip2").value);

if(isNaN(v1) || isNaN(v2))
alert("enter a valid number");

else if(click_id=="add")
document.getElementById("output").value=v1+v2;

else if(click_id=="sub")
document.getElementById("output").value=v1-v2;

else if(click_id=="mul")
document.getElementById("output").value=v1*v2;

else if(click_id=="div")
document.getElementById("output").value=v1/v2;
}
</script>
</head>
<body>
<center>
<h1> A SIMPLE CALCULATOR PROGRAM</h1>
<table style="background-color:yellow" align=="center">
<tr>
<td>
<form method="get" action="">
<div width=50% align="center">
<label>OP1<input type="text" id="ip1"/></label>
<label>op2<input type="text" id="ip2"/></label>
<lablel>total<input type="text" id="output"/></label>
</div>
<br>
<div width=50% align="center">
<input type="button" value="+" id="add" onclick="call(this.id)"/
><input type="button" value="-" id="sub" onclick="call(this.id)"/
><input type="button" value="*" id="mul"
onclick="call(this.id)"/><input type="button" value="/" id="div"
onclick="call(this.id)"/><input type="reset" value="clear"/></
div>
</form>
</td>
</tr>
</table>
</center>
</body>
</html>

OUTPUT:-

Program 2:

Write a JavaScript that calculates the squares and cubes of the numbers from 0 to 10
and outputs HTML text that displays the resulting values in an HTML table format.

<html>
<head>
</head>
<body>
<table align="center" border=1><tr><td>number</
td><td>square</td><td>cube</td></tr><script type="text/
javascript"> for(var n=0; n<=10; n++)

{
document.write( "<tr><td>" + n + "</td><td>" + n*n + "</td><td>" + n*n*n
+ "</td></tr>" ) ;
}

</script>
</table>
</body>
</html>
OUTPUT:-

Program 3:

Write a JavaScript code that displays text “TEXT-GROWING” with increasing font
size in the interval of 100ms in RED COLOR, when the font size reaches 50pt it displays
“TEXT-SHRINKING” in BLUE color. Then the font size decreases to 5pt.<html>

<body>
<p id="demo"></p>
<script>
var var1 = setInterval(inTimer, 1000);
var size = 5;
var ids = document.getElementById("demo");
function inTimer() {
ids.innerHTML = 'TEXT GROWING';
ids.setAttribute('style', "font-size: " + size + "px; color: red");
size += 5;
if(size >= 50 ){
clearInterval(var1);
var2 = setInterval(deTimer, 1000);
}
}
function deTimer() {
size -= 5;
ids.innerHTML = 'TEXT SHRINKING';
ids.setAttribute('style', "font-size: " + size + "px; color: blue");
if(size == 5 ){
clearInterval(var2);
}
}
</script>
</body>
</html>
Output:-

Program 4:

Develop and demonstrate a HTML5 file that includes JavaScript script that uses
functions for the following problems:
a. Parameter: A string
b. Output: The position in the string of the left-most vowel
c. Parameter: A number
d. Output: The number with its digits in the reverse order
<html>
<body>
<script type="text/javascript">
var str = prompt("Enter the Input","");
if(isNaN(str))
{
str = str.toUpperCase();
for(var i = 0; i < str.length; i++) {
var chr = str.charAt(i);
if(chr == 'A' || chr == 'E' || chr == 'I' || chr == 'O' || chr == 'U')break;
}
if( i < str.length )
alert("The position of the left most vowel is "+
(i+1)); else
alert("No vowel found in the entered string");
}
else
{
var num,rev=0,remainder;
num = parseInt(str);
while(num!=0) {
remainder = num%10;
num = parseInt(num/10);
rev = rev * 10 + remainder;
}
alert("Reverse of "+str+" is "+rev);
}
</script>
</body>
</html>
Output:-
Program 5:
Create a script that asks the user for a name, then greets the user with "Hello" and the
user name on the page

Program
<html>
<head>
<script type="text/javascript">
let name = prompt("What is your name?");
alert("Hello, " + name + "!");
</script>
</head>
</html>
Output:
Program 6:
Develop and demonstrate a XHTML file that includes Javascript script for the
following problems:
a) Input: A number n obtained using prompt
Output: The first n Fibonacci numbers
b) Input: A number n obtained using prompt
Output: A table of numbers from 1 to n and their squares using alert

(a)
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml/">
<head><title>Fibonacci Series</title>
</head>
<body bgcolor="yellow">
<h3 style="text-align:center;color:red"> Program to generate first n fibonacci numbers </h3>
<script type="text/javascript">
var limit = prompt("Enter the number");
var f1=0;
var f2=1;
document.write("<h3>The limit entered is: </h3>",limit,"<br/>");
document.write("<h3>The fibonacci series is: </h3> <br/>");
if(limit == 1)
{
document.write("",f1,"<br/>");
}
if(limit == 2)
{
document.write("",f1,"<br/>");
document.write("",f2,"<br/>");
}
if(limit > 2)
{
document.write("",f1,"<br/>");
document.write("",f2,"<br/>");
for(i=2;i<limit;i++)
{
f3 = f2+f1;
document.write("",f3,"<br/>");
f1=f2;
f2=f3;
}
}
</script>
</body>
</html>
Output:

(b)
<?xml version ="1.0" encoding = "utf-8?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> square.html </title>
</head>
<body style="background-color:yellow">
<h3 style="text-align:center;color:red"> Program to generate a table
of numbers from 1 to n and their squares using alert</h3>
<script type="text/javascript" >
var n= prompt("Enter the limit 'n' to generate the table of numbers from 1 to n:","");
var msg = "";
var res = "0";
for(var x = 1; x <= n; x++)
{
res = x * x;
msg = msg + " "+ x + " * "+ x + " = " + res + "\n";
}
alert(msg);
</script>
</body>
</html>
Output:

Program 7:
Create a sample form program that collects the first name, last name, email, user id,
password and confirms password from the user. All the inputs are mandatory and email
address entered should be in correct format. Also, the values entered in the password
and confirm password textboxes should be the same. After validating using JavaScript,
In output display proper error messages in red color just next to the textbox where
there is an error.
Program:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
var divs = new Array();
divs[0] = "errFirst";
divs[1] = "errLast";
divs[2] = "errEmail";
divs[3] = "errUid";
divs[4] = "errPassword";
divs[5] = "errConfirm";
function validate()
{
var inputs = new Array();
inputs[0] = document.getElementById('first').value;
inputs[1] = document.getElementById('last').value;
inputs[2] = document.getElementById('email').value;
inputs[3] = document.getElementById('uid').value;
inputs[4] = document.getElementById('password').value;
inputs[5] = document.getElementById('confirm').value;
var errors = new Array();
errors[0] = "<span style='color:red'>Please enter your first name!</span>";
errors[1] = "<span style='color:red'>Please enter your last name!</span>";
errors[2] = "<span style='color:red'>Please enter your email!</span>";
errors[3] = "<span style='color:red'>Please enter your user id!</span>";
errors[4] = "<span style='color:red'>Please enter your password!</span>";
errors[5] = "<span style='color:red'>Please confirm your password!</span>";
for (i in inputs)
{
var errMessage = errors[i];
var div = divs[i];
if (inputs[i] == "")
document.getElementById(div).innerHTML = errMessage;
else if (i==2)
{
var atpos=inputs[i].indexOf("@");
var dotpos=inputs[i].lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=inputs[i].length)
document.getElementById('errEmail').innerHTML = "<span style='color: red'>Enter
a valid email address!</span>";
else
document.getElementById(div).innerHTML = "OK!";
}
else if (i==5)
{
var first = document.getElementById('password').value;
var second = document.getElementById('confirm').value;
if (second != first)
document.getElementById('errConfirm').innerHTML = "<span style='color:
red'>Your passwords don't match!</span>";
else
document.getElementById(div).innerHTML = "OK!";
}
else
document.getElementById(div).innerHTML = "OK!";
}
}
function finalValidate()
{
var count = 0;
for(i=0;i<6;i++)
{
var div = divs[i];
if(document.getElementById(div).innerHTML == "OK!")
count = count + 1;
}
if(count == 6)
document.getElementById("errFinal").innerHTML = "All the data you entered is
correct!!!";
}
</script>
</head>
<body>
<table id="table1">
<tr>
<td>First Name:</td>
<td><input type="text" id="first" onkeyup="validate();" /></td>
<td><div id="errFirst"></div></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="last" onkeyup="validate();"/></td>
<td><div id="errLast"></div></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" onkeyup="validate();"/></td>
<td><div id="errEmail"></div></td>
</tr>
<tr>
<td>User Id:</td>
<td><input type="text" id="uid" onkeyup="validate();"/></td>
<td><div id="errUid"></div></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="password" onkeyup="validate();"/></td>
<td><div id="errPassword"></div></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" id="confirm" onkeyup="validate();"/></td>
<td><div id="errConfirm"></div></td>
</tr>
<tr>
<td><input type="button" id="create" value="Create"
onclick="validate();finalValidate();"/></td>
<td><div id="errFinal"></div></td>
</tr>
</table>
</body>
</html>

Output:

Program 8:
Write a html program for Creation of web site with forms, frames, links, tables etc

Program

1. Create a HTML page named index.html under that using <frameset> tags which splits

a single page into rows and columns

2. Create three different HTML pages to display in each frame created.

3. 1st HTML page is created for banner which displays the IMAGE.

4. 2nd HTML Page is created for navigation of different HTML pages which is done

using LINK tags.

5. 3rd HTML Page is created is used to display the HTML files when each link in clicked

in the navigation page.

6. Created pages like

1. About.html

2. Department.html

3. Courses.html
4. Contact.html

Using TABLE tag, LINK tag, P tag.

7. Execute the Index.html Page using Internet Explorer

index.html

<html>

<head><title> :-) Welcomes u</title></head>

<frameset rows="227,*">

<frame name="top" src="top.html">

<frameset cols="150,*">

<frame name="left" src="nav.html">

<frame name="main" src="main.html">

<body>index</body>

</html>

nav.html

<html>

<head><title>nav</title></head>

<body>

<table border="0" width="70%">

<tr><td>Home</td></tr>

<tr><td><a href="D:\MMM\Website\about.html" target="main">About us</


a></td></tr>

<tr><td><a href="D:\MMM\Website\courses.html" target="main">Courses</


a></td></tr>
<tr><td><a href="D:\MMM\Website\department.html"
target="main">Departments</a></td></tr>

<tr><td>Gallery</td></tr>

<tr><td><a href="D:\MMM\Website\contact.html" target="main">Contact us</


a></td></tr>

</table>

<br/>

<br/>

<table border="0" width="70%">

<caption><strong>News & Events</strong></caption>

<tr><td></td></tr>

</table>

</body>

</html>

top.html

<html>

<head><title>top</title></head>

<body bgcolor="black">

<center><img src="D:\MMM\Website\banner.jpg" /></center></body>

</html>

about.html

<html>

<head><title>nav</title></head>

<body>
<p><strong>About Us</strong></p>

<br/>

<p style="font-size:14ft">

MMM College Example

</p>

<br/>

<br/>

<p>

EXAMPLE

</p>

</body>

</html>

contact.html

<html>

<head><title>nav</title></head>

<body>

<table border="0" width="70%">

<tr><td>

<strong> MMM College Example </strong>

<br/>

<br/>

CHENGALPATTU

Tamilnadu, India.

<br/>
Phone: + 91 - 44

Fax: + 91 - 44

Email: admission.mmmcollegeexample@gmail.com</td></tr>

</table>

</body>

</html>

department.html

<html>

<head><title>Departments</title></head>

<body>

<table border="0" width="70%">

<caption> <strong>Departments </strong></caption>

<thead>

</thead>

<tbody>

<tr>

<td>Computer Science and Engineering</td>

</tr>

<tr>

<td>Information Technology</td>

</tr>

<tr>

<td>Electronics and Communication Engineering</td>

</tr>
<tr>

<td>M Engineering</td>

</tr>

<tr>

<td>Civil Engineering</td>

</tr>

</tbody>

</table>

</body>

</html>

course.html

<html>

<head><title>Courses</title></head>

<body>

<table border="0" width="70%">

<caption> <strong>Courses Offered </strong></caption>

<thead>

<tr>

<th>S.no</th>

<th>Course</th>

</tr>

</thead>

<tbody>

<tr>
<td>1.</td>

<td>B.E. - Computer Science and Engineering</td>

</tr>

<tr>

<td>2.</td>

<td>B.E. - Information Technology</td>

</tr>

<tr>

<td>3</td>

<td>M.E. - Computer Science and Engineering</td>

</tr>

<tr>

<td>4</td>

<td>M.E. - Communication Systems</td>

</tr>

<tr>

<td>3</td>

<td>M.E. - Embedded systems and engineering</td>

</tr>

</tbody>

</table>

<br/>

<br/>

</body>

</html>

Output:
2. Lab Experiments-Python

Program 1:
Sendingsimple Email using SMTP
#!/usr/bin/python

importsmtplib

sender='from@fromdomain.com'
receivers=['to@todomain.com']

message="""From: From Person <from@fromdomain.com>


To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.


"""

try:
smtpObj=smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print"Successfully sent email"
exceptSMTPException:
print"Error: unable to send email"

Program 2:
Sending an HTML Email using Python//
#!/usr/bin/python

importsmtplib

message="""From: From Person <from@fromdomain.com>


To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>


<h1>This is headline.</h1>
"""

try:
smtpObj=smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print"Successfully sent email"
exceptSMTPException:
print"Error: unable to send email"

Program 3:
Simple SERVER and CLIENT Program
//Simple Server //
#!/usr/bin/python # This is server.py file

import socket # Import socket module

s =socket.socket()# Create a socket object


host=socket.gethostname()# Get local machine name
port=12345# Reserve a port for your service.
s.bind((host, port))# Bind to the port

s.listen(5)# Now wait for client connection.


whileTrue:
c,addr=s.accept()# Establish connection with client.
print'Got connection from',addr
c.send('Thank you for connecting')
c.close()# Close the connection

//Simple CLIENT //
#!/usr/bin/python # This is client.py file

import socket # Import socket module

s =socket.socket()# Create a socket object


host=socket.gethostname()# Get local machine name
port=12345# Reserve a port for your service.
s.connect((host, port))
prints.recv(1024)
s.close()# Close the socket when done

Now run this server.py in background and then run above client.py to see the result.
# Following would start a server in background.
$ python server.py &

# Once server is started run client as follows:


$ python client.py
This would produce following result −
Got connection from ('127.0.0.1', 48437)
Thank you for connecting

Program 4:
Python program for Multithreading

#!/usr/bin/python

import thread
import time

# Define a function for the thread


defprint_time(threadName, delay):
count=0
while count <5:
time.sleep(delay)
count+=1
print"%s: %s"%(threadName,time.ctime(time.time()))

# Create two threads as follows


try:
thread.start_new_thread(print_time,("Thread-1",2,))
thread.start_new_thread(print_time,("Thread-2",4,))
except:
print"Error: unable to start thread"

while1:
pass
When the above code is executed, it produces the following result −
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Program 5:
To write a Python program to find the most frequent words in a text read from a file.
def main():
filename=raw_input("enter the file").strip()
infile=open(filename,"r")
wordcounts={}
for line in infile:
processLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())
items=[[x,y] for (y,x) in pairs]
items.sort()
for i in range(len(items)-1,len(items)-11,-1):
print(items[i][1]+"\t"+str(items[i][0]))
def processLine(line,wordcounts):
line=replacePunctuations(line)
words=line.split()
for word in words:
if word in wordcounts:
wordcounts[word]+=1
else:
wordcounts[word]=1
def replacePunctuations(line):
for ch in line:
if ch in "~@#$%^&*()_-+=<>?/.,:;!{}[]''":
line=line.replace(ch," ")
return line
main()

Output:
Enter a filename:a.txt
Hi 1
How 1
Are 1
You 1
Program 6:
Write a program to implement

import turtle
c=["red","green","blue"]
i=0
turtle.pensize(10)
for angle in range(0,360,30):
if i>2:
i=0
turtle.color(c[i])
turtle.seth(angle)
turtle.circle(60)
i=i+1

Program 7:
Write a GUI for an Expression Calculator using Tkinter
import turtle
turtle.pensize(2)
for i in range(36):
for j in range(4):
turtle.forward(70)
turtle.left(90)
turtle.left(10)

from Tkinter import *


from math import *
root=Tk()
root.title("Calculator")
root.geometry("210x200")
e=Entry(root,bd=8,width=30)
e.grid(row=0,column=1,columnspan=5)
def setText(txt):
l=len(e.get())
e.insert(l,txt)
def clear1():
txt=e.get()
e.delete(0,END)
e.insert(0,txt[:-1])
def clear():
e.delete(0,END)
def sqroot():
txt=sqrt(float(e.get()))
e.delete(0,END)
e.insert(0,txt)
def negation():
txt=e.get()
if txt[0]=="-":
e.delete(0,END)
e.insert(0,txt[1:])
elif txt[0]=="+":
e.delete(0,END)
e.insert(0,"-"+txt[1:])
else:
e.insert(0,"-")

def equals():
try:
s=e.get()
for i in range(0,len(s)):
if s[i]=="+" or s[i]=="-" or s[i]=="*" or s[i]=="/" or s[i]=="%":
expr=str(float(s[:i]))+s[i:]
break
elif s[i]==".":
expr=s
break
e.delete(0,END)
e.insert(0,eval(expr))
except Exception:
e.delete(0,END)
e.insert(0,"INVALID EXPRESSION")

back1=Button(root,text="<--",command=lambda:clear1(),width=10)
back1.grid(row=1,column=1,columnspan=2)
sqr=Button(root,text=u'\u221A',command=lambda:sqroot(),width=4)
sqr.grid(row=1,column=5)
can=Button(root,text="C",command=lambda:clear(),width=4)
can.grid(row=1,column=3)
neg=Button(root,text="+/-",command=lambda:negation(),width=4)
neg.grid(row=1,column=4)
nine=Button(root,text="9",command=lambda:setText("9"),width=4)
nine.grid(row=2,column=1)
eight=Button(root,text="8",command=lambda:setText("8"),width=4)
eight.grid(row=2,column=2)
seven=Button(root,text="7",command=lambda:setText("7"),width=4)
seven.grid(row=2,column=3)
six=Button(root,text="6",command=lambda:setText("6"),width=4)
six.grid(row=3,column=1)
five=Button(root,text="5",command=lambda:setText("5"),width=4)
five.grid(row=3,column=2)
four=Button(root,text="4",command=lambda:setText("4"),width=4)
four.grid(row=3,column=3)
three=Button(root,text="3",command=lambda:setText("3"),width=4)
three.grid(row=4,column=1)
two=Button(root,text="2",command=lambda:setText("2"),width=4)
two.grid(row=4,column=2)
one=Button(root,text="1",command=lambda:setText("1"),width=4)
one.grid(row=4,column=3)

zero=Button(root,text="0",command=lambda:setText("0"),width=10)
zero.grid(row=5,column=1,columnspan=2)
dot=Button(root,text=".",command=lambda:setText("."),width=4)
dot.grid(row=5,column=3)
div=Button(root,text="/",command=lambda:setText("/"),width=4)
div.grid(row=2,column=4)
mul=Button(root,text="*",command=lambda:setText("*"),width=4)
mul.grid(row=3,column=4)
minus=Button(root,text="-",command=lambda:setText("-"),width=4)
minus.grid(row=4,column=4)
plus=Button(root,text="+",command=lambda:setText("+"),width=4)
plus.grid(row=5,column=4)
mod=Button(root,text="%",command=lambda:setText("%"),width=4)
mod.grid(row=2,column=5)
byx=Button(root,text="1/x",command=lambda:setText("%"),width=4)
byx.grid(row=3,column=5)
equal=Button(root,text="=",command=lambda:equals(),width=4,height=3)
equal.grid(row=4,column=5,rowspan=2)
root.mainloop()
Output:

Program 8:
To write a Python program to bouncing ball in Pygame.
import pygame
import random

# Define some colors


BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
BALL_SIZE = 25

class Ball:
"""
Class to keep track of a ball's location and vector.
"""
def __init__(self):
self.x = 0
self.y = 0
self.change_x = 0
self.change_y = 0

def make_ball():
"""
Function to make a new, random ball.
"""
ball = Ball()
# Starting position of the ball.
# Take into account the ball size so we don't spawn on the edge.
ball.x = random.randrange(BALL_SIZE, SCREEN_WIDTH - BALL_SIZE)
ball.y = random.randrange(BALL_SIZE, SCREEN_HEIGHT - BALL_SIZE)

# Speed and direction of rectangle


ball.change_x = random.randrange(-2, 3)
ball.change_y = random.randrange(-2, 3)

return ball

def main():
"""
This is our main program.
"""
pygame.init()

# Set the height and width of the screen


size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bouncing Balls")

# Loop until the user clicks the close button.


done = False

# Used to manage how fast the screen updates


clock = pygame.time.Clock()

ball_list = []

ball = make_ball()
ball_list.append(ball)

# -------- Main Program Loop -----------


while not done:
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
# Space bar! Spawn a new ball.
if event.key == pygame.K_SPACE:
ball = make_ball()
ball_list.append(ball)

# --- Logic
for ball in ball_list:
# Move the ball's center
ball.x += ball.change_x
ball.y += ball.change_y

# Bounce the ball if needed


if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE:
ball.change_y *= -1
if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x < BALL_SIZE:
ball.change_x *= -1

# --- Drawing
# Set the screen background
screen.fill(BLACK)

# Draw the balls


for ball in ball_list:
pygame.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE)

# --- Wrap-up
# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.


pygame.display.flip()

# Close everything down


pygame.quit()

if __name__ == "__main__":
main()
Output:
Program 9:
To write a Python program to simulate elliptical orbits in Pygame.
import pygame
import math
import sys

pygame.init()

screen = pygame.display.set_mode((600, 300))


pygame.display.set_caption("Elliptical orbit")

clock = pygame.time.Clock()

while(True):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()

xRadius = 250
yRadius = 100

for degree in range(0,360,10):


x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)

pygame.display.flip()
clock.tick(5)
Output:

Program 10:
Write a python program to get input using Tkinter Textbox

from Tkinter import *


window = Tk()

window.title("Welcome to LikeGeeks app")


window.geometry('350x200')

lbl = Label(window, text="Hello")

lbl.grid(column=0, row=0)

txt = Entry(window,width=10)

txt.grid(column=1, row=0)

def clicked():

lbl.configure(text="Button was clicked !!")

btn = Button(window, text="Click Me", command=clicked)

btn.grid(column=2, row=0)

window.mainloop()

Output:

Program 11:
Write a Python program to add radio buttons in the widget.

from Tkinter import *

window = Tk()

window.title("Welcome to LikeGeeks app")

window.geometry('350x200')

rad1 = Radiobutton(window,text='First', value=1)

rad2 = Radiobutton(window,text='Second', value=2)

rad3 = Radiobutton(window,text='Third', value=3)

rad1.grid(column=0, row=0)

rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)

window.mainloop()

Output:

You might also like