Wednesday, May 31, 2023

#PYTHON(DAY35)Example Programs

            #PYTHON(DAY35)

Example Programs

1) Python Program to Find the Largest Among Three Numbers

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user
#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 is", largest)

And the output is:

The largest number is 14.0

2) Python Program to Check Prime Number

# Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable
flag = False

if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

And the output is:

29 is a prime number

3) Python Program to Print all Prime Numbers in an Interval

# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

And the output is:

Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997

4) Python Program to Find the Factorial of a Number

# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# To take input from 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)

And the output is:

The factorial of 7 is 5040

Tuesday, May 30, 2023

#PYTHON(DAY34)Example Programs

 #PYTHON(DAY34)

Example Programs

1) Python Program to Convert Celsius To Fahrenheit

# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result
celsius = 37.5

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

And the output is:

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

2) Python Program to Check if a Number is Positive, Negative or 0

num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

And the output is:

Enter a number: 2
Positive number

3) Python Program to Check if a Number is Odd or Even

# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

And the output is:

Enter a number: 43
43 is Odd

4) Python Program to Check Leap Year

# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))

And the output is:

2000 is a leap year

Monday, May 29, 2023

#PYTHON(DAY33)Example Programs

                             #PYTHON(DAY33)

Example Programs

1) Python Program to Solve Quadratic Equation

# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module
import cmath

a = 1
b = 5
c = 6

# calculate the discriminant
d = (b**2) - (4*a*c)

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

And the output is:

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

2) Python Program to Swap Two Variables

# Python program to swap two variables

x = 5
y = 10

# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values
temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

And the output is:

The value of x after swapping: 10
The value of y after swapping: 5

3) Python Program to Generate a Random Number

# Program to generate a random number between 0 and 9

# importing the random module
import random

print(random.randint(0,9))

And the output is:

5

4) Python Program to Convert Kilometers to Miles

# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))

# conversion factor
conv_fac = 0.621371

# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))

And the output is:

Enter value in kilometers: 3.5
3.50 kilometers is equal to 2.17 miles

Sunday, May 28, 2023

#PYTHON(DAY32)Example Programs

 

#PYTHON(DAY32)

Example programs

1) Python Program to Print Hello world!

print('Hello, world!')

And the output is:

Hello, world!

2) Python Program to Add Two Numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

And the output is:

The sum of 1.5 and 6.3 is 7.8

3) Python Program to Find the Square Root

num = 8 
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

And the output is:

The square root of 8.000 is 2.828

4) Python Program to Calculate the Area of a Triangle

a = 5
b = 6
c = 7

# 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)

And the output is:

The area of the triangle is 14.70

Friday, May 26, 2023

#PYTHON(DAY31)File Handling(delete() method)

 

#PYTHON(DAY31)

File Handling(delete() method)

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example:

Remove the file “demofile.txt”:

import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example:

Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Example:

Remove the folder “myfolder”:

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

#PYTHON(DAY30)FileHandling(write() method)

 

#PYTHON(DAY30)

Filehandling(write() method)

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

“a” - Append - will append to the end of the file

“w” - Write - will overwrite any existing content

Example:

Open the file “demofile2.txt” and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

And the output is:

Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content!

Example:

Open the file “demofile3.txt” and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:
f = open("demofile3.txt", "r")
print(f.read())

And the output is:

Woops! I have deleted the content!

Note: the “w” method will overwrite the entire file.

Thursday, May 25, 2023

#PYTHON(DAY29)File Handling(read() method)

 

#PYTHON(DAY29)

File Handling(read() method)

Definition and Usage

Python provides the various function to read the file, but we will use the most common read() function. It takes an argument called size, which is nothing but a given number of characters to be read from the file. If the size is not specified, then it will read the entire file.

The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.

Syntax:

file.read()

Parameter Values:

Parameter : size

Description : Optional. The number of bytes to return. Default -1, which means the whole file.

Example :

Read the content of the file “demofile.txt”:

f = open("demofile.txt", "r")
print(f.read(33))

And the output is:

Hello! Welcome to demofile.txt
Th

Wednesday, May 24, 2023

#PYTHON(DAY28)File Handling open() function

 

#PYTHON(DAY28)

File Handling(open() function)

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

“r” - Read - Default value. Opens a file for reading, error if the file does not exist

“a” - Append - Opens a file for appending, creates the file if it does not exist

“w” - Write - Opens a file for writing, creates the file if it does not exist

“x” - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

“t” - Text - Default value. Text mode

“b” - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because “r” for read, and “t”for text are the default values, you do not need to specify them.

Example:

# opens python.text file of the current directory  
f = open("python.txt")
# specifying full path
f = open("C:/Python33/README.txt")

And the output is:

Since the mode is omitted, the file is opened in 'r' mode; opens for reading.

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...