1
[Link]/python-programming/examples/calculator
C:\Users\kv2>pip install pandas jupyter mysql-connector 3.6.5
Python program for class XI
Program 1 Store input numbers & add tow two number
num1 = int(input('Enter first number: '))
num2 =int ( input('Enter second number: '))
sum = num1+ num2
print (sum)
Program 2 # print large no form 3 no
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
Program 3 # the number is positive or negative or zero and display an appropriate message
num = int (input('Enter number: '))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
2
Program 4 Uncomment below to take inputs from the user# calculate the area triangle
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Program 5 # Python program to find the factorial of a number provided by the user.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Program 6 # Python program to find the sum of natural numbers up to n where n is provided by
user
# change this value for a different result
#num = 16
# uncomment to take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
3
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
**************
Program 7 to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1, end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Program 8 # Python program to check if the input number is prime or not
#num = 407
# take input from the user
num = input('Enter a number: ')
# prime numbers are greater than 1
4
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
Program 9 # the number is positive or negative or zero and display an appropriate message
num = input('Enter number: ')
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Program make a simple calculator that can add,
Program 10
subtract, multiply and divide using functions '''
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
5
print("Select operation.")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Out put Select operation.
[Link] [Link] [Link]
[Link]
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210
11 #Program for finding digit sum of a given number
m=input("Enter a number")
l=len(m)
m=int(m)
print("The digitsum of ",m," is: ")
s=0
for l in range(l,0,-1):
r=m%10
s=s+r
m=int(m/10)
6
print(s)
.........................................................................................................
12 # Python Program to find the words and characters in string
string=input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
...........................................................................
13 #A program to print grade of a student based on marks
# showing use of logical and relational operators
m1=float(input("Enter marks in English (out of 100) : "))
m2=float(input("Enter marks in Hindi (out of 100) : "))
m3=float(input("Enter marks in Maths (out of 100) : "))
m4=float(input("Enter marks in Science (out of 100) : "))
m5=float(input("Enter marks in [Link] (out of 100) : "))
total=m1+m2+m3+m4+m5
per = total/5
7
if per>=90:
grade='A'
elif per<90 and per>=70:
grade='B'
elif per<70 and per>=50:
grade='C'
elif per<50 and per>=33:
grade='D'
else:
grade='E'
print("RESULT")
print("Total marks = ", total)
print("Percentage = ", per , "%")
print("Grade = ", grade)
...................................................................................................
14. #table of a given number
num = int(input("Enter the number"))
# To take input from the user
# num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1, 11):
print(num,'x',i,'=',num*i)
8. Program to print even numbers
m=int(input("enter the number"))
8
for i in range(0,m,2):
print(i)
................................................................................................................
15 # Python Program to Reverse a Number using While loop
Number = int(input("Please Enter any Number: "))
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
print("\n Reverse of entered number is = ")
print(Reverse)
....................................................
16 # A program to calculate discount based on the total amount
# showing use of logical and relational operators
amount=float(input("Enter total amount : "))
if amount>=10000:
dis=20.0
elif amount<10000 and amount>=7000:
dis=15.0
elif amount<7000 and amount>=4000:
dis=10.0
9
else:
dis=0.0
print("Amount = ", amount)
print("Discount = ", dis, "%")
print("Final amount = ", amount - (amount*dis)/100)
................................................................................
#17. Program to check if the input number is a armstrong no or not
def arm(num):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
**************************
18 # programe of looping
a= int(input("enter no for table"))
for i in range(1,11):
print(a*i)
print ("print using while loop")
i=1
while i<=10:
print(i*a)
i=i+1
10
print ("print reverse table using while loop")
i=10
while i>=1:
print(i*a)
i=i-1
print ("print table using nested loop")
for i in range(1,7):
for j in range(1, i):
print (j, end ='' )
print()
print ("print table using nested loop")
i=6
while i>=1:
for j in range(1, i):
print (j, end ='' )
print()
i=i-1
for i in range(11,1):
print(a*i)
19 # PASSWORD PRGRAM
password = "admin";
guess = input("Enter passowrd: ")
if password == guess:
print ("correct guess")
else:
print ("Try again")
20 # program of string function
Name = input ("Input Name ")
alpha=digits=Vov=0;
Namec = [Link]()
print ("lenght of name is ", len(Name))
11
print ("Capital name is ", Namec)
print ("UPPER name is ", [Link]())
print ("LOWER name is ", [Link]())
output
nput Name SumitInput Name Sumit
lenght of name is 5
Capital name is Sumit
UPPER name is SUMIT
LOWRER name is sumit
20A Program of palindrome number
num=int(raw_input("Enter a number"))
sum1=0
n=num
while num!=0:
rem=num%10
sum1=sum1*10+rem
num=num/10
if sum1==n:
print n, "is palindrome"
else:
print n, "is not palindrome"
20 B program of Fibonacci series
nterms = int(input("How many terms? "))
n1 = 0
n2 = 1
count = 0
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
12
21 # program of list
i=j=0;
list1 =[5, 10, 15, 25, 30, 35, 40, 45, 50]
list2 = eval(input("enter even no list"))
list3 =list(input(" input name "))
for i in list1:
print (i)
print ("first in list is ", list1[0])
print ("last no in list is ", i)
print (list2)
print (" print in reverse order")
i=8
while i>=1:
13
print (list1[i], end= ' ')
i=i-1
print()
print(list2)
print()
print(list3)
OUTPUT
enter even no list2
input name AMIT
5 10 15 25 30 35 40 45 50
first in list is 5
last no in list is 50
[5, 10, 15, 25, 30, 35, 40, 45, 50]
print in reverse order
50 45 40 35 30 25 15 10
['A', 'M', 'I', 'T']
22 Program of modules
def greeting(name, a,b):
print("Hello, " + name)
print("Sum, " )
print (a+b)
stu1 = {
"name": "John",
"age": 36,
"country": "Norway"
22A import mymodule
14
name = input("enter your name")
no1 = int(input("enter no"))
no2 = int(input("enter no"))
[Link](name, no1, no2)
print()
a = mymodule.stu1["name"]
print(a)
b = mymodule.stu1["age"]
print(b)
print()
import platform
x = [Link]()
print(x)
OUTPUT
enter your name amit
enter no1205
enter no123
Hello, amit
Sum,
1328
John
36
Windows
15
23 # program of dectionare
Student={"1":"Amit", "2":"Baby", "3": "Rohan","4": "Geeta", "5": "Reena"}
print(Student)
print ()
Student
print()
#change value of key5
Student["5"]= "Teena"
print (Student["1"])
print([Link]())
print(Student["5"])
# add new value to dictionares
Student["10"]= "kavita"
print([Link]())
# dictionare create by run time
n =int(input("how many member"))
Teacher = {}
for a in range(n):
key= input("name of teacher")
value= int(input("salary of teacher"))
Teacher[key]=value
print(Teacher)
********************************
OUTPUT FILE
{'1': 'Amit', '2': 'Baby', '3': 'Rohan', '4': 'Geeta', '5': 'Reena'}
dict_keys(['1', '2', '3', '4', '5'])
dict_values(['Amit', 'Baby', 'Rohan', 'Geeta', 'Teena'])
Amit
16
Teena
{'1': 'Amit', '2': 'Baby', '3': 'Rohan', '4': 'Geeta', '5': 'Teena', '10': 'kavita'}
how many member3
name of teacherAMIT
salary of teacher2000
name of teacherSUMIT
salary of teacher5000
name of teacherGEETA
salary of teacher3000
{'AMIT': 2000, 'SUMIT': 5000, 'GEETA': 3000}
24 # Python program to demonstrate NUMPARRAY
# [Link]
import numpy as np
arr = [Link]( [[ 1, 2, 3],
[ 4, 2, 5]] )
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", [Link])
17
# Printing shape of array
print("Shape of array: ", [Link])
# Printing size (total number of elements) of array
print("Size of array: ", [Link])
# Printing type of elements in array
print("Array stores elements of type: ", [Link])
OUTPUT
Array is of type: <class '[Link]'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int32
25 # Python program to demonstrate NUMPARRAY
import numpy as np
# Creating array from list with type float
a = [Link]([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)
# Creating array from tuple
b = [Link]((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
# Creating a 3X4 array with all zeros
18
c = [Link]((3, 4))
print ("\nAn array initialized with all zeros:\n", c)
# Create a constant value array of complex type
d = [Link]((3, 3), 6, dtype = 'complex')
print ("\nAn array initialized with all 6s."
"Array type is complex:\n", d)
# Create an array with random values
e = [Link]((2, 2))
print ("\nA random array:\n", e)
# Create a sequence of integers
# from 0 to 30 with steps of 5
f = [Link](0, 30, 5)
print ("\nA sequential array with steps of 5:\n", f)
# Create a sequence of 10 values in range 0 to 5
g = [Link](0, 5, 10)
print ("\nA sequential array with 10 values between"
"0 and 5:\n", g)
# Reshaping 3X4 array to 2X2X3 array
arr = [Link]([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])
newarr = [Link](2, 2, 3)
print ("\nOriginal array:\n", arr)
19
print ("Reshaped array:\n", newarr)
# Flatten array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
flarr = [Link]()
print ("\nOriginal array:\n", arr)
print ("Fattened array:\n", flarr)
OUTPUT
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
Array created using passed tuple:
[1 3 2]
An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all [Link] type is complex:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]
A random array:
[[0.3654793 0.05222288]
[0.97986546 0.61770567]]
A sequential array with steps of 5:
[ 0 5 10 15 20 25]
20
A sequential array with 10 values between0 and 5:
[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]
Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]
Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]
# [Link]
26 PROGRAM OF NUMMPY ARRAY
# basic operations on single array
import numpy as np
a = [Link]([1, 2, 5, 3])
print (a)
# add 1 to every element
print ("Adding 1 to every element:", a+1)
# subtract 3 from each element
21
print ("Subtracting 3 from each element:", a-3)
# multiply each element by 10
print ("Multiplying each element by 10:", a*10)
# square each element
print ("Squaring each element:", a**2)
# modify existing array
a *= 2
print ("Doubled each element of original array:", a)
# transpose of array
a = [Link]([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
OUTPUT
[1 2 5 3]
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]
Original array:
[[1 2 3]
[3 4 5]
22
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]
27 # [Link]
# Program to Create series
import pandas as pd # Import Panda Library
Data =[1, 3, 4, 5, 6, 2, 9] # Numeric data
s = [Link](Data)
print (s)
# predefined index values
Index =['a', 'b', 'c', 'd', 'e', 'f', 'g']
si = [Link](Data, Index)
23
print()
print (si)
# Program to Create Dictionary series
dictionary ={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
sd = [Link](dictionary)
print()
print (sd)
# Program to Create ndarray series
Data =[[2, 3, 4], [5, 6, 7]] # Defining 2darray
snd = [Link](Data)
print()
print(snd)
OUTPUT
0 1
1 3
2 4
3 5
4 6
5 2
6 9
dtype: int64
a 1
24
b 3
c 4
d 5
e 6
f 2
g 9
dtype: int64
a 1
b 2
c 3
d 4
e 5
dtype: int64
0 [2, 3, 4]
1 [5, 6, 7]
dtype: object
28# Program to Create Data Frame
import pandas as pd
# Program to Create Data Frame with two dictionaries
dict1 ={'a':1, 'b':2, 'c':3, 'd':4}
dict2 ={'a':5, 'b':6, 'c':7, 'd':8, 'e':9}
Data = {'first':dict1, 'second':dict2}
df = [Link](Data)
print (df)
# Program to create Dataframe of three series
s1 = [Link]([1, 3, 4, 5, 6, 2, 9])
s2 = [Link]([1.1, 3.5, 4.7, 5.8, 2.9, 9.3])
25
s3 = [Link](['a', 'b', 'c', 'd', 'e'])
Data ={'first':s1, 'second':s2, 'third':s3}
dfseries = [Link](Data)
print (dfseries)
print ()
# Program to create DataFrame from 2D array
d1 =[[2, 3, 4], [5, 6, 7]]
d2 =[[2, 4, 8], [1, 3, 9]]
Data ={'first': d1, 'second': d2}
df2d = [Link](Data)
print (df2d)
print ()
print (df2d+df2d)
print ()
print (df2d*2)
print (df+ 2)
Output
first second
a 1.0 5
b 2.0 6
c 3.0 7
d 4.0 8
e NaN 9
first second third
0 1 1.1 a
1 3 3.5 b
2 4 4.7 c
3 5 5.8 d
26
4 6 2.9 e
5 2 9.3 NaN
6 9 NaN NaN
first second
0 [2, 3, 4] [2, 4, 8]
1 [5, 6, 7] [1, 3, 9]
first second
0 [2, 3, 4, 2, 3, 4] [2, 4, 8, 2, 4, 8]
1 [5, 6, 7, 5, 6, 7] [1, 3, 9, 1, 3, 9]
first second
0 [2, 3, 4, 2, 3, 4] [2, 4, 8, 2, 4, 8]
1 [5, 6, 7, 5, 6, 7] [1, 3, 9, 1, 3, 9]
first second
a 3.0 7
b 4.0 8
c 5.0 9
d 6.0 10
e NaN 11
29# Program to use of CSV file
import pandas as pd
#import sqlite3 as sq
df = pd.read_csv("C:\\Users\\kv2\\Desktop\\[Link]")
print (df)
print ()
df = pd.read_csv("C:\\Users\\kv2\\Desktop\\[Link]", names=["Roll", "Name","class1"])
print (df)
df = pd.read_csv("C:\\Users\\kv2\\Desktop\\[Link]", header=None )
27
print (df)
df = pd.read_csv("C:\\Users\\kv2\\Desktop\\[Link]", names=["Roll",
"Name","class1"],nrows=2 )
print (df)
# Program to Create Data Frame with two dictionaries
dict1 ={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
dict2 ={'a':5, 'b':6, 'c':7, 'd':8, 'e':9}
Data = {'first':dict1, 'second':dict2}
df = [Link](Data)
print (df)
df.to_csv("C:\\Users\\kv2\\Desktop\\[Link]")
output
amit 101 10
0 sumit 102 11
1 nitin 103 12
2 sunit 104 10
3 nita 105 11
Roll Name class1
0 amit 101 10
1 sumit 102 11
2 nitin 103 12
28
3 sunit 104 10
4 nita 105 11
0 1 2
0 amit 101 10
1 sumit 102 11
2 nitin 103 12
3 sunit 104 10
4 nita 105 11
Roll Name class1
0 amit 101 10
1 sumit 102 11
first second
a 1 5
b 2 6
c 3 7
d 4 8
e 5 9
30 # Program to use of sqlite database
import pandas as pd
import sqlite3 as sq
conn= [Link]("C:\\sqlite3\\[Link]")
df= pd.read_sql("select * from rkl; ",conn);
#print (df)
*********************
29