0% found this document useful (0 votes)
27 views

python practical

python codes

Uploaded by

racer9309
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)
27 views

python practical

python codes

Uploaded by

racer9309
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
You are on page 1/ 12

Section 1: Basic Python Programs

1. Python program to print Hello world!

print("Hello, world!")

2. Python program to add two numbers

# Add two numbers


num1 = 3
num2 = 5
sum = num1 + num2
print("The sum is:", sum)

3. Python program to find the square root

import math

# Find the square root


num = 16
sqrt = math.sqrt(num)
print("The square root is:", sqrt)

4. Python program to calculate the area of a triangle

# Calculate area of a triangle


base = 5
height = 10
area = 0.5 * base * height
print("The area of the triangle is:", area)

5. Python program to swap two variables

# Swap two variables


a=5
b = 10
a, b = b, a
print("a =", a, "b =", b)
Section 2: Python Conversion Programs

1. Python program to convert kilometres to miles

#Convert kilometers to miles


km = 5
miles = km * 0.621371
print(km, "kilometers is equal to", miles, "miles")

2. Python program to convert Celsius to Fahrenheit

# Convert Celsius to Fahrenheit


celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(celsius, "degrees Celsius is equal to", fahrenheit, "degrees Fahrenheit")

3. Python program to convert decimal to binary, octal and hexadecimal

# Convert decimal to binary, octal and hexadecimal


decimal = 10
print("Binary:", bin(decimal))
print("Octal:", oct(decimal))
print("Hexadecimal:", hex(decimal))

4. Python program to find ASCII value of character

# Find ASCII value of character


char = 'A'
print("The ASCII value of", char, "is", ord(char))
5. Python program to implement type conversion

# Type conversion examples


integer = 10
float_num = float(integer)
string = str(integer)
print("Integer:", integer)
print("Converted to float:", float_num)
print("Converted to string:", string)

Section 3: Basic Mathematical Programs

1. Python program to check Armstrong number

# Check if a number is an Armstrong number

num = 153

sum = 0

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** 3

temp //= 10

if num == sum:

print(num, "is an Armstrong number")

else:

print(num, "is not an Armstrong number")


2. Python program to check if a number is odd or even

# Check if a number is odd or even

num = 4

if num % 2 == 0:

print(num, "is an even number")

else:

print(num, "is an odd number")

3. Python program to check leap year

#Check if a year is a leap year

year = 2020

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")


4. Python program to find the largest among three numbers

# Find the largest among three numbers

a=5

b = 10

c=8

largest = max(a, b, c)

print("The largest number is", largest)

5. Python program to check prime number

# Check if a number is prime

num = 29

if num > 1:

for i in range(2, int(num / 2) + 1):

if (num % i) == 0:

print(num, "is not a prime number")

break

else:

print(num, "is a prime number")

else:

print(num, "is not a prime number")


Section 4: Python program on list

1. Python program to check if a list is empty

def is_list_empty(lst):
return not lst

my_list = []
print("Is the list empty?", is_list_empty(my_list))

2. Python program to access index of a list using for loop

my_list = ['a', 'b', 'c']

for index, value in enumerate(my_list):

print("Index:", index, "Value:", value)

3. Python program to slice list

my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
print("Sliced List:", sliced_list)

4. Python program to concatenate two lists

list1 = [1, 2, 3]

list2 = [4, 5, 6]

concatenated_list = list1 + list2

print("Concatenated List:", concatenated_list)


5. Python program to remove duplicate element from a list

my_list = [1, 2, 2, 3, 4, 4, 5]

unique_list = list(set(my_list))

print("List without duplicates:", unique_list)

Section 5: Python program on dictionary

1. Python program to merge two dictionaries

dict1 = {'a': 1, 'b': 2}

dict2 = {'c': 3, 'd': 4}

merged_dict = {**dict1, **dict2}

print("Merged Dictionary:", merged_dict)

2. Python program to iterate over dictionary using for loop

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():

print("Key:", key, "Value:", value)


3. Python program to sort a dictionary by value

my_dict = {'a': 3, 'b': 1, 'c': 2}

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print("Sorted Dictionary by Value:", sorted_dict)

4. Python program to delete an element from a dictionary

my_dict = {'a': 1, 'b': 2, 'c': 3}

if 'b' in my_dict:

del my_dict['b']

print("Dictionary after deletion:", my_dict)

5. Python program to check if a key is already present in a dictionary

my_dict = {'a': 1, 'b': 2, 'c': 3}

key_to_check = 'b'

if key_to_check in my_dict:

print(f"Key '{key_to_check}' is present in the dictionary.")

else:

print(f"Key '{key_to_check}' is not present in the dictionary.")


Section 6: Python program on string

1. Python program to check if given string is palindrome or not

def is_palindrome(s):

return s == s[::-1]

my_string = "radar"

print("Is the string palindrome?", is_palindrome(my_string))

2. Python program to capitalize the first character of a string

my_string = "hello world"

capitalized_string = my_string.capitalize()

print("Capitalized String:", capitalized_string)

3. Python program to compute all the Permutation of the String

from itertools import permutations

my_string = "abc"

perm = [''.join(p) for p in permutations(my_string)]

print("All Permutations:", perm)


4. Python program to create a countdown timer

import time

def countdown(seconds):

while seconds:

mins, secs = divmod(seconds, 60)

timer = '{:02d}:{:02d}'.format(mins, secs)

print(timer, end="\r")

time.sleep(1)

seconds -= 1

print("Time's up!")

countdown(10)

5. Python program to count the number of occurrences of a character in string

my_string = "hello world"

char_to_count = 'o'

count = my_string.count(char_to_count)

print(f"The character '{char_to_count}' occurs {count} times in the string.")


Section 7: Python program on tuple

1. Python program to find the size of a tuple

my_tuple = (1, 2, 3, 4, 5)
print("Size of the tuple:", len(my_tuple))

2. Python program for adding a tuple to list and vice-versa

my_list = [1, 2, 3]

my_tuple = (4, 5, 6)

# Adding tuple to list

combined_list = my_list + list(my_tuple)

print("List after adding tuple:", combined_list)

# Adding list to tuple

combined_tuple = tuple(my_list) + my_tuple

print("Tuple after adding list:", combined_tuple)

3. Python program to sort a list of tuples in increasing order by the last element in each
tuple

my_list_of_tuples = [(1, 3), (2, 2), (3, 1)]

sorted_list_of_tuples = sorted(my_list_of_tuples, key=lambda x: x[-1])

print("Sorted list of tuples:", sorted_list_of_tuples)


4. Python program to assign frequency to tuples

from collections import Counter

my_tuple = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)

frequency = Counter(my_tuple)

print("Frequency of each element in the tuple:", frequency)

5. Python program to check if any list element is present in tuple

my_list = [5, 6, 7]

my_tuple = (1, 2, 3, 4, 5)

is_present = any(item in my_tuple for item in my_list)

print("Is any list element present in the tuple?", is_present)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy