0% found this document useful (0 votes)
13 views6 pages

Python Programs for Beginners

The document contains a series of 27 Python programs that perform various tasks such as checking if a number is positive, negative, or zero, determining leap years, finding the largest of three numbers, and performing basic arithmetic operations. It also includes functions for string manipulation, prime number checking, and generating Fibonacci series. Each program is designed to demonstrate fundamental programming concepts and operations in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Python Programs for Beginners

The document contains a series of 27 Python programs that perform various tasks such as checking if a number is positive, negative, or zero, determining leap years, finding the largest of three numbers, and performing basic arithmetic operations. It also includes functions for string manipulation, prime number checking, and generating Fibonacci series. Each program is designed to demonstrate fundamental programming concepts and operations in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Program 1: Check positive, negative or zero


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

2. Program 2: Check leap year


# Program 2
year = int(input("Enter year (e.g., 2024): "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")

3. Program 3: Largest of three numbers


# Program 3
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
largest = a
if b > largest:
largest = b
if c > largest:
largest = c
print("Largest number is", largest)

4. Program 4: Even, odd, or multiple of 5


# Program 4
n = int(input("Enter an integer: "))
if n % 5 == 0:
print(n, "is a multiple of 5")
elif n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")

5. Program 5: Admission eligibility


# Program 5
math = int(input("Math marks: "))
physics = int(input("Physics marks: "))
chemistry = int(input("Chemistry marks: "))
total = math + physics + chemistry
if (math >= 60 and physics >= 50 and chemistry >= 40) or total >= 200:
print("Eligible for admission")
else:
print("Not eligible for admission")

6. Program 6: Traffic light action (red/yellow/green)


# Program 6
color = input("Enter traffic light color (red/yellow/green): ").strip().lower()
if color == "red":
print("Stop")
elif color == "yellow":
print("Get ready / slow down")
elif color == "green":
print("Go")
else:
print("Unknown color")

7. Program 7: Print numbers 1 to 10


# Program 7
for i in range(1, 11):
print(i)

8. Program 8: Even numbers from 1 to 50


# Program 8
for i in range(2, 51, 2):
print(i)

9. Program 9: Sum of first n natural numbers


# Program 9
n = int(input("Enter n: "))
s = 0
for i in range(1, n+1):
s += i
print("Sum is", s)

10. Program 10: Print numbers 10 down to 1


# Program 10
for i in range(10, 0, -1):
print(i)

11. Program 11: Sum of even and odd numbers separately (1..n)
# Program 11
n = int(input("Enter n: "))
sum_even = 0
sum_odd = 0
for i in range(1, n+1):
if i % 2 == 0:
sum_even += i
else:
sum_odd += i
print("Sum of even numbers:", sum_even)
print("Sum of odd numbers:", sum_odd)

12. Program 12: Check if a number is prime


# Program 12
n = int(input("Enter number: "))
if n <= 1:
print(n, "is not prime")
else:
is_prime = True
i = 2
while i*i <= n:
if n % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(n, "is prime")
else:
print(n, "is not prime")

13. Program 13: Print star pattern


# Program 13
n = 5
for i in range(1, n+1):
print('*' * i)

14. Program 14: Numeric operations (two integers)


# Program 14
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
if b != 0:
print("Quotient:", a / b)
else:
print("Cannot divide by zero")

15. Program 15: List operations (favorite movies)


# Program 15
movies = ["The Matrix", "Inception", "Interstellar", "The Dark Knight", "Parasite"]
print("Original list:", movies)
[Link]("Top Gun")
print("After adding one movie:", movies)
[Link](movies[0])
print("After removing first movie:", movies)

16. Program 16: Tuple operations


# Program 16
t = (10, 20, 30, 40, 50)
print("First element:", t[0])
print("Last element:", t[-1])
print("Slice (1:4):", t[1:4])
# Trying to modify will raise an error (uncomment to see)
# t[0] = 99

17. Program 17: Dictionary access (student)


# Program 17
student = {"name": "Ali", "roll no.": 12, "marks": 85}
print("Name:", student["name"])
print("Roll no.:", student["roll no."])
print("Marks:", student["marks"])

18. Program 18: Set operations (union & intersection)


# Program 18
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print("Union:", [Link](s2))
print("Intersection:", [Link](s2))

19. Program 19: Tuple statistics


# Program 19
t = (5, 2, 9, 1, 7)
print("Maximum:", max(t))
print("Minimum:", min(t))
print("Sum:", sum(t))

20. Program 20: Greeting function


# Program 20
def greet(name):
print("Hello", name + "!")

name = input("Enter your name: ")


greet(name)

21. Program 21: add, subtract, multiply, divide functions


# Program 21
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b

print("Add:", add(10, 5))


print("Subtract:", subtract(10, 5))
print("Multiply:", multiply(10, 5))
print("Divide:", divide(10, 5))

22. Program 22: Function that returns largest of 3 numbers


# Program 22
def largest_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c

print("Largest is", largest_of_three(10, 25, 7))

23. Program 23: Count vowels in a string


# Program 23
def count_vowels(s):
count = 0
vowels = "aeiouAEIOU"
for ch in s:
if ch in vowels:
count += 1
return count

text = input("Enter text: ")


print("Vowel count:", count_vowels(text))

24. Program 24: Function to check prime


# Program 24
def is_prime(n):
if n <= 1:
return False
i = 2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True

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


print(num, "is prime?" , is_prime(num))

25. Program 25: Factorial function


# Program 25
def factorial(n):
if n < 0:
return None
result = 1
for i in range(1, n+1):
result *= i
return result

n = int(input("Enter non-negative integer: "))


print("Factorial:", factorial(n))

26. Program 26: Reverse a string


# Program 26
def reverse_string(s):
return s[::-1]

s = input("Enter a string: ")


print("Reversed:", reverse_string(s))

27. Program 27: Fibonacci series


# Program 27
n = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
count = 0
while count < n:
print(a)
a, b = b, a + b
count += 1

Common questions

Powered by AI

Program 21 employs separate functions for addition, subtraction, multiplication, and division, structuring arithmetic operations into modular, reusable code blocks . It handles the exceptional case of division by zero by checking if the divisor is zero before performing the operation, returning a specific message "Cannot divide by zero" to alert the user. This error handling prevents runtime errors and provides clarity on invalid operations.

Program 5 employs a compound conditional structure to determine admission eligibility. It checks if the student has at least 60 marks in math, 50 in physics, and 40 in chemistry, or if the total marks exceed 200 . This setup allows flexibility as students can qualify either by meeting specific subject criteria or by achieving a high total score. Thus, even if a student falls short in one subject but scores well overall, they might still be considered eligible, indicating a degree of flexibility in the criteria.

Program 12 identifies a prime number by checking divisibility from 2 up to the square root of the number, breaking out early if any divisor is found . This method is efficient as it reduces unnecessary checks compared to testing all numbers up to n-1. A further improvement could include skipping even numbers greater than 2 during iteration, as these can't be prime, and starting checks from 3, reducing the number of iterations by half.

Programs 7 and 10 utilize the range function to demonstrate iteration in Python. Program 7 uses range(1, 11) to print numbers from 1 to 10, showcasing an ascending loop . Program 10 employs range(10, 0, -1) to count down from 10 to 1, illustrating a descending iteration. These examples highlight Python's flexible range function, allowing specification of start, stop, and step parameters, making loops versatile and expressive for different data traversal needs.

Program 2 determines if a year is a leap year by checking two conditions: first, if the year is divisible by 4 but not by 100, and second, if the year is divisible by 400 . This algorithm is reliable because it accounts for the structure of the Gregorian calendar, which defines a leap year as one that is divisible by 4 and not by 100 unless it is also divisible by 400. This design aligns with the need to keep our calendar year synchronized with the astronomical year.

Program 19's use of the 'max', 'min', and 'sum' functions is particularly useful in statistical analysis contexts where quick identification of data extremes and totals are needed. For example, in a dataset representing temperatures across a month, these functions quickly provide maximum, minimum, and total temperatures without looping through data manually . This simplifies code and enhances readability while reducing the likelihood of errors associated with manual calculations.

Program 22 uses comparative checks to determine the largest of three numbers, sequentially verifying which is greater between pairs . While effective, this approach can be optimized by using Python's built-in 'max' function, which directly returns the largest value in a given set of numbers, simplifying code and potentially improving readability and performance by leveraging Python's underlying optimizations.

The significance of using a tuple in Program 16 is to provide an immutable data structure. In Python, tuples are fixed in size and cannot be altered after creation . Attempting to modify a tuple, for example by assigning a new value to an element, will raise an error because tuples are designed to be read-only collections and provide data security and consistency by preventing changes once they are defined.

Program 25 calculates the factorial of a number using an iterative approach. It initializes a result variable to 1 and then multiplies it by each integer from 1 to n in a loop . The function will return 'None' if the input, n, is negative, as the factorial is undefined for negative numbers. This condition is explicitly checked at the beginning of the function to prevent calculation attempts with invalid inputs.

Program 23 counts vowels by iterating through a string and incrementing a count for each character found in a predefined set of vowels . This method is straightforward and efficient for vowel detection. To extend it for counting consonants, a similar approach can be implemented by defining a set of consonants and checking each character against this set. Alternatively, since vowels are already counted, consonants could be calculated by subtracting vowel counts from the total alphabetic characters, accounting for case sensitivity and excluding digits/symbols.

You might also like