0% found this document useful (0 votes)
5 views9 pages

Programs

python program compilation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Programs

python program compilation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Even or Odd Number Checker


# Program to determine if a given number is even or odd using the modulo operator and an if-
else statement.
Python
num = int(input("Enter an integer: "))

if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
2. Age-Based Access Control
# Program to simulate a system that grants or denies access based on a user's age, utilizing
an if-else statement.
Python
age = int(input("Enter your age: "))

if age >= 18:


print("Access granted. Welcome!")
else:
print("Access denied. You must be 18 or older.")
3. Grade Calculator
# Program to calculate a student's grade based on their score using if-elif-else statements to
handle multiple conditions.
Python
score = int(input("Enter the student's score: "))

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
4. Positive, Negative, or Zero Checker
# Program to classify a number as positive, negative, or zero using if-elif-else.
Python
number = float(input("Enter a number: "))

if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

5. Simple Password Verification


# Program to check if a user-entered password matches a predefined password using an if-
else statement.
Python
correct_password = "mysecretpassword"
entered_password = input("Enter the password: ")

if entered_password == correct_password:
print("Password correct. Access granted.")
else:
print("Incorrect password. Access denied.")
1. Program to calculate the sum of numbers from 1 to a given number n using a while loop:
n = 5 # Example number
total_sum = 0
counter = 1
while counter <= n:
total_sum += counter
counter += 1
print(f"The sum of numbers from 1 to {n} is: {total_sum}")

2. Program to Print the multiplication table of a given number num using a for loop:

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


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

3. Program to Reverse a given integer number using a while loop:


number = 12345 # Example number
reversed_number = 0
while number > 0:
digit = number % 10
reversed_number = (reversed_number * 10) + digit
number //= 10
print(f"The reversed number is: {reversed_number}")

4. Program to Count the number of even and odd numbers in a list using a for loop:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print(f"Number of even numbers: {even_count}")
print(f"Number of odd numbers: {odd_count}")

5. Program to Count the number of vowels in a string using a for loop:


my_string = "Hello World"
vowels = "AEIOUaeiou"
count = 0
for char in my_string:
if char in vowels:
count += 1
print(count)

6. Program to Print the Fibonacci sequence up to the 10th term using


a while loop:
a, b = 0, 1
count = 0
while count < 10:
print(a, end=" ")
a, b = b, a + b
count += 1
1. Program on Basic String Operations:
# Create a string
my_string = "Hello Python!"
# Print the string
print(f"Original string: {my_string}")
# Get the length of the string
print(f"Length of string: {len(my_string)}")
# Access characters by index (0-based)
print(f"First character: {my_string[0]}")
print(f"Last character (using negative index): {my_string[-1]}")
# Slice a string
print(f"Slice from index 6 to 12: {my_string[6:13]}")
print(f"Slice from beginning to index 5: {my_string[:5]}")
print(f"Slice from index 6 to end: {my_string[6:]}")
# Concatenate strings
greeting = "Hi"
name = "Alice"
full_message = greeting + ", " + name + "!"
print(f"Concatenated string: {full_message}")
# Repeat a string
repeated_string = "abc" * 3
print(f"Repeated string: {repeated_string}")

2. Program to display String Methods:


sample_text = " Python Programming is Fun! "
# Convert to uppercase and lowercase
print(f"Uppercase: {sample_text.upper()}")
print(f"Lowercase: {sample_text.lower()}")
# Remove leading/trailing whitespace
print(f"Stripped string: {sample_text.strip()}")
# Replace a substring
modified_text = sample_text.replace("Fun", "Awesome")
print(f"Replaced substring: {modified_text}")
# Check if a string starts or ends with a specific substring
print(f"Starts with ' Python': {sample_text.startswith(' Python')}")
print(f"Ends with 'Fun! ': {sample_text.endswith('Fun! ')}")
# Count occurrences of a character/substring
print(f"Count of 'P': {sample_text.count('P')}")
# Find the index of a substring
print(f"Index of 'Programming': {sample_text.find('Programming')}")

4. Program to Reverse a given string


str1 = "PYnative"
print("Original String is:", str1)

str1 = str1[::-1]
print("Reversed String is:", str1)

5. Program to Find the last position of a given substring


str1 = "Emma is a data scientist who knows Python. Emma works at google."
print("Original String is:", str1)

index = [Link]("Emma")
print("Last occurrence of Emma starts at index:", index)
3. Program on Conditional Checks and Iteration:
word = "madam"
# Check if a string is a palindrome
if word == word[::-1]: # [::-1] reverses the string
print(f"'{word}' is a palindrome.")
else:
print(f"'{word}' is not a palindrome.")
# Iterate through characters in a string
for char in "example":
print(char)
# Check if all characters are alphabetic or numeric
alpha_string = "HelloWorld"
numeric_string = "12345"
print(f"'{alpha_string}' is alphabetic: {alpha_string.isalpha()}")
print(f"'{numeric_string}' is numeric: {numeric_string.isdigit()}")

6. Program to Split a string on hyphens


str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)
# split string
sub_strings = [Link]("-")
print("Displaying each substring")
for sub in sub_strings:
print(sub)

7. Program to Remove special symbols / punctuation from a string


import string
str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)
new_str = [Link]([Link]('', '', [Link]))
print("New string is ", new_str)

8. Program to Replace each special symbol with # in the following string


import string
str1 = '/*Jon is @developer & musician!!'
print("The original string is : ", str1)
# Replace punctuations with #
replace_char = '#'
# [Link] to get the list of all special symbols
for char in [Link]:
str1 = [Link](char, replace_char)
print("The strings after replacement : ", str1)

9. Program to Find all occurrences of a substring in a given string by ignoring


the case
str1 = "Welcome to USA. usa awesome, isn't it?"
sub_string = "USA"
# convert string to lowercase
temp_str = [Link]()
# use count function
count = temp_str.count(sub_string.lower())
print("The USA count is:", count)
1. Basic Function Definition and Calling:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
2. Functions with Return Values:
def calculate_area(length, width):
return length * width
area = calculate_area(5, 7)
print(f"The area is: {area}")
3. Functions with Default Arguments:
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Output: 9
print(power(2, 4)) # Output: 16
4. Functions with Variable-Length Arguments:
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100
5. Functions with Keyword Arguments:
def display_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
display_info(name="Bob", age=30, city="New York")
6. Functions for Data Manipulation:
def reverse_string(s):
return s[::-1]
print(reverse_string("Python")) # Output: nohtyP
7. Functions for Conditional Logic:
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
print(is_prime(7)) # Output: True
print(is_prime(10)) # Output: False

8. Create a function with a default


argument
# function with default argument
def show_employee(name, salary=9000):
print("Name:", name, "salary:", salary)

show_employee("Ben", 12000)
show_employee("Jessa")

Create a function with variable


length of arguments
def func1(*args):
for arg in args:
print(arg)

# Example calls to the function with different numbers of arguments


func1(10, 20)
func1("hello", 3.14, True)
func1(1, 2, 3, 4, 5)
func1() # Calling with no arguments
List
1: Sum and average of all numbers in a list
Calculate and print the sum and average of all numbers in a list.
numbers = [10, 20, 30, 40, 50]
# Calculate the sum
total_sum = sum(numbers)
# Calculate the average
# The average is the sum divided by the number of elements
average = total_sum / len(numbers)
# Print the results
print("Sum:", total_sum)
print("Average:", average)

2: Reverse a list
Solution 1: list function reverse()
list1 = [100, 200, 300, 400, 500]
[Link]()
print(list1)
Solution 2: Using negative slicing
-1 indicates to start from the last item.
list1 = [100, 200, 300, 400, 500]
list1 = list1[::-1]
print(list1)

3: Turn every item of a list into its square


Given a list of numbers. write a program to turn every item of a list into its square.
numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:
# calculate square and add to the result list
[Link](i * i)
print(res)

4: Find Maximum and Minimum


Find and print the largest and smallest number in a list [8, 2, 15, 1, 9].
# List of numbers
data = [8, 2, 15, 1, 9]
# Find the maximum number
maximum_number = max(data)
# Find the minimum number
minimum_number = min(data)
# Print the results
print("Largest number:", maximum_number)
print("Smallest number:", minimum_number)

5: Count Occurrences
Count and print how many times 'Football' appears in list.
# List of fruits
sports = ['Cricket', 'Football', 'Hockey', 'Football', 'Tennis']
# Count occurrences of 'Football'
football_count = [Link]('Football')
print("Count:", football_count)

6: Sort a list of numbers


Sort a given list of numbers in ascending order and print it.
numbers = [5, 2, 8, 1, 9]
print("Original list:", numbers)
# Method 1: Using the sort() method (sorts in-place)
[Link]()
print("Sorted list (in-place using .sort()):", numbers)
# Resetting for demonstration of sorted()
numbers = [5, 2, 8, 1, 9]
print("\nOriginal list for sorted() demonstration:", numbers)
# Method 2: Using the sorted() function (returns a new sorted list)
sorted_numbers = sorted(numbers)
print("New sorted list (using sorted()):", sorted_numbers)
print("Original list after sorted() (unchanged):", numbers)

7: Combine two lists


Combine given two lists into a single list and print it.
list_a = [1, 2]
list_b = [3, 4]
# Method 1: Using the + operator (creates a new list)
combined_list_plus = list_a + list_b
print("Combined list (using + operator):", combined_list_plus)
# Method 2: Using the extend() method (modifies list_a in-place)
temp_list = [1, 2]
temp_list.extend(list_b)
print("Combined list (using .extend() on temp_list):", temp_list)
# Method 3: Using unpacking (creates a new list - Python 3.5+)
combined_list_unpacking = [*list_a, *list_b]
print("Combined list (using unpacking *):", combined_list_unpacking)
8. Remove empty strings from the list of strings
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
# remove None from list1 and convert result into list
res = list(filter(None, list1))
print(res)
9. Remove Duplicates from list
Write a function that takes a list with duplicate elements and returns a new list with
only unique
list_with_duplicates = [1, 2, 2, 3, 1, 4, 5, 4]
unique_elements_set = set(list_with_duplicates)
unique_list = list(unique_elements_set)
print(f"Original list: {list_with_duplicates}")
print(f"List with unique elements: {unique_list}")
1: Accept Numbers From User
num1 = int(input("Enter first number "))
num2 = int(input("Enter second number "))

res = num1 * num2


print("Multiplication:", res)
2: Format Output String
str1 = 'My'
str2 = 'Name'
str3 = 'Is'
str4 = 'James'
print(str1, str2, str3, str4, sep='**')
3: Display Decimal Number to Octal
using print() function
num = 8
print('%o' % num)
4: Display Float Number with 2
Decimal Places
num = 458.541315
print('%.2f' % num)
5: Accept a list of 5 float numbers as
an input from the user
numbers = []

# 5 is the list size


# run loop 5 times
for i in range(0, 5):
print("Enter number at location", i, ":")
# accept float number from user
item = float(input())
# add it to the list
[Link](item)

print("User List:", numbers)


6: Write all content of a file into a new
file by skipping line number 5
read [Link]
with open("[Link]", "r") as fp:
# read all lines from a file
lines = [Link]()

# open new file in write mode


with open("new_file.txt", "w") as fp:
count = 0
# iterate each lines from a [Link]
for line in lines:
# skip 5th lines
if count == 4:
count += 1
continue
else:
# write current line
[Link](line)
# in each iteration reduce the count
count += 17: Accept any
three string from one input() call
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)
Format variables
using [Link]() method
quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f}
dollars."
print([Link](quantity, totalMoney, price))
9: Read Line Number 4 from File
# read file
with open("[Link]", "r") as fp:
# read all lines from a file
lines = [Link]()
# get line number 3
print(lines[2])

You might also like