Q.
1 Write a Python program that prints (displays) your name, address, and telephone
number.
Q.2 Let x=8 and y=2 Write the values of the following expressions:
a. x + y * 3
b. (x + y) * 3
c. x ** y
d. x % y
e. x / 12.0
f. x // 6
Q.3 WAP to print the number is positive or negative.
Q.4 WAP to print the number is even or odd.
Q. 5 WAP to print the number is leap year or non-leap year.
Q.6 WAP to calculate the swap two values using third variable or without using third
variable. And using comma operator.
Q. 7 WAP to display the Quotient and Remainder.
Q.8 WAP to convert KM TO CM.
Q.9 WAP to print the largest of the three numbers.
Q.10 Python Program to find the area of Triangle.
Q.11 Python Program to convert temperature in Celsius to Fahrenheit.
Q.12 The calculation of salary based on hours worked is,
Hours worked = 8, payment = 1500.
Hours worked < 8, pay less, 75 per hour.
Hours worked > 8, pay more, 75 per hour.
Q.13 '''Calculate the Gross Salary of an employee for following allowance &
deduction.
Get Basic Salary of Employee,
DA = 25% of Basic,
HRA = 15% of Basic,
PF = 12% of Basic,
TA = 7.50% of Basic.
Net Pay = Basic + DA + HRA + TA
Gross Pay = Net Pay - PF.
Q.14 WAP to using calculation program Arithmetic operators program.
Q.15 I want to make a piece of code that converts from a numerical grade (35
-100) to a letter grade (A, B, C, D, F).
Q.16 WAP to find which one is smallest given the three variable.
Q.17 Python program to check whether the entered character is vowel or consonant.
Q.18 Python Program to Add four Numbers.
Q.19 Write a program that takes the radius of a sphere (a floating-point number) as
input and then outputs the sphere’s diameter, circumference, surface area, and volume.
Solution---
import math
def calculate_sphere_properties(radius):
# Calculating Diameter
diameter = 2 * radius
# Calculating Circumference
circumference = 2 * [Link] * radius
# Calculating Surface area
surface_area = 4 * [Link] * (radius ** 2)
# Calculating Volume
volume = (4/3) * [Link] * (radius ** 3)
return diameter, circumference, surface_area, volume
# Prompt the user for the radius
radius = float(input("Enter the radius of the sphere: "))
# Calculate the sphere properties
diameter, circumference, surface_area, volume = calculate_sphere_properties(radius)
# Output the results
print("Diameter:", diameter)
print("Circumference:", circumference)
print("Surface Area:", surface_area)
print("Volume:", volume)
Q.20 write a program to check the person is eligible for voting or not.
Q.21 write a program to check the number is divisible by 7 or not.
Q.22 Write a program to display the “hello” if a number entered by user is a multiple of
five , otherwise print “bye”.
Q.23 write a program to calculate the electricity bill(accept number of unit from user)
according to the following criteria.
Unit price
First 100 units no charge
Next 100 units Rs 5 per unit
After 100 units Rs 10 per unit
If input unit is 350 than total bill amount is Rs 2000
Q.24 write a program to display the last digit of a number.
Q.25 write a program to accept the cost price of a bike and display the road tax to be
paid according to the following criteria.
Cost price Tax
>100000 15%
>50000 and <=100000 10 %
<=50000 5%
Q.26 write a program to accept a number from 1 to 7 and display the name of the day
like 1for Sunday ,2 for Monday and so on.
Q.27 write a program to accept a number from 1 to 12 and display name of the month
and days in that month like 1for January and so on.
Q. 28 Accept any city from the user and display monument of that city.
City monument
Delhi Red fort
Agra Taj mahal
Jaipur Taj mahal
Q.29 write the output of the if a=10.
Q.30 Write a program to check the person is senior citizen or not.
Q.31 write a program to whether a number is divisible by 2 and 3 both.
Q.32 Accept the age of 4 people and display oldest one.
Q.33 Accept the following from the user and calculate the percentage of class attended
Total no. of working days
Total no. of days for absent
After calculating percentage show that if the percentage is less than 75 than student
will not be able to sit in exam.
Q.34 A company decided to give bonus to employee according to following criteria
Time period of service Bonus
More than 10 year 10 %
>=6 and <=10 8%
Less than 6 year 5%
Ask user for their salary and years of service and print net bonus amount.
[Link] First 10 natural numbers using while loop.
36. Write a program to print the following number pattern using a loop.
1
12
123
1234
1 2 3 4 5
37. Calculate the sum of all numbers from 1 to a given number.
38. Write a program to print multiplication table of a given number.
39. Count the total number of digits in a number.
40. Print list in reverse order using a loop.
[Link] numbers from -10 to -1 using for loop.
[Link] to find area of a circle using function use single return value
function with pi=3.14
def areaOfCircle(r):
[Link] to write sum different product and using arguments with
return value .
[Link] the following number pattern using Python range() and a loop.
1
22
333
[Link] range starting from 20 to 10.
46. Generate integers multiply by 7.
47. Negative range from -10 to -20.
48. print series Combination of negative and positive numbers.
[Link] the first 10 numbers on each line 5 times.
50. # call function with 3 arguments
func1(20, 40, 60)
# call function with 2 arguments
func1(80, 100)
51. Return multiple values from a function.
[Link] # [Link] - Draws a square spiral
import turtle
t = [Link]()
for x in range(120):
[Link](x)
[Link](90)
#Draw circle spiral
import turtle
t = [Link]()
for x in range(100):
[Link](x)
[Link](91)
[Link] the first 10 numbers on each line 5 times.
[Link] to display all the elements before number 88 using break .
[Link] a clock using python.
from tkinter import *
from [Link] import *
from time import strftime
root = Tk()
[Link]("Clock")
def time():
string = strftime('%H:%M:%S %p')
[Link]fig(text=string)
[Link](1000, time)
label = Label(root, font=("ds-digital", 150), background = "black", foreground = "red")
[Link](anchor='center')
time()
mainloop()
56.'''Calculate the Gross Salary of an employee for following allowance &
deduction.
Get Basic Salary of Employee, using function.
DA = 25% of Basic,
HRA = 15% of Basic,
PF = 12% of Basic,
TA = 7.50% of Basic.
Net Pay = Basic + DA + HRA + TA
Gross Pay = Net Pay - PF.
'''
57. Prints all letters except 'e' and 's'.
58. program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
59.#merry Christmas design page in python.
from turtle import *
from random import randint
def create_rectangle(turtle, color, x, y, width, height):
[Link]()
[Link](color)
turtle.fillcolor(color)
[Link](x, y)
[Link]()
turtle.begin_fill()
[Link](width)
[Link](90)
[Link](height)
[Link](90)
[Link](width)
[Link](90)
[Link](height)
[Link](90)
# fill the above shape
turtle.end_fill()
# Reset the orientation of the turtle
[Link] heading(0)
def create_circle(turtle, x, y, radius, color):
[Link]()
[Link](color)
oogway.fillcolor(color)
[Link](x, y)
[Link]()
oogway.begin_fill()
[Link](radius)
oogway.end_fill()
BG_COLOR = "#0080ff"
# "Yesterday is history, tomorrow is a mystery, but today is a gift. That is why it is called
the present.”
#Oogway to Po under the peach tree, Kung Fu Panda
oogway = Turtle()
# set turtle speed
[Link](2)
screen = [Link]()
# set background color
[Link](BG_COLOR)
# set tile of screen
[Link]("Merry Christmas")
# maximize the screen
[Link](width=1.0, height=1.0)
y = -100
# create tree trunk
create_rectangle(oogway, "yellow", -15, y-60, 30, 60)
# create tree
width = 240
[Link](10)
while width > 10:
width = width - 10
height = 10
x = 0 - width/2
create_rectangle(oogway, "green", x, y, width, height)
y = y + height
# create a star a top of tree
[Link](1)
[Link]()
[Link]('yellow')
[Link](-20, y+10)
oogway.begin_fill()
[Link]()
for i in range(5):
[Link](40)
[Link](144)
oogway.end_fill()
tree_height = y + 40
# create moon in sky
# create a full circle
create_circle(oogway, 230, 180, 60, "white")
# overlap with full circle of BG color to make a crescent shape
create_circle(oogway, 220, 180, 60, BG_COLOR)
# now add few stars in sky
[Link](10)
number_of_stars = randint(20,30)
# print(number_of_stars)
for _ in range(0,number_of_stars):
x_star = randint(-(screen.window_width()//2),screen.window_width()//2)
y_star = randint(tree_height, screen.window_height()//2)
size = randint(5,20)
[Link]()
[Link]('white')
[Link](x_star, y_star)
oogway.begin_fill()
[Link]()
for i in range(5):
[Link](size)
[Link](144)
oogway.end_fill()
# print greeting message
[Link](1)
[Link]()
msg = "Merry Christmas from my family"
[Link](0, -200) # y is in minus because tree trunk was below x axis
[Link]("white")
[Link]()
[Link](msg, move=False, align="center", font=("Arial", 15, "bold"))
[Link]()
[Link]()
[Link] a prog to sum of list.
list1 = [3,4,5,9,10,12,24]
61. Creating a function with parameters
create a function that takes two parameters and displays their values.
62. Creating a function with parameters and return value .
63. # Write a Python function that takes two lists and returns True if they have at least
one common number.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
64.# parameter passing prog.
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)
65. # To display vandemataram by using function use no args no return type.
66. #Type1 : No parameters and no return type.
def Fun1() :
print("function 1")
Fun1()
67. #Type 2: with param without return type.
68. #Type 3: without param with return type.
69. #Type 4: with param with return type.
70. # create a local variable.
71. # create a global variable.
72.#color [Link]
import turtle
t = [Link]()
[Link]("black")
colors = ["red", "yellow", "blue", "green"]
for x in range(100):
[Link](colors[x%4])
[Link](x)
[Link](91)
73.# [Link] - prints a colorful spiral of the user's name
import turtle # Set up turtle graphics
t = [Link]()
[Link]("black")
colors = ["red", "yellow", "blue", "green"]
# Ask the user's name using turtle's text input pop-up window
your_name = [Link]("Enter your name", "What is your name?")
# Draw a spiral of the name on the screen, written 100 times
for x in range(100):
[Link](colors[x%4]) # Rotate through the four colors
[Link]() # Don't draw the regular spiral lines
[Link](x*4) # Just move the turtle on the screen
[Link]() # Write the user's name, bigger each time
[Link](your_name, font = ("Arial", int( (x + 4) / 4), "bold") )
[Link](92) # Turn left, just as in our other spirals
74.#Improving Our Rosette Program with User Input
import turtle
t = [Link]()
# Ask the user for the number of circles in their rosette, default to 6
number_of_circles = int([Link]("Number of circles","How many circles in your
rosette?", 6))
for x in range(number_of_circles):
[Link](100)
[Link](360/number_of_circles)
#[Link]
import turtle # Set up turtle graphics
t = [Link]()
[Link]("black")
colors = ["red", "yellow", "blue", "green", "orange",
"purple", "white", "brown", "gray", "pink" ]
family = [] # Set up an empty list for family names
# Ask for the first name
name = [Link]("My family",
"Enter a name, or just hit [ENTER] to end:")
# Keep asking for names
while name != "":
# Add their name to the family list
[Link](name)
# Ask for another name, or end
name = [Link]("My family",
"Enter a name, or just hit [ENTER] to end:")
# Draw a spiral of the names on the screen
for x in range(100):
[Link](colors[x%len(family)]) # Rotate through the colors
[Link]() # Don't draw the regular spiral lines
[Link](x*4) # Just move the turtle on the screen
[Link]() # Draw the next family member's name
[Link](family[x%len(family)], font = ("Arial", int((x+4)/4), "bold") )
[Link](360/len(family) + 2) # Turn left for our spiral
75.#calender in GUI process…….
#Importing tkinter module
from tkinter import *
#importing calendar module
import calendar
#function to show calendar of the given year
def showCalender():
gui = Tk()
[Link]fig(background='grey')
[Link]("Calender for the year")
[Link]("550x600")
year = int(year_fi[Link]())
gui_content= [Link](year)
calYear = Label(gui, text= gui_content, font= "Consolas 10 bold")
[Link](row=5, column=1,padx=20)
[Link]()
new = Tk()
[Link]fig(background='grey')
[Link]("Calender")
[Link]("250x140")
cal = Label(new, text="Calender",bg='grey',font=("times", 28, "bold"))
year = Label(new, text="Enter year", bg='dark grey')
year_field=Entry(new)
button = Button(new, text='Show
Calender',fg='Black',bg='Blue',command=showCalender)
#putting widgets in position
[Link](row=1, column=1)
[Link](row=2, column=1)
year_fi[Link](row=3, column=1)
[Link](row=4, column=1)
[Link]()
76: Program for even number with a lambda function
l = [10, 5, 12, 78, 6, 1, 7, 9]
even_nos = list(filter(lambda x: x % 2 == 0, l))
print("Even numbers are: ", even_nos)
[Link] function with filter()
l = [-10, 5, 12, -78, 6, -1, -7, 9]
positive_nos = list(filter(lambda x: x > 0, l))
print("Positive numbers are: ", positive_nos)
78. lambda function with map() function
list1 = [2, 3, 4, 8, 9]
list2 = list(map(lambda x: x*x*x, list1))
print("Cube values are:", list2)
79.#[Link]
answer = input("Do you want to see a spiral? y/n:")
if answer == 'y':
print("Working…")
import turtle
t = [Link]()
[Link](2)
for x in range(100):
[Link](x*2)
[Link](89)
print("Okay, lets start!")
80.#[Link]
import turtle
t = [Link]()
# Ask the user for the number of sides or circles, default to 6
number = int([Link]("Number of sides or circles",
"How many sides or circles in your shape?", 6))
# Ask the user whether they want a polygon or rosette
shape = [Link]("Which shape do you want?",
"Enter 'p' for polygon or 'r' for rosette:")
for x in range(number):
if shape == 'r': # User selected rosette
[Link](100)
else: # Default to polygon
[Link] (150)
[Link](360/number)
81A: Create a string made of the first, middle and last character
Write a program to create a new string made of an input string’s first, middle, and last
character.
Given:
str1 = "James"
Expected Output:
Jms
#code
str1 = 'James'
print("Original String is", str1)
# Get first character
res = str1[0]
# Get string size
l = len(str1)
# Get middle index number
mi = int(l / 2)
# Get middle character and add it to result
res = res + str1[mi]
# Get last character and add it to result
res = res + str1[l - 1]
print("New String:", res)
82: Create a string made of the middle three characters
Write a program to create a new string made of the middle three characters of an input
string.
Given:
Case 1
str1 = "JhonDipPeta"
Output
Dip
Case 2
str2 = "JaSonAy"
Output
Son
# code-----
def get_middle_three_chars(str1):
print("Original String is", str1)
# first get middle index number
mi = int(len(str1) / 2)
# use string slicing to get result characters
res = str1[mi - 1:mi + 2]
print("Middle three chars are:", res)
get_middle_three_chars("JhonDipPeta")
get_middle_three_chars("JaSonAy")
[Link] example 1−
str = 'Hello World!'
print str # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character print
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
84.# interactive mode-----
>>> x='computer'
>>> x[1:4]
'omp' #first index to four index number.
>>> x[1:6:2]
'opt' # distance between step 2 (o,p,t)
>>> x[3:]
'puter' # start the index 3 to last index.
>>> x[:5]
'compu' #start the o index to 4.
>>> x[-1]
'r' # reverse the index.
>>> x[-3:]
'ter' # index -3 to index -1.
>>> x[:-2]
'comput' #start the index to -2 index.
>>> x[::-2]
'rtpo' # reverse index distance 2 .
>>> x[::-1]
'retupmoc' # -1 to till positive index.
[Link]()
>>>string="123alpha"
>>>[Link]()
>>>True
[Link]:
[Link]()
>>>string="nikhil"
>>>[Link]()
>>>True
[Link]:
[Link]()
>>>string="123456789"
>>>[Link]()
>>>True
88. Syntax:
[Link]()
>>>string="nikhil"
>>>[Link]()
>>>True
89.#string module-----
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
print([Link])
#print([Link])
print([Link])
90.#Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
91.# Python program to demonstrate
# Creation of Array
# importing "array" for array creations
import array as arr
# creating an array with integer type
a = [Link]('i', [1, 2, 3])
# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()
# creating an array with double type
b = [Link]('d', [2.5, 3.2, 3.3])
# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")
92.# Python program to demonstrate
# Adding Elements to a Array
# importing "array" for array creations
import array as arr
# array with int type
a = [Link]('i', [1, 2, 3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()
# inserting array using
# insert() function
[Link](1, 4)
print ("Array after insertion : ", end =" ")
for i in (a):
print (i, end =" ")
print()
# array with float type
b = [Link]('d', [2.5, 3.2, 3.3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")
print()
# adding an element using append()
[Link](4.4)
print ("Array after insertion : ", end =" ")
for i in (b):
print (i, end =" ")
print()
93.# Python program to demonstrate
# accessing of element from list
# importing array module
import array as arr
# array with int type
a = [Link]('i', [1, 2, 3, 4, 5, 6])
# accessing element of array
print("Access element is: ", a[0])
# accessing element of array
print("Access element is: ", a[3])
# array with float type
b = [Link]('d', [2.5, 3.2, 3.3])
# accessing element of array
print("Access element is: ", b[1])
# accessing element of array
print("Access element is: ", b[2])
94.# Python program to demonstrate
# Removal of elements in a Array
# importing "array" for array operations
import array
# initializing array with array values
# initializes array with signed integers
arr = [Link]('i', [1, 2, 3, 1, 5])
# printing original array
print ("The new created array is : ", end ="")
for i in range (0, 5):
print (arr[i], end =" ")
print ("\r")
# using pop() to remove element at 2nd position
print ("The popped element is : ", end ="")
print ([Link](2))
# printing array after popping
print ("The array after popping is : ", end ="")
for i in range (0, 4):
print (arr[i], end =" ")
print("\r")
# using remove() to remove 1st occurrence of 1
[Link](1)
# printing array after removing
print ("The array after removing is : ", end ="")
for i in range (0, 3):
print (arr[i], end =" ")
95.# Python program to demonstrate
# slicing of elements in a Array
# importing array module
import array as arr
# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [Link]('i', l)
print("Initial Array: ")
for i in (a):
print(i, end =" ")
# Print elements of a range
# using Slice operation
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
# Print elements from a
# pre-defined point to end
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
# Printing elements from
# beginning till end
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
96.# Python code to demonstrate
# searching an element in array
# importing array module
import array
# initializing array with array values
# initializes array with signed integers
arr = [Link]('i', [1, 2, 3, 1, 2, 5])
# printing original array
print ("The new created array is : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
print ("\r")
# using index() to print index of 1st occurrence of 2
print ("The index of 1st occurrence of 2 is : ", end ="")
print ([Link](2))
# using index() to print index of 1st occurrence of 1
print ("The index of 1st occurrence of 1 is : ", end ="")
print ([Link](1))
97.# Python code to demonstrate
# how to update an element in array
# importing array module
import array
# initializing array with array values
# initializes array with signed integers
arr = [Link]('i', [1, 2, 3, 1, 2, 5])
# printing original array
print ("Array before updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
print ("\r")
# updating a element in a array
arr[2] = 6
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
print()
# updating a element in a array
arr[4] = 8
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
98.#List program- - - -
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
99.#Program- - - -
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
100.#update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
[Link] face using turtle
from turtle import *
import turtle
tur = [Link]()
def eyes(color, radius):
[Link]()
tur.fillcolor(color)
tur.begin_fill()
[Link](radius)
tur.end_fill()
[Link]()
tur.fillcolor('cyan')
tur.begin_fill()
[Link](100)
tur.end_fill()
[Link]()
[Link](-40, 120)
eyes('white', 15)
[Link](-37, 125)
eyes('blue', 5)
[Link](40, 120)
eyes('white', 15)
[Link](40, 125)
eyes('blue', 5)
[Link](0, 75)
eyes('red', 8)
[Link](-40, 85)
[Link]()
[Link](90)
[Link](40, 180)
[Link]()
[Link](-10, 45)
[Link]()
[Link](180)
tur.fillcolor('red')
tur.begin_fill()
[Link](10, 180)
tur.end_fill()
[Link]()
[Link]()
[Link] making using turtle
#imports
import turtle as t
#variables
screen = [Link]()
ganpati = [Link]()
blue = '#10557d'
white = '#ffffff'
red = '#ff0004'
black = '#000000'
yellow = '#ffb700'
[Link]('Ganpati Drawing')
[Link]('turtle')
# pentagon
[Link](blue, blue)
ganpati.begin_fill()
[Link](angle=130)
[Link](distance=55)
[Link](90)
[Link](70)
[Link](65)
[Link](70)
[Link](80)
[Link](55)
[Link](70)
[Link](66)
ganpati.end_fill()
[Link]()
[Link](10)
[Link](90)
[Link](12.5)
[Link]()
#square
[Link](yellow, yellow)
ganpati.begin_fill()
[Link](90)
for _ in range(3):
[Link](90)
[Link](90)
ganpati.end_fill()
[Link]()
[Link](10)
[Link]()
#rectangle 1
[Link](red, red)
ganpati.begin_fill()
for _ in range(2):
[Link](27.5)
[Link](90)
[Link](90)
[Link](90)
[Link]()
[Link](180)
[Link](137.5)
[Link]()
#rectangle 2
for _ in range(2):
[Link](27.5)
[Link](90)
[Link](90)
[Link](90)
ganpati.end_fill()
[Link]()
[Link](180)
[Link](57.5)
[Link](90)
[Link](5)
[Link](90)
[Link]()
# Bindi line 1
[Link](white)
[Link](50)
[Link]()
[Link](90)
[Link](5)
[Link](90)
[Link]()
#Bindi line 2
[Link](50)
[Link]()
[Link](90)
[Link](5)
[Link](90)
[Link]()
#Bindi line 3
[Link](50)
[Link]()
[Link](90)
[Link](10)
[Link]()
#Eye 1
[Link](black, black)
ganpati.begin_fill()
[Link](5)
[Link]()
[Link](90)
[Link](50)
[Link]()
#Eye 2
[Link](5)
ganpati.end_fill()
[Link]()
[Link](180)
[Link](30)
[Link](90)
[Link](25)
[Link]()
#Nose
[Link](red, red)
ganpati.begin_fill()
[Link](100)
[Link](90)
[Link](50)
[Link](90)
[Link](20)
[Link](90)
[Link](30)
[Link](90)
[Link](80)
ganpati.end_fill()
# finisher
[Link]()
[Link](1000)
[Link]()
103. # function to calculate Age
def calculateAge() :
# check for error
value = checkError()
# if error is occur then return
if value == -1 :
return
else :
# take a value from the respective entry boxes
# get method returns current text as string
birth_day = int([Link]())
birth_month = int([Link]())
birth_year = int([Link]())
given_day = int([Link]())
given_month = int([Link]())
given_year = int([Link]())
# if birth date is greater then given birth_month
# then donot count this month and add 30 to the date so
# as to subtract the date and get the remaining days
month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (birth_day > given_day):
given_month = given_month - 1
given_day = given_day + month[birth_month-1]
# if birth month exceeds given month, then
# donot count this year and add 12 to the
# month so that we can subtract and find out
# the difference
if (birth_month > given_month):
given_year = given_year - 1
given_month = given_month + 12
# calculate day, month, year
calculated_day = given_day - birth_day;
calculated_month = given_month - birth_month;
calculated_year = given_year - birth_year;
# calculated day, month, year write back
# to the respective entry boxes
# insert method inserting the
# value in the text entry box.
[Link](10, str(calculated_day))
[Link](10, str(calculated_month))
[Link](10, str(calculated_year))
# Driver Code
if __name__ == "__main__" :
# Create a GUI window
gui = Tk()
# Set the background colour of GUI window
[Link]figure(background = "light green")
# set the name of tkinter GUI window
[Link]("Age Calculator")
# Set the configuration of GUI window
[Link]("525x260")
# Create a Date Of Birth : label
dob = Label(gui, text = "Date Of Birth", bg = "blue")
# Create a Given Date : label
givenDate = Label(gui, text = "Given Date", bg = "blue")
# Create a Day : label
day = Label(gui, text = "Day", bg = "light green")
# Create a Month : label
month = Label(gui, text = "Month", bg = "light green")
# Create a Year : label
year = Label(gui, text = "Year", bg = "light green")
# Create a Given Day : label
givenDay = Label(gui, text = "Given Day", bg = "light green")
# Create a Given Month : label
givenMonth = Label(gui, text = "Given Month", bg = "light green")
# Create a Given Year : label
givenYear = Label(gui, text = "Given Year", bg = "light green")
# Create a Years : label
rsltYear = Label(gui, text = "Years", bg = "light green")
# Create a Months : label
rsltMonth = Label(gui, text = "Months", bg = "light green")
# Create a Days : label
rsltDay = Label(gui, text = "Days", bg = "light green")
# Create a Resultant Age Button and attached to calculateAge function
resultantAge = Button(gui, text = "Resultant Age", fg = "Black", bg = "Red", command
= calculateAge)
# Create a Clear All Button and attached to clearAll function
clearAllEntry = Button(gui, text = "Clear All", fg = "Black", bg = "Red", command =
clearAll)
# Create a text entry box for filling or typing the information.
dayField = Entry(gui)
monthField = Entry(gui)
yearField = Entry(gui)
givenDayField = Entry(gui)
givenMonthField = Entry(gui)
givenYearField = Entry(gui)
rsltYearField = Entry(gui)
rsltMonthField = Entry(gui)
rsltDayField = Entry(gui)
# grid method is used for placing
# the widgets at respective positions
# in table like structure .
[Link](row = 0, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 1)
[Link](row = 2, column = 0)
[Link](row = 2, column = 1)
[Link](row = 3, column = 0)
[Link](row = 3, column = 1)
[Link](row = 0, column = 4)
[Link](row = 1, column = 3)
[Link](row = 1, column = 4)
[Link](row = 2, column = 3)
[Link](row = 2, column = 4)
[Link](row = 3, column = 3)
[Link](row = 3, column = 4)
[Link](row = 4, column = 2)
[Link](row = 5, column = 2)
[Link](row = 6, column = 2)
[Link](row = 7, column = 2)
[Link](row = 8, column = 2)
[Link](row = 9, column = 2)
[Link](row = 10, column = 2)
[Link](row = 12, column = 2)
# Start the GUI
[Link]()
#draw rainbow
# Import turtle package
import turtle
# Creating a turtle screen object
sc = [Link]()
# Creating a turtle object(pen)
pen = [Link]()
# Defining a method to form a semicircle
# with a dynamic radius and color
def semi_circle(col, rad, val):
# Set the fill color of the semicircle
[Link](col)
# Draw a circle
[Link](rad, -180)
# Move the turtle to air
[Link]()
# Move the turtle to a given position
[Link](val, 0)
# Move the turtle to the ground
[Link]()
[Link](180)
# Set the colors for drawing
col = ['violet', 'indigo', 'blue',
'green', 'yellow', 'orange', 'red']
# Setup the screen features
[Link](600, 600)
# Set the screen color to black
[Link]('black')
# Setup the turtle features
[Link](90)
[Link](10)
[Link](7)
# Loop to draw 7 semicircles
for i in range(7):
semi_circle(col[i], 10*(
i + 8), -10*(i + 1))
# Hide the turtle
[Link]()
104.#draw rainbow
# Import turtle package
import turtle
# Creating a turtle screen object
sc = [Link]()
# Creating a turtle object(pen)
pen = [Link]()
# Defining a method to form a semicircle
# with a dynamic radius and color
def semi_circle(col, rad, val):
# Set the fill color of the semicircle
[Link](col)
# Draw a circle
[Link](rad, -180)
# Move the turtle to air
[Link]()
# Move the turtle to a given position
[Link](val, 0)
# Move the turtle to the ground
[Link]()
[Link](180)
# Set the colors for drawing
col = ['violet', 'indigo', 'blue',
'green', 'yellow', 'orange', 'red']
# Setup the screen features
[Link](600, 600)
# Set the screen color to black
[Link]('black')
# Setup the turtle features
[Link](90)
[Link](10)
[Link](7)
# Loop to draw 7 semicircles
for i in range(7):
semi_circle(col[i], 10*(
i + 8), -10*(i + 1))
# Hide the turtle
[Link]()
105. #Colorful star making using turtle
from turtle import *
import random
speed(speed ='fastest')
def draw(n, x, angle):
# loop for number of stars
for i in range(n):
colormode(255)
# choosing random integers
# between 0 and 255
# to generate random rgb values
a = [Link](0, 255)
b = [Link](0, 255)
c = [Link](0, 255)
# setting the outline
# and fill colour
pencolor(a, b, c)
fillcolor(a, b, c)
# begins filling the star
begin_fill()
# loop for drawing each star
for j in range(5):
forward(5 * n-5 * i)
right(x)
forward(5 * n-5 * i)
right(72 - x)
# colour filling complete
end_fill()
# rotating for
# the next star
rt(angle)
# setting the parameters
n = 30 # number of stars
x = 144 # exterior angle of each star
angle = 18 # angle of rotation for the spiral
draw(n, x, angle)
106. Draw factral tree using recursion function.
from turtle import *
speed('fastest')
# turning the turtle to face upwards
rt(-90)
# the acute angle between
# the base and branch of the Y
angle = 30
# function to plot a Y
def y(sz, level):
if level > 0:
colormode(255)
# splitting the rgb range for green
# into equal intervals for each level
# setting the colour according
# to the current level
pencolor(0, 255//level, 0)
# drawing the base
fd(sz)
rt(angle)
# recursive call for
# the right subtree
y(0.8 * sz, level-1)
pencolor(0, 255//level, 0)
lt( 2 * angle )
# recursive call for
# the left subtree
y(0.8 * sz, level-1)
pencolor(0, 255//level, 0)
rt(angle)
fd(-sz)
# tree of size 80 and level 7
y(80, 7)
107. program Alaising in list.
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b)
print(a is b)
b = a
print(a == b)
print(a is b)
b[0] = 5
print(a)
108. cloning in list.
a = [81, 82, 83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
109.#List comprehension:
110.#Reverse a list in Python
111.#Using negative slicing
112. Smiley face using turtle
from turtle import *
import turtle
tur = [Link]()
def eyes(color, radius):
[Link]()
tur.fillcolor(color)
tur.begin_fill()
[Link](radius)
tur.end_fill()
[Link]()
tur.fillcolor('cyan')
tur.begin_fill()
[Link](100)
tur.end_fill()
[Link]()
[Link](-40, 120)
eyes('white', 15)
[Link](-37, 125)
eyes('blue', 5)
[Link](40, 120)
eyes('white', 15)
[Link](40, 125)
eyes('blue', 5)
[Link](0, 75)
eyes('red', 8)
[Link](-40, 85)
[Link]()
[Link](90)
[Link](40, 180)
[Link]()
[Link](-10, 45)
[Link]()
[Link](180)
tur.fillcolor('red')
tur.begin_fill()
[Link](10, 180)
tur.end_fill()
[Link]()
[Link]()
113. #draw rainbow
# Import turtle package
import turtle
# Creating a turtle screen object
sc = [Link]()
# Creating a turtle object(pen)
pen = [Link]()
# Defining a method to form a semicircle
# with a dynamic radius and color
def semi_circle(col, rad, val):
# Set the fill color of the semicircle
[Link](col)
# Draw a circle
[Link](rad, -180)
# Move the turtle to air
[Link]()
# Move the turtle to a given position
[Link](val, 0)
# Move the turtle to the ground
[Link]()
[Link](180)
# Set the colors for drawing
col = ['violet', 'indigo', 'blue',
'green', 'yellow', 'orange', 'red']
# Setup the screen features
[Link](600, 600)
# Set the screen color to black
[Link]('black')
# Setup the turtle features
[Link](90)
[Link](10)
[Link](7)
# Loop to draw 7 semicircles
for i in range(7):
semi_circle(col[i], 10*(
i + 8), -10*(i + 1))
# Hide the turtle
[Link]()
114#pong game
# Import required library
import turtle
# Create screen
sc = [Link]()
[Link]("Pong game")
[Link]("white")
[Link](width=1000, height=600)
# Left paddle
left_pad = [Link]()
left_pad.speed(0)
left_pad.shape("square")
left_pad.color("black")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
# Right paddle
right_pad = [Link]()
right_pad.speed(0)
right_pad.shape("square")
right_pad.color("black")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(400, 0)
# Ball of circle shape
hit_ball = [Link]()
hit_ball.speed(10)
hit_ball.shape("circle")
hit_ball.color("blue")
hit_ball.penup()
hit_ball.goto(0, 0)
hit_ball.dx = 5
hit_ball.dy = -5
[Link] the program to remove the duplicate element of the list.
116. #Write the programTurn every item of a list into its square.
117. Access tuple items .
118. Loop through a tuple .
119. #Example of Repeating Tuples .
120. #Example of Finding the Length of a Tuple .
121. #Example of Nested Tuples .
122. #Example of Swapping Variables Using Tuples .
123. Slicing Tuples in Python .
124.# Deleting a Tuple in Python .
125. # Converting a List to a Tuple .
126. # Convert string tuples to list tuples.
127. Python program to Dictionary Length.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# get dictionary's length
print(len(country_capitals)) # 3
128. python program to Access Dictionary Items
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
print(country_capitals["United States"]) # Washington D.C.
print(country_capitals["England"]) # London
129. python program to Change Dictionary Items.
country_capitals = {
"United States": "Washington D.C.,
"Italy": "Naples",
"England": "London"
}
# change the value of "Italy" key to "Rome"
country_capitals["Italy"] = "Rome"
print(country_capitals)
130. Remove Dictionary Items
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# delete item having "United States" key
del country_capitals["United States"]
print(country_capitals)