1. Write a Python program to print "Hello, World!"
print("Hello, World!")
2. Write a Python program to declare and initialize an integer, a float, and a character variable. Then print their values in a single line with proper formatting.
a = 10
b = 5.5
c = 'A'
print(f"{a} {b:.2f} {c}")
3. Write a Python program to swap the values of two integer variables using a temporary variable.
a = 5
b = 10
temp = a
a = b
b = temp
print("After swapping:")
print("a =", a)
print("b =", b)
4. Write a Python program to find and display the memory size (in bytes) allocated to different data types: int, float, char, and double.
import sys
a = 0 # int
b = 0.0 # float
c = 'A' # char (single-character string)
d = 0.0 # double (same as float in Python)
print("Size of int:", sys.getsizeof(a), "bytes")
print("Size of float:", sys.getsizeof(b), "bytes")
print("Size of char:", sys.getsizeof(c), "bytes")
print("Size of double:", sys.getsizeof(d), "bytes") # Python does not distinguish float/double
5. Write a Python program to take the name of a user as input and display it on the screen.
name = input("Enter your name: ")
print("Hello,", name)
Operators
6. Write a Python program to demonstrate the use of arithmetic operators (+, -, *, /, %) on two integer numbers.
a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
7. Write a Python program to demonstrate the use of relational operators (==, !=, >, <, >=, <=) between two numbers.
a = 10
b = 20
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)
8. Write a Python program to demonstrate the use of logical operators (and, or, not) on two conditions.
a = 10
b = 5
print("a > 0 and b > 0:", a > 0 and b > 0)
print("a > 0 or b < 0:", a > 0 or b < 0)
print("not (a < b):", not (a < b))
9. Write a Python program to demonstrate the use of assignment operators (=, +=, -=, *=, /=, %=) on a variable.
a = 10
print("Initial value:", a)
a += 5
print("After a += 5:", a)
a -= 3
print("After a -= 3:", a)
a *= 2
print("After a *= 2:", a)
a /= 4
print("After a /= 4:", a)
a %= 3
print("After a %= 3:", a)
10. Write a Python program to simulate the behavior of increment and decrement operations (prefix and postfix style) using standard arithmetic.
a = 5
print("Initial value of a:", a)
# Simulating prefix increment
a = a + 1
print("After prefix increment (++a):", a)
# Simulating postfix increment
print("Value before postfix increment (a++):", a)
a = a + 1
print("After postfix increment:", a)
# Simulating prefix decrement
a = a - 1
print("After prefix decrement (--a):", a)
# Simulating postfix decrement
print("Value before postfix decrement (a--):", a)
a = a - 1
print("After postfix decrement:", a)
Data Types
11. Write a Python program to declare variables of different data types, assign values to them, and print both their values and data types.
i = 10
f = 3.14
c = 'A'
d = 123.456
print("Integer value:", i, "(", type(i).__name__, ")")
print("Float value:", f, "(", type(f).__name__, ")")
print("Character value:", c, "(", type(c).__name__, ")")
print("Double value:", d, "(", type(d).__name__, ")")
12. Write a Python program to convert a float value to an integer and print both the original float value and the converted integer value.
f = 9.78
i = int(f)
print("Original float value:", f)
print("Converted integer value:", i)
13. Write a Python program to demonstrate implicit type conversion in arithmetic operations.
i = 10
f = 3.5
result = i + f
print("Integer:", i)
print("Float:", f)
print("Result (i + f):", result)
print("Type of result:", type(result).__name__)
14. Write a Python program to take a single character as input from the user and display its corresponding ASCII value.
char = input("Enter a character: ")
ascii_value = ord(char)
print("The ASCII value of", char, "is", ascii_value)
15. Write a Python program to demonstrate overflow behavior with the char data type.
# Note: Python's int type does not overflow, but we can simulate char overflow (0 to 255)
value = 255 # Max for unsigned 8-bit char
print("Initial value:", value)
value = (value + 1) % 256
print("Value after overflow (simulated 8-bit char):", value)
If/Else and Nested If
16. Write a Python program to find the largest among three numbers entered by the user.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("The largest number is:", largest)
17. Write a Python program to check whether a given integer is even or odd.
num = int(input("Enter an integer: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
18. Write a Python program to check whether a given year is a leap year or not.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("It is a leap year.")
else:
print("It is not a leap year.")
19. Write a Python program to grade a student based on their marks using nested if statements.
marks = int(input("Enter student's marks: "))
if marks >= 0 and marks <= 100:
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")
else:
print("Invalid marks entered.")
20. Write a Python program to check whether a given number is positive, negative, or zero.
num = float(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Switch Case
21. Write a Python program to create a simple calculator that can perform basic arithmetic operations: addition, subtraction, multiplication, and division.
22. Write a Python program to display the day of the week based on user input (1 to 7) using if-elif-else conditions.
day = int(input("Enter a number (1-7) to get the corresponding day of the week: "))
if day == 1:
print("Sunday")
elif day == 2:
print("Monday")
elif day == 3:
print("Tuesday")
elif day == 4:
print("Wednesday")
elif day == 5:
print("Thursday")
elif day == 6:
print("Friday")
elif day == 7:
print("Saturday")
else:
print("Invalid input! Please enter a number between 1 and 7.")
23. Write a Python program to check whether an entered alphabet is a vowel or a consonant.
ch = input("Enter an alphabet: ").lower()
if ch in ('a', 'e', 'i', 'o', 'u'):
print("Vowel")
elif ch.isalpha():
print("Consonant")
else:
print("Invalid input")
24. Write a Python program to check whether a given integer is even or odd.
num = int(input("Enter an integer: "))
match num % 2:
case 0:
print("Even")
case 1 | -1:
print("Odd")
25. Write a Python program that displays a menu to perform addition or subtraction of two numbers.
choice = int(input("Menu:\n1. Addition\n2. Subtraction\nEnter your choice (1 or 2): "))
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
match choice:
case 1:
print("Result:", num1 + num2)
case 2:
print("Result:", num1 - num2)
case _:
print("Invalid choice.")
Loops & Nested Loops
26. Write a C program to print numbers from 1 to 10 using a for loop.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
27. Write a Python program to calculate and print the factorial of a given positive integer using a while loop.
num = int(input("Enter a positive integer: "))
i = 1
fact = 1
while i <= num:
fact *= i
i += 1
print(f"Factorial of {num} is {fact}")
28. Write a Python program to print all even numbers from 1 to 20 using a loop.
for i in range(1, 21):
if i % 2 == 0:
print(i, end=" ")
29. Write a Python program to print the multiplication table of a given number using a loop.
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
30. Write a Python program to print a square pattern of stars (*) using nested loops.
n = int(input("Enter the size of the square: "))
for i in range(n):
for j in range(n):
print("*", end=" ")
print()
Star Pattern - Nested Loops
31. Write a Python program to print a left-aligned triangle pattern of stars (*) using nested loops.
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
32. Write a Python program to print a right-aligned triangle pattern of stars (*) using nested loops.
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
print(" " * (n - i) + "* " * i)
33. Write a Python program to print a pyramid pattern of stars (*) using nested loops.
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
print(" " * (n - i) + "* " * (2 * i - 1))
34. Write a Python program to print an inverted pyramid pattern of stars (*) using nested loops.
n = int(input("Enter number of rows: "))
for i in range(n, 0, -1):
print(" " * (n - i) + "* " * (2 * i - 1))
35. Write a Python program to print a hollow square pattern of stars (*) using nested loops.
n = int(input("Enter the size of the square: "))
for i in range(1, n + 1):
for j in range(1, n + 1):
if i == 1 or i == n or j == 1 or j == n:
print("*", end=" ")
else:
print(" ", end=" ")
print()
Arrays
36. Write a Python program to declare an integer array, initialize it with values, and display the elements.
numbers = [10, 20, 30, 40, 50]
print("Array elements are:")
for num in numbers:
print(num, end=" ")
37. Write a Python program to find the sum of all elements in an integer array.
numbers = [5, 10, 15, 20, 25]
total = sum(numbers)
print("Sum of all elements:", total)
38. Write a Python program to find the largest element in an array of integers.
numbers = [12, 45, 67, 23, 89, 34]
maximum = max(numbers)
print("Largest element is:", maximum)
39. Write a Python program to reverse the elements of an integer array.
40. Write a Python program to count the number of even and odd elements in an integer array.
arr = [12, 7, 9, 20, 18, 5, 11]
even = sum(1 for x in arr if x % 2 == 0)
odd = len(arr) - even
print("Number of even elements:", even)
print("Number of odd elements:", odd)
Strings
41. Write a Python program to input a string from the user and display it on the screen.
str_input = input("Enter a string: ")
print("You entered:", str_input)
42. Write a Python program to find and display the length of a given string.
str_input = input("Enter a string: ")
print("Length of the string:", len(str_input))
43. Write a Python program to input two strings from the user and concatenate them into one.
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
result = str1 + str2
print("Concatenated string:", result)
44. Write a Python program to input a string from the user and copy its contents into another string.
original = input("Enter a string: ")
copy = original # Copy string
print("Copied string:", copy)
45. Write a Python program to input two strings from the user and compare them to determine if they are equal.
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
if str1 == str2:
print("Strings are equal.")
else:
print("Strings are not equal.")
Arrays
46. Write a Python program to declare and initialize an array (list), then display its elements.
arr = [10, 20, 30, 40, 50]
print("Array elements are:")
for num in arr:
print(num, end=" ")
47. Write a Python program to input elements into a list, calculate the sum of all elements, and display the result.
n = int(input("Enter the number of elements: "))
arr = []
print("Enter", n, "elements:")
for _ in range(n):
arr.append(int(input()))
total = sum(arr)
print("Sum of all elements =", total)
48. Write a Python program to input elements into a list, calculate the maximum of all elements, and display the result.
n = int(input("Enter the number of elements: "))
arr = []
print("Enter", n, "elements:")
for _ in range(n):
arr.append(int(input()))
maximum = max(arr)
print("Maximum element =", maximum)
49. Write a Python program to input elements into a list and display the list in reverse order.
n = int(input("Enter the number of elements: "))
arr = []
print("Enter", n, "elements:")
for _ in range(n):
arr.append(int(input()))
print("Array in reverse order:")
for i in reversed(arr):
print(i, end=' ')
50. Write a Python program to input elements into a list and count how many elements are even and how many are odd.
n = int(input("Enter the number of elements: "))
arr = []
print("Enter", n, "elements:")
for _ in range(n):
arr.append(int(input()))
even = 0
odd = 0
for num in arr:
if num % 2 == 0:
even += 1
else:
odd += 1
print("Number of even elements:", even)
print("Number of odd elements:", odd)
Strings
51. Write a Python program to take a string input from the user and print it on the screen.
text = input("Enter a string: ")
print("You entered:", text)
52. Write a Python program to input a string from the user and find its length without using the built-in len() function.
text = input("Enter a string: ")
length = 0
for char in text:
length += 1
print("Length of the string:", length)
53. Write a Python program to input two strings from the user and concatenate (join) the second string to the end of the first string. Then print the combined string.
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
combined = str1 + str2
print("Combined string:", combined)
54. Write a Python program to input a string from the user and copy it into another variable. Then print the copied string.
original = input("Enter a string: ")
copy = ""
for char in original:
copy += char
print("Copied string:", copy)
55. Write a Python program to input two strings from the user and compare them to check if they are equal or not. Display an appropriate message.
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
if str1 == str2:
print("The strings are equal.")
else:
print("The strings are not equal.")
\
Pointers
56. Write a Python program to declare an integer variable, assign it a value, and print its memory address using the id() function.
num = 42
print("Value of num:", num)
print("Address of num (using id):", id(num))
57. Write a Python program to declare an integer variable, assign a value, and use a reference (simulating a pointer) to access and print the value.
# Python doesn't support pointers like C, but all variables are references
num = 100
ref = num # ref points to the same value
print("Original value:", num)
print("Accessed through reference:", ref)
58. Write a Python program to swap the values of two integer variables using a function that takes them as references.
61. Write a Python program to simulate pointer arithmetic by traversing a list using a loop variable and printing elements without direct indexing.
arr = [3, 6, 9, 12, 15]
print("Traversing array using simulated pointer arithmetic:")
for element in arr:
print(element)
62. Write a Python program to create a function that takes two integers, adds them, and returns the sum. Call this function and print the result.
def add(a, b):
return a + b
# Main program
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = add(num1, num2)
print("Sum:", result)
63. Write a Python program to calculate the factorial of a given non-negative integer using recursion.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a non-negative integer: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print(f"Factorial of {num} is {result}")
64. Write a Python program that defines a function to check whether a given integer is a prime number.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
65. Write a Python program that uses a function to generate and print the Fibonacci series up to n terms. The function should take an integer n as an argument and print the Fibonacci sequence up to n terms. Call this function from main() after taking input from the user.
def fibonacci(n):
a, b = 0, 1
print("Fibonacci Series up to", n, "terms:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
# Main
terms = int(input("Enter the number of terms: "))
fibonacci(terms)