Class 11 – CS 083 Practical List – Python Programming

Class 11 – Practical – Python Programming

Input a welcome message and display it.

# Input a welcome message from the user
welcome_message = input("Enter a welcome message: ")

# Display the welcome message
print("Welcome message:", welcome_message)

This program uses the input function to take a user’s input and stores it in the variable welcome_message. Then, it uses the print function to display the entered welcome message.

Input two numbers and display the larger / smaller number.

# Input two numbers from the user
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))

# Compare the numbers to find the larger and smaller ones
if number1 > number2:
    larger_number = number1
    smaller_number = number2
elif number2 > number1:
    larger_number = number2
    smaller_number = number1
else:
    print("Both numbers are equal.")
    exit(0)

# Display the larger and smaller numbers
print(f"The larger number is: {larger_number}")
print(f"The smaller number is: {smaller_number}")

In this program:

  1. We use input to get two numbers from the user.
  2. We compare the two numbers using if statements to determine which is larger and which is smaller.
  3. Finally, we print the larger and smaller numbers.

This program accounts for the possibility that the two numbers entered by the user could be equal.

Input three numbers and display the largest / smallest number.

# Input three numbers from the user
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
number3 = float(input("Enter the third number: "))

# Find the largest number
largest_number = max(number1, number2, number3)

# Find the smallest number
smallest_number = min(number1, number2, number3)

# Display the largest and smallest numbers
print(f"The largest number is: {largest_number}")
print(f"The smallest number is: {smallest_number}")

In this program:

  1. We use input to get three numbers from the user.
  2. We use the max function to find the largest number among the three.
  3. We use the min function to find the smallest number among the three.
  4. Finally, we print the largest and smallest numbers.

This program will correctly identify the largest and smallest numbers among the three input values.

Generate the following patterns using nested loops:
python-program-1

for i in range(1, 6):
    for j in range(i):
        print("*", end="")
    print()

This code uses two nested for loops. The outer loop iterates from 1 to 5, and the inner loop iterates from 0 to i-1. It prints an asterisk (*) in each iteration of the inner loop and then moves to the next line after each row of asterisks is printed.

The output of this code will be:

*
**
***
****
*****

Write a program to input the value of x and n and print the sum of the following series:
python-program-2

Determine whether a number is a perfect number, an Armstrong number or a palindrome.

# Function to check if a number is a perfect number
def is_perfect_number(number):
    divisors = [i for i in range(1, number) if number % i == 0]
    return sum(divisors) == number

# Function to check if a number is an Armstrong number
def is_armstrong_number(number):
    num_str = str(number)
    num_digits = len(num_str)
    armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)
    return armstrong_sum == number

# Function to check if a number is a palindrome
def is_palindrome_number(number):
    num_str = str(number)
    return num_str == num_str[::-1]

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

# Check if it's a perfect number, Armstrong number, or palindrome
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

if is_armstrong_number(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

if is_palindrome_number(num):
    print(f"{num} is a palindrome number.")
else:
    print(f"{num} is not a palindrome number.")

In this program:

  1. We define three functions: is_perfect_number to check for perfect numbers, is_armstrong_number to check for Armstrong numbers, and is_palindrome_number to check for palindromes.
  2. We input a number from the user.
  3. We call each of the three functions to check if the number meets the criteria for being a perfect number, an Armstrong number, or a palindrome.
  4. We print the results based on the function checks.

This program will determine whether the input number is a perfect number, an Armstrong number, and/or a palindrome and print the corresponding results.

Input a number and check if the number is a prime or composite number.

# Input a number from the user
num = int(input("Enter a positive integer: "))

# Check if the number is less than 2
if num < 2:
    print("Not a prime number.")
else:
    is_prime = True

    # Check for factors from 2 to the square root of the number
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False
            break

    # Display the result
    if is_prime:
        print(f"{num} is a prime number.")
    else:
        print(f"{num} is a composite number.")

In this program:

  1. We input a positive integer from the user.
  2. We first check if the number is less than 2 because prime numbers are defined as greater than 1. If the number is less than 2, it’s not considered prime.
  3. We use a for loop to check for factors from 2 to the square root of the number. If any factor is found, we set is_prime to False and break out of the loop.
  4. Finally, we display the result based on the value of is_prime.

This program will determine if the input number is prime or composite and print the result accordingly.

Display the terms of a Fibonacci series.

# Input the number of terms you want to display
n = int(input("Enter the number of Fibonacci terms to display: "))

# Initialize the first two terms of the series
a, b = 0, 1

# Check if the number of terms is valid
if n <= 0:
    print("Please enter a positive integer.")
elif n == 1:
    print("Fibonacci series:")
    print(a)
else:
    print("Fibonacci series:")
    print(a)
    print(b)

    # Generate and print the remaining terms
    for i in range(2, n):
        next_term = a + b
        print(next_term)
        a, b = b, next_term

In this program:

  1. We input the number of Fibonacci terms (n) to display from the user.
  2. We initialize the first two terms of the Fibonacci series as a = 0 and b = 1.
  3. We check if the input is valid (positive integer) and handle special cases where n is 1 or less.
  4. For n greater than 1, we print the first two terms and then use a for loop to generate and print the remaining terms by calculating each term as the sum of the previous two terms.

This program will display the specified number of terms in the Fibonacci series.

Compute the greatest common divisor and least common multiple of two integers.

You can compute the greatest common divisor (GCD) and least common multiple (LCM) of two integers in Python using the math module or by implementing your own GCD and LCM functions. Here’s how you can do it using the math module:

import math

# Input two integers from the user
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

# Calculate the GCD using math.gcd() function
gcd = math.gcd(num1, num2)

# Calculate the LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b)
lcm = (num1 * num2) // gcd

# Display the GCD and LCM
print(f"GCD of {num1} and {num2} is: {gcd}")
print(f"LCM of {num1} and {num2} is: {lcm}")

In this program:

  1. We import the math module to use its gcd() function to calculate the GCD.
  2. We input two integers from the user.
  3. We calculate the GCD using math.gcd() and the LCM using the formula (num1 * num2) / GCD(num1, num2).
  4. We display the calculated GCD and LCM.

This program will compute and display the GCD and LCM of the two input integers.

Count and display the number of vowels, consonants, uppercase, lowercase characters in string.

# Function to count and display character statistics
def count_characters(string):
    # Initialize counters
    vowels_count = 0
    consonants_count = 0
    uppercase_count = 0
    lowercase_count = 0

    # Define vowels (both uppercase and lowercase)
    vowels = "AEIOUaeiou"

    # Iterate through the characters in the string
    for char in string:
        # Check if the character is a vowel
        if char in vowels:
            vowels_count += 1
        # Check if the character is a consonant and not a space
        elif char.isalpha():
            consonants_count += 1

        # Check if the character is uppercase
        if char.isupper():
            uppercase_count += 1
        # Check if the character is lowercase
        elif char.islower():
            lowercase_count += 1

    # Display the results
    print("Vowels:", vowels_count)
    print("Consonants:", consonants_count)
    print("Uppercase characters:", uppercase_count)
    print("Lowercase characters:", lowercase_count)

# Input a string from the user
input_string = input("Enter a string: ")

# Call the function to count and display character statistics
count_characters(input_string)

In this program:

  1. We define a function count_characters that takes a string as input and initializes counters for vowels, consonants, uppercase characters, and lowercase characters.
  2. We iterate through each character in the string and check if it falls into one of the categories (vowel, consonant, uppercase, lowercase) using the if conditions and various string methods (isalpha(), isupper(), islower()).
  3. We increment the respective counters based on the category of the character.
  4. Finally, we display the counts for vowels, consonants, uppercase characters, and lowercase characters.

This program will count and display the specified character statistics for the input string.

Input a string and determine whether it is a palindrome or not; convert the case of characters in a string.

# Function to check if a string is a palindrome
def is_palindrome(input_string):
    # Remove spaces and convert to lowercase for case-insensitive comparison
    clean_string = input_string.replace(" ", "").lower()
    # Compare the original string with its reverse
    return clean_string == clean_string[::-1]

# Input a 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 in the string
converted_string = input_string.swapcase()
print("String with swapped case:", converted_string)

In this program:

  1. We define a function is_palindrome that checks if a given string is a palindrome. It first removes spaces and converts the string to lowercase for case-insensitive comparison and then compares the original string with its reverse.
  2. We input a string from the user.
  3. We call the is_palindrome function to check if the string is a palindrome and print the result.
  4. We use the swapcase() method to convert the case of characters in the string and print the result.

This program will determine if the input string is a palindrome or not and also provide a version of the string with the case of characters swapped.

Find the largest/smallest number in a list/tuple

To find the largest and smallest number in a list or tuple in Python, you can use the max() and min() functions, respectively. Here’s how you can do it:

# Input a list of numbers
numbers = input("Enter a list of numbers separated by spaces: ").split()
numbers = [int(num) for num in numbers]  # Convert to integer list

# Find the largest and smallest numbers
largest = max(numbers)
smallest = min(numbers)

# Display the results
print(f"Largest number: {largest}")
print(f"Smallest number: {smallest}")
# Input a tuple of numbers
numbers = tuple(input("Enter a tuple of numbers separated by spaces: ").split())
numbers = tuple(int(num) for num in numbers)  # Convert to integer tuple

# Find the largest and smallest numbers
largest = max(numbers)
smallest = min(numbers)

# Display the results
print(f"Largest number: {largest}")
print(f"Smallest number: {smallest}")

In both examples:

  1. We input a list of numbers (or a tuple of numbers for the second example).
  2. We use split() to split the input string into a list (or a tuple) of strings.
  3. We convert the strings to integers using a list (or tuple) comprehension.
  4. We use the max() function to find the largest number and the min() function to find the smallest number.
  5. Finally, we display the largest and smallest numbers.

These programs will find and display the largest and smallest numbers in the input list or tuple.

Input a list of numbers and swap elements at the even location with the elements at the odd location.

# Input a list of numbers
numbers = input("Enter a list of numbers separated by spaces: ").split()
numbers = [int(num) for num in numbers]  # Convert to integer list

# Ensure the number of elements is even to perform swaps properly
if len(numbers) % 2 != 0:
    print("Number of elements should be even for proper swapping.")
else:
    # Swap elements at even locations with elements at odd locations
    for i in range(0, len(numbers), 2):
        if i + 1 < len(numbers):
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]

    print("List after swapping:")
    print(numbers)

In this program:

  1. We input a list of numbers separated by spaces and convert the input strings into an integer list using a list comprehension.
  2. We check if the number of elements is even. Swapping can be performed correctly only if the number of elements is even.
  3. If the number of elements is even, we use a for loop with a step of 2 to swap elements at even locations with elements at odd locations. We use tuple unpacking to swap the elements.
  4. Finally, we print the list after swapping.

This program will swap elements at even locations with elements at odd locations in the list and then display the modified list.

Input a list/tuple of elements, search for a given element in the list/tuple.

To search for a given element in a list or tuple in Python, you can use the in operator or the index() method. Here’s a Python program that demonstrates how to do this:

# Input a list of elements
elements = input("Enter a list of elements separated by spaces: ").split()

# Input the element to search for
search_element = input("Enter the element to search for: ")

# Check if the element is in the list
if search_element in elements:
    print(f"{search_element} is found in the list.")
else:
    print(f"{search_element} is not found in the list.")

# Alternatively, using the index() method
try:
    index = elements.index(search_element)
    print(f"{search_element} is found at index {index}.")
except ValueError:
    print(f"{search_element} is not found in the list.")

In this program:

  1. We input a list of elements separated by spaces. The split() method is used to split the input string into a list.
  2. We input the element we want to search for.
  3. We use the in operator to check if the element is in the list. If found, it prints a message indicating that it’s found. Otherwise, it prints a message indicating that it’s not found.
  4. We also demonstrate an alternative approach using the index() method, which returns the index of the first occurrence of the element in the list. If the element is not found, it raises a ValueError exception, which we handle to print a message indicating that it’s not found.

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.

# Create an empty dictionary to store student information
student_data = {}

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

# Input student information and store it in the dictionary
for i in range(1, n + 1):
    roll_number = input(f"Enter roll number for student {i}: ")
    name = input(f"Enter name for student {i}: ")
    marks = float(input(f"Enter marks for student {i}: "))
    student_data[roll_number] = {'name': name, 'marks': marks}

# Display the names of students with marks above 75
print("Students with marks above 75:")
for roll, data in student_data.items():
    if data['marks'] > 75:
        print(data['name'])

In this program:

  1. We create an empty dictionary student_data to store student information.
  2. We input the number of students (n) from the user.
  3. We use a for loop to input the roll number, name, and marks for each student and store it in the dictionary as a nested dictionary.
  4. Finally, we iterate through the dictionary to display the names of students who have marks above 75.

This program allows you to input student data and then filters and displays the names of students with marks above 75.

Leave a Comment