0% found this document useful (0 votes)
7 views14 pages

Essential Python Functions Guide

The document provides a comprehensive guide to various Python programming tasks, including counting occurrences in a list, finding the second largest element, removing duplicates, calculating factorials, and more. It features a menu-driven interface for user interaction, allowing users to select different functionalities. Additionally, it includes examples of string manipulation and list operations.

Uploaded by

vidyabhagyaraj25
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)
7 views14 pages

Essential Python Functions Guide

The document provides a comprehensive guide to various Python programming tasks, including counting occurrences in a list, finding the second largest element, removing duplicates, calculating factorials, and more. It features a menu-driven interface for user interaction, allowing users to select different functionalities. Additionally, it includes examples of string manipulation and list operations.

Uploaded by

vidyabhagyaraj25
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

Install Python using this link

[Link]

Type 1
import math
from collections import Counter

def count_occurrences():
lst = [1, 2, 2, 3,5,6,6,7, 4, 4, 5]
print("Occurrences:", dict(Counter(lst)))

def second_largest():
lst = [12, 45, 7, 34, 89, 23]
[Link]()
print("Second Largest:", lst[-2])

def remove_duplicates():
lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))
print("Without Duplicates:", unique)

def factorial():
n=5
fact = 1
i=1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)

def reverse_string():
s = "Python"
print("Reversed String:", s[::-1])

def check_palindrome():
s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

def prime_numbers():
n = 10
primes = []
num = 2
while len(primes) < n:
for i in range(2, num):
if num % i == 0:
break
else:
[Link](num)
num += 1
print("First", n, "primes:", primes)

def perfect_square():
n = 49
if int([Link](n))**2 == n:
print("Perfect Square")
else:
print("Not Perfect Square")

def average_list():
lst = [10, 20, 30, 40, 50]
avg = sum(lst) / len(lst)
print("Average:", avg)

def square_number():
n=7
print("Square:", n**2)

def largest_element():
lst = [15, 78, 23, 56, 99, 12]
print("Largest Element:", max(lst))

def celsius_to_fahrenheit():
c = 37
f = (c * 9/5) + 32
print("Fahrenheit:", f)

def area_circle():
r=7
area = [Link] * r**2
print("Area of Circle:", area)

def sum_natural():
n = 10
total = n * (n + 1) // 2
print("Sum:", total)

# Menu
while True:
print("\n--- Python Programs Menu ---")
print("1. Count occurrences in list")
print("2. Find second largest element")
print("3. Remove duplicates from list")
print("4. Factorial using while loop")
print("5. Reverse a string")
print("6. Check palindrome")
print("7. First n prime numbers")
print("8. Check perfect square")
print("9. Average of list")
print("10. Square of number")
print("11. Largest element in list")
print("12. Celsius to Fahrenheit")
print("13. Area of circle")
print("14. Sum of natural numbers")
print("0. Exit")

choice = int(input("Enter your choice: "))

if choice == 1: count_occurrences()
elif choice == 2: second_largest()
elif choice == 3: remove_duplicates()
elif choice == 4: factorial()
elif choice == 5: reverse_string()
elif choice == 6: check_palindrome()
elif choice == 7: prime_numbers()
elif choice == 8: perfect_square()
elif choice == 9: average_list()
elif choice == 10: square_number()
elif choice == 11: largest_element()
elif choice == 12: celsius_to_fahrenheit()
elif choice == 13: area_circle()
elif choice == 14: sum_natural()
elif choice == 0:
print("Exiting program...")
break
else:
print("Invalid choice, try again!")

--- Python Programs Menu ---


1. Count occurrences in list
2. Find second largest element
3. Remove duplicates from list
4. Factorial using while loop
...
Enter your choice: 4
Factorial: 120

Type 2:
import math

def count_occurrences():
lst = list(map(int, input("Enter numbers separated by space: ").split()))
occurrences = {}
for num in lst:
occurrences[num] = [Link](num, 0) + 1
print("Occurrences:", occurrences)

def second_largest():
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = list(set(lst)) # remove duplicates
[Link]()
if len(lst) < 2:
print("Not enough unique elements!")
else:
print("Second Largest:", lst[-2])

def remove_duplicates():
lst = list(map(int, input("Enter numbers separated by space: ").split()))
unique = []
for num in lst:
if num not in unique:
[Link](num)
print("Without Duplicates:", unique)

def factorial():
n = int(input("Enter a number: "))
fact = 1
i=1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)

def reverse_string():
s = input("Enter a string: ")
print("Reversed String:", s[::-1])

def check_palindrome():
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

def prime_numbers():
n = int(input("Enter how many prime numbers you want: "))
primes = []
num = 2
while len(primes) < n:
for i in range(2, num):
if num % i == 0:
break
else:
[Link](num)
num += 1
print("First", n, "primes:", primes)

def perfect_square():
n = int(input("Enter a number: "))
if int([Link](n))**2 == n:
print("Perfect Square")
else:
print("Not Perfect Square")

def average_list():
lst = list(map(int, input("Enter numbers separated by space: ").split()))
if len(lst) == 0:
print("List is empty!")
else:
avg = sum(lst) / len(lst)
print("Average:", avg)

def square_number():
n = int(input("Enter a number: "))
print("Square:", n**2)

def largest_element():
lst = list(map(int, input("Enter numbers separated by space: ").split()))
if len(lst) == 0:
print("List is empty!")
else:
print("Largest Element:", max(lst))

def celsius_to_fahrenheit():
c = float(input("Enter Celsius value: "))
f = (c * 9/5) + 32
print("Fahrenheit:", f)

def area_circle():
r = float(input("Enter radius of circle: "))
area = [Link] * r**2
print("Area of Circle:", area)

def sum_natural():
n = int(input("Enter a number: "))
total = n * (n + 1) // 2
print("Sum of natural numbers up to", n, ":", total)

# ---------------- Menu ----------------


while True:
print("\n--- Python Programs Menu ---")
print("1. Count occurrences in list")
print("2. Find second largest element")
print("3. Remove duplicates from list")
print("4. Factorial using while loop")
print("5. Reverse a string")
print("6. Check palindrome")
print("7. First n prime numbers")
print("8. Check perfect square")
print("9. Average of list")
print("10. Square of number")
print("11. Largest element in list")
print("12. Celsius to Fahrenheit")
print("13. Area of circle")
print("14. Sum of natural numbers")
print("0. Exit")

choice = int(input("Enter your choice: "))

if choice == 1: count_occurrences()
elif choice == 2: second_largest()
elif choice == 3: remove_duplicates()
elif choice == 4: factorial()
elif choice == 5: reverse_string()
elif choice == 6: check_palindrome()
elif choice == 7: prime_numbers()
elif choice == 8: perfect_square()
elif choice == 9: average_list()
elif choice == 10: square_number()
elif choice == 11: largest_element()
elif choice == 12: celsius_to_fahrenheit()
elif choice == 13: area_circle()
elif choice == 14: sum_natural()
elif choice == 0:
print("Exiting program...")
break
else:
print("Invalid choice, try again!")
-- Python Programs Menu ---
1. Count occurrences in list
2. Find second largest element
3. Remove duplicates from list
...

Enter your choice: 1


Enter numbers separated by space: 1 2 2 3 4 4 5
Occurrences: {1: 1, 2: 2, 3: 1, 4: 2, 5: 1}

Type 3:
1) Count the occurrences of each element in a list
from collections import Counter

lst = [1, 2, 2, 3, 4, 4, 4, 5]
count = Counter(lst)
print("Occurrences:", dict(count))
Output:
Occurrences: {1: 1, 2: 2, 3: 1, 4: 3, 5: 1}

2) Find the second largest element in a list


lst = [12, 45, 7, 34, 89, 23]
[Link]()
print("Second Largest:", lst[-2])
Output:
Second Largest: 45

3) Remove duplicates from a list


lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))
print("Without Duplicates:", unique)
Output:
Without Duplicates: [1, 2, 3, 4, 5]

4) Factorial of a number using while loop


n=5
fact = 1
i=1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)
Output:
Factorial: 120

5) Reverse a string
s = "Python"
print("Reversed String:", s[::-1])
Output:
Reversed String: nohtyP

6) Check if a string is palindrome


s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Output:
Palindrome

7) Find first n prime numbers


n = 10
primes = []
num = 2
while len(primes) < n:
for i in range(2, num):
if num % i == 0:
break
else:
[Link](num)
num += 1
print("First", n, "primes:", primes)
Output:
First 10 primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

8) Check if a number is a perfect square


import math
n = 49
if int([Link](n))**2 == n:
print("Perfect Square")
else:
print("Not Perfect Square")
Output:
Perfect Square
9) Calculate average of a list
lst = [10, 20, 30, 40, 50]
avg = sum(lst) / len(lst)
print("Average:", avg)
Output:
Average: 30.0

10) Find square of a number


n=7
print("Square:", n**2)
Output:
Square: 49

11) Find the largest element in a list


lst = [15, 78, 23, 56, 99, 12]
print("Largest Element:", max(lst))
Output:
Largest Element: 99

12) Convert Celsius to Fahrenheit


c = 37
f = (c * 9/5) + 32
print("Fahrenheit:", f)
Output:
Fahrenheit: 98.6

13) Calculate area of a circle


import math
r=7
area = [Link] * r**2
print("Area of Circle:", area)
Output:
Area of Circle: 153.93804002589985

14) Find sum of natural numbers up to n


n = 10
total = n * (n + 1) // 2
print("Sum:", total)
Output:
Sum: 55

Some String Manipulation One-Liners


strings = ["hello", "world", "python", "rocks"]
uppercase_strings = [[Link]() for s in strings]
print(uppercase_strings)

O/P : ['HELLO', 'WORLD', 'PYTHON', 'ROCKS']

fruits = ["apple", "banana", "cherry", "apricot", "blueberry"]


filtered = [s for s in fruits if "ap" in s]
print(filtered)

O/P: ['apple', 'apricot']

strings = [" rust ", " python "]


trimmed_strings = [[Link]() for s in strings]
print(trimmed_strings)

O/P: ['rust', 'python']

to_do = ["code", "debug", "refactor"]


reversed_strings = [task[::-1] for task in to_do]
print(reversed_strings)

O/P: ['edoc', 'gubed', 'rotcafer']

strings = ["code", "debug", "test"]


prefixed_strings = [f"py-{s}" for s in strings]
print(prefixed_strings)

O/P: ['py-code', 'py-debug', 'py-test']

strings = ["learn python", "python is fun"]


split_strings = [[Link]() for s in strings]
print(split_strings)

O/P: [['learn', 'python'], ['python', 'is', 'fun']]

strings = ["C is cool", "I code in C", "I like C"]


replaced_strings = [[Link]("C", "Python") for s in strings]
print(replaced_strings)

O/P: ['Python is cool', 'I code in Python', 'I like Python']


strings = ["apple", "banana", "cherry"]
char_counts = [[Link]("a") for s in strings]
print(char_counts)

O/P: [1, 3, 0]

strings = ["Python", "is", "great"]


sentence = " ".join(strings)
print(sentence)

O/P: Python is great

strings = ["python", "rocks"]


capitalized_strings = [[Link]() for s in strings]
print(capitalized_strings)

O/P: ['Python', 'Rocks']

strings = ["elephant", "cat", "dinosaur", "ant"]


lengths = [len(s) for s in strings]
print(lengths)

O/P: [8, 3, 8, 3]

strings = ["hello123", "world!", "python3.12", "rocks"]


is_alphanumeric = [[Link]() for s in strings]
print(is_alphanumeric)

O/P: [True, False, False, True]

files = ["main", "test", "app"]


suffixed_files = [file + ".py" for file in files]
print(suffixed_files)

O/P: ['[Link]', '[Link]', '[Link]']

strings = ["banana", "cherry", "date", "blueberry"]


first_letters = [s[0] for s in strings]
print(first_letters)

O/P: ['b', 'c', 'd', 'b']

strings = ["Apple", "banana", "Cherry", "date"]


sorted_strings = sorted(strings, key=lambda s: [Link]())
print(sorted_strings)

O/P: ['Apple', 'banana', 'Cherry', 'date']

List:
shopping_list = ['apples','pens','oatmeal cookies','notepad','brushes','paint']

shopping_list[2] = 'candy'
print(shopping_list)
#output: ['apples', 'pens', 'candy', 'notepad', 'brushes', 'paint']

for item in shopping_list:


print(item)
#output: apples
#pens
#candy
#notepad
#brushes
#paint

print(shopping_list[2:])
# Output: ['candy', 'notepad', 'brushes', 'paint']

print(shopping_list[:2])
# Output: ['apples', 'pens']

print(shopping_list[:])
# Output: ['apples', 'pens', 'candy', 'notepad', 'brushes', 'paint']

print(len(shopping_list))
#6

print(max(shopping_list))
# pens

print(min(shopping_list))
# apples

# list methods
shopping_list.append('grapes')
print(shopping_list)
#['apples', 'pens', 'candy', 'notepad', 'brushes', 'paint', 'grapes']

shopping_list.extend(['protein bars','cheese'])
print(shopping_list)
#['apples', 'pens', 'candy', 'notepad', 'brushes', 'paint', 'grapes', 'protein bars',
'cheese']

last_element = shopping_list.pop()
#print(shopping_list)
print(last_element)
#cheese

not_needed = shopping_list.pop(2)
print(not_needed)
#candy
print(shopping_list)
#['apples', 'pens', 'notepad', 'brushes', 'paint', 'grapes', 'protein bars']

del shopping_list[1]
print(shopping_list)
#['apples', 'notepad', 'brushes', 'paint', 'grapes', 'protein bars']

shopping_list.sort()
print(shopping_list)
#['apples', 'brushes', 'grapes', 'notepad', 'paint', 'protein bars']

list_2 = shopping_list + ['noodles','almonds']


print(list_2)
#['apples', 'brushes', 'grapes', 'notepad', 'paint', 'protein bars', 'noodles', 'almonds']
print(len(list_2))
#8

You might also like