Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
100 views

Practical cs

Practical for cs

Uploaded by

parthrajsharma12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Practical cs

Practical for cs

Uploaded by

parthrajsharma12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Practical 1

OBJECTIVE: Input a welcome message and display it.


PYTHON PROGRAMME
# Ask for the user's name

user_name = input("What is your name? ")

# Display a welcome message using the user's name

print(f"Hello, {user_name}! Welcome to our program!")

OUTPUT
What is your name? Alice

Hello, Alice! Welcome to our program!


Practical 2
OBJECTIVE: Input two numbers and display the larger
and smaller number.
PYTHON PROGRAMME
# Input two numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Compare the numbers and display the larger and smaller number

if num1 > num2:

print(f"The larger number is {num1}")

print(f"The smaller number is {num2}")

elif num1 < num2:

print(f"The larger number is {num2}")

print(f"The smaller number is {num1}")

else:

print("Both numbers are equal.")

OUTPUT
Enter the first number: 10

Enter the second number: 20

The larger number is 20.0

The smaller number is 10.0

Enter the first number: 25

Enter the second number: 25

Both numbers are equal.


Practical 3
OBJECTIVE: Input three numbers and display the
largest and smallest number.
PYTHON PROGRAMME
# Input three numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

num3 = float(input("Enter the third number: "))

# Find the largest and smallest number

largest = num1

smallest = num1

# Compare the numbers

if num2 > largest:

largest = num2

if num3 > largest:

largest = num3

if num2 < smallest:

smallest = num2

if num3 < smallest:

smallest = num3

# Display the largest and smallest numbers

print(f"The largest number is {largest}")

print(f"The smallest number is {smallest}")

OUTPUT
Enter the first number: 30

Enter the second number: 25

Enter the third number: 40

The largest number is 40.0

The smallest number is 25.0


Practical 4
OBJECTIVE: Generate
# Pattern 3: Right-angled triangle with letters
the following patterns
print("Pattern-3:")
using nested loops.
for i in range(1, 6): # Loop for rows
Pattern-1 Pattern-2 for j in range(i): # Loop for printing letters
Pattern-3 in each row

print(chr(65 + j), end="") # chr(65) is


* 12345 A 'A', chr(66) is 'B', and so on
** 1234 AB print() # Newline after each row
*** 123 ABC
OUTPUT
**** 12 ABCD
Pattern-1:
***** 1 ABCDE
*
PYTHON PROGRAMME **
# Pattern 1: Right-angled triangle with stars ***
print("Pattern-1:") ****
for i in range(1, 6): # Loop for rows *****
for j in range(i): # Loop for printing '*' in Pattern-2:
each row
12345
print("*", end="")
1234
print() # Newline after each row
123

12
print("Pattern-2:")
1
# Pattern 2: Right-angled triangle with
numbers Pattern-3:

for i in range(5, 0, -1): # Loop for rows (start A


from 5 to 1)
AB
for j in range(1, i + 1): # Loop for printing
numbers in each row ABC

print(j, end="") ABCD

print() # Newline after each row ABCDE


Practical 5
OBJECTIVE: Write a program to input value of x and n
and print the sum of the following series:

PYTHON PROGRAMME
#SERIES 1

def series1(x, n):

total = 0

for i in range(n + 1):

total += x**i

return total

# Input from the user

x = int(input("Enter the value of x: "))

n = int(input("Enter the value of n: "))

print("Sum of the series:", series1(x, n))

#SERIES 2

def series2(x, n):

total = 0

for i in range(n + 1):

total += (-1)**i * x**i

return total

# Input from the user

x = int(input("Enter the value of x: "))

n = int(input("Enter the value of n: "))

print("Sum of the series:", series2(x, n))

#SERIES 3

def series3(x, n):

total = 0
for i in range(2, n + 1):

total += x**i / i

return total

# Input from the user

x = int(input("Enter the value of x: "))

n = int(input("Enter the value of n: "))

print("Sum of the series:", series3(x, n))

#SERIES 4

import math

def series4(x, n):

total = 0

for i in range(1, n + 1):

total += x**i / math.factorial(i)

return total

# Input from the user

x = int(input("Enter the value of x: "))

n = int(input("Enter the value of n: "))

print("Sum of the series:", series4(x, n))

OUTPUT
Enter the value of x: 2

Enter the value of n: 4

Sum of the series: 31

Enter the value of x: 2

Enter the value of n: 4

Sum of the series: 11

Enter the value of x: 2

Enter the value of n: 4

Sum of the series: 8.666666666666666

Enter the value of x: 2

Enter the value of n: 4

Sum of the series: 6.0


Practical 6
OBJECTIVE: Determine if a number is a perfect
number, and Armstrong number or a palindrome.
PYTHON PROGRAMME # Check and display the results

# Function to check if a number is a perfect


number if is_perfect_number(num):

def is_perfect_number(num): print(f"{num} is a Perfect Number.")

divisors_sum = sum(i for i in range(1, num) else:


if num % i == 0)
print(f"{num} is not a Perfect Number.")
return divisors_sum == num

if is_armstrong_number(num):
# Function to check if a number is an
Armstrong number print(f"{num} is an Armstrong Number.")

def is_armstrong_number(num): else:

num_str = str(num) print(f"{num} is not an Armstrong


Number.")
num_digits = len(num_str)

armstrong_sum = sum(int(digit) **
num_digits for digit in num_str) if is_palindrome(num):

return armstrong_sum == num print(f"{num} is a Palindrome.")

else:

# Function to check if a number is a print(f"{num} is not a Palindrome.")


palindrome

def is_palindrome(num): OUTPUT


return str(num) == str(num)[::-1]
Enter a number: 6

6 is a Perfect Number.
# Input number from the user
6 is not an Armstrong Number.
num = int(input("Enter a number: "))
6 is a Palindrome.
Practical 7
OBJECTIVE: Input a number and check if the number is
a prime or composite number.
PYTHON PROGRAMME
# Function to check if a number is prime or composite

def check_prime_or_composite(num):

if num <= 1:

return "Neither prime nor composite"

# Check if num is divisible by any number from 2 to num-1

for i in range(2, int(num**0.5) + 1): # Optimized loop to check divisibility

if num % i == 0:

return "Composite" # If divisible by any number, it's composite

return "Prime" # If no divisors found, it's prime

# Input number from the user

num = int(input("Enter a number: "))

# Check and display the result

result = check_prime_or_composite(num)

print(f"The number {num} is {result}.")

OUTPUT
Enter a number: 29

The number 29 is Prime.

Enter a number: 1

The number 1 is Neither prime nor composite.

Enter a number: 15

The number 15 is Composite.


Practical 8
OBJECTIVE: Display the terms of a Fibonacci series.
PYTHON PROGRAMME
# Function to display the Fibonacci series up to n terms

def fibonacci(n):

a, b = 0, 1 # Starting values for the Fibonacci series

for _ in range(n):

print(a, end=" ")

a, b = b, a + b # Update a and b for the next terms

# Input the number of terms from the user

n = int(input("Enter the number of terms for the Fibonacci series: "))

OUTPUT
Enter the number of terms for the Fibonacci series: 10

0 1 1 2 3 5 8 13 21 34

Enter the number of terms for the Fibonacci series: 5

01123
Practical 9
OBJECTIVE: Compute the greatest common divisor and
least common multiple of two integers.
PYTHON PROGRAMME
# Function to compute the GCD of two numbers using the Euclidean algorithm

def gcd(a, b):

while b:

a, b = b, a % b # Update a and b

return a

# Function to compute the LCM of two numbers using the formula LCM(a, b) = |a * b| / GCD(a, b)

def lcm(a, b):

return abs(a * b) // gcd(a, b)

# Input two integers from the user

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

# Compute and display the GCD and LCM

gcd_result = gcd(a, b)

lcm_result = lcm(a, b)

print(f"The GCD of {a} and {b} is: {gcd_result}")

print(f"The LCM of {a} and {b} is: {lcm_result}")

OUTPUT
Enter the first number: 12

Enter the second number: 15

The GCD of 12 and 15 is: 3

The LCM of 12 and 15 is: 60


Practical 10
OBJECTIVE: Count and display the number of vowels,
consonants, uppercase, lowercase characters in a
string.
PYTHON PROGRAMME
def count_characters(input_string):

vowels = "aeiouAEIOU"

vowels_count = 0

consonants_count = 0

uppercase_count = 0

lowercase_count = 0

for char in input_string:

if char.isalpha(): # Check if the character is a letter

if char in vowels:

vowels_count += 1 # If it's a vowel, increment vowel count

else:

consonants_count += 1 # If it's a consonant, increment consonant

if char.isupper():

uppercase_count += 1 # If it's uppercase, increment uppercase

elif char.islower():

lowercase_count += 1 # If it's lowercase, increment lowercase

print(f"Vowels: {vowels_count}")

print(f"Consonants: {consonants_count}")

print(f"Uppercase letters: {uppercase_count}")

print(f"Lowercase letters: {lowercase_count}")

# Input string from the user

input_string = input("Enter a string: ")

# Call the function to count and display character types

count_characters(input_string)

OUTPUT
Enter a string: Hello World!

Vowels: 3

Consonants: 7

Uppercase letters: 2
Lowercase letters: 8
Practical 11
OBJECTIVE: Input a string and determine whether it is
a palindrome or not; convert the case of characters in a
string.

PYTHON PROGRAMME
# Function to check if a string is a palindrome

def is_palindrome(input_string):

# Remove spaces and convert to lowercase for uniformity

cleaned_string = input_string.replace(" ", "").lower()

# Check if the string is equal to its reverse

return cleaned_string == cleaned_string[::-1]

# Function to convert the case of characters in a string

def convert_case(input_string):

return input_string.swapcase()

# Input string from the user

input_string = input("Enter a string: ")

# Check if the string is a palindrome

if is_palindrome(input_string):

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

# Convert the case of characters and display the result

converted_string = convert_case(input_string)

print(f"Converted case: {converted_string}")

OUTPUT
Enter a string: Hello

The string is not a palindrome.

Converted case: hELLO


Practical 12
OBJECTIVE: Find the largest and smallest number in a
list or tuple.
PYTHON PROGRAMME
# Function to find the largest and smallest number in a list or tuple

def find_largest_and_smallest(numbers):

largest = max(numbers) # Find the largest number using max()

smallest = min(numbers) # Find the smallest number using min()

return largest, smallest

# Input a list or tuple from the user (in this case, a list of numbers)

numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))

# Find and display the largest and smallest numbers

largest, smallest = find_largest_and_smallest(numbers)

print(f"The largest number is: {largest}")

print(f"The smallest number is: {smallest}")

OUTPUT
Enter numbers separated by spaces: 30 18 42 10 15

The largest number is: 42

The smallest number is: 10

Enter numbers separated by spaces: 12 5 8 20 7

The largest number is: 20

The smallest number is: 5


Practical 13
OBJECTIVE: Input a list of numbers and swap the
elements at the even location with the elements at the
odd location.
PYTHON PROGRAMME
# Function to swap elements at even and odd locations

def swap_even_odd_locations(numbers):

# Loop through the list, step 2 to check even and odd indexed elements

for i in range(0, len(numbers) - 1, 2):

# Swap the elements at the current index (even) and the next index (odd)

numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]

return numbers

# Input list of numbers from the user

numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))

# Swap the elements at even and odd positions

swapped_list = swap_even_odd_locations(numbers)

# Display the swapped list

print("List after swapping elements at even and odd locations:", swapped_list)

OUTPUT
Enter numbers separated by spaces: 1 2 3 4 5 6

List after swapping elements at even and odd locations: [2, 1, 4, 3, 6, 5]

Enter numbers separated by spaces: 10 20 30 40 50

List after swapping elements at even and odd locations: [20, 10, 40, 30, 50]
Practical 14
OBJECTIVE: Input a list or tuple of elements, search for
a given element in the list or tuple.
PYTHON PROGRAMME
# Function to search for an element in a list or tuple

def search_element(collection, element):

if element in collection:

return f"Element {element} found in the collection."

else:

return f"Element {element} not found in the collection."

# Input the collection type (list or tuple)

collection_type = input("Enter the collection type (list/tuple): ").lower()

# Input the elements for the list or tuple

if collection_type == "list":

collection = list(map(int, input("Enter list elements separated by spaces: ").split()))

elif collection_type == "tuple":

collection = tuple(map(int, input("Enter tuple elements separated by spaces: ").split()))

else:

print("Invalid collection type!")

collection = []

element = int(input("Enter the element to search for: "))

result = search_element(collection, element)

print(result)

OUTPUT
Enter the collection type (list/tuple): tuple

Enter tuple elements separated by spaces: 5 10 15 20 25

Enter the element to search for: 100

Element 100 not found in the collection.


Practical 15
OBJECTIVE: Create a dictionary with the roll number,
name and marks of n students in a class and display
the names of students who have marks above 75.
PYTHON PROGRAMME
# Function to create the student dictionary

def display_students_above_75(n):

student_dict = {}

for _ in range(n):

roll_number = input("Enter roll number: ")

name = input("Enter student name: ")

marks = float(input("Enter marks: "))

# Add the student information to the dictionary

student_dict[roll_number] = {'name': name, 'marks': marks}

print("\nStudents with marks above 75:")

for roll_number, details in student_dict.items():

if details['marks'] > 75:

print(details['name'])

n = int(input("Enter the number of students: "))

# Call the function to input data and display students with marks above 75

display_students_above_75(n)

OUTPUT
Enter the number of students: 3

Enter roll number: 1

Enter student name: Alice

Enter marks: 80

Enter roll number: 2

Enter student name: Bob

Enter marks: 70

Enter roll number: 3

Enter student name: Charlie

Enter marks: 85

Students with marks above 75:

Alice
Charlie

You might also like