Python Fundamentals: Strings, Lists, Math, and Plotting Examples
P1: Python String Manipulation Techniques
Demonstrating String Operations
s = "hello"
print(s.capitalize())
print(s.upper())
print(s.rjust(100))
print(s.center(100))
print(s.replace('l','(M)'))
print(s)
print("don't")
Indexing
a = 'symbiosis2024'
print(a[2])
Negative Indexing
print(a[-1])
print(a[-6])
Slicing
print(a[9:12])
print(a[9:])
print(a[9:-1])
print(a[:8])
print(a[-12:-1])
Stride [start index:end index:step size]
print(a[0:13:2])
print(a[0::2])
Concatenation
b = 'hello'
c = 'world'
d = b + c
print(d)
e = b + " " + c
print(e)
Repetition
f = a * 3
print(f)
g = "2024"
print(g * 2)
print(a + '2')
Reversing a String
print(a[::-1])
Split
h = "sspu"
print(h.split()) # Returns a list
i = "05/08/2024"
print(i.split("/"))
j = "14:20:25"
print(j.split(":"))
P2: Essential Python List Operations
Concatenation and Repetition on Lists
L1 = [1, '2', 3.0]
L2 = [4, '5', 6.0]
L3 = L1 + L2 # Concatenation
print(L3)
L4 = L2 + L1
print(L4)
L5 = L1 * 3 # Repetition
print(L5)
Modifying Lists (Append, Insert, Pop, Remove, Del)
lis = [1, 4, 3, 2, 5]
lis.append('sspu')
print(lis)
lis.insert(2, 'hello')
print(lis)
lis.pop()
print(lis)
lis.remove(3)
print(lis)
del(lis[3])
print(lis)
Indexing
l1 = [1, 2, 3, 5, 4, 6, 7, 8]
print(l1[0])
print(l1[5])
print(l1[-1])
print(l1[-3])
Slicing
print(l1[3:6])
print(l1[3:])
print(l1[:6])
print(l1[:])
Stride
print(l1[0:7:2])
print(l1[0:7:3])
print(l1[::2])
print(l1[::3])
Membership Testing: 'in' and 'not in'
lis2 = [1, 4, 3, 2, 5]
if 4 in lis2:
print("List has element 4")
else:
print("List does not have element 4")
if 6 not in lis2:
print("List does not have element 6")
else:
print('List has element 6')
P3: Advanced String Programming Examples
Program to Reverse a Given String
Using a loop:
s = input("Enter some string:")
i = len(s) - 1
target = ''
while i >= 0:
target = target + s[i]
i = i - 1
print(target)
Using slicing (Pythonic way):
print(s[::-1]) # Using stride
Reverse Internal Contents of Each Word in a Sentence
s2 = input("Enter some string:")
l = s2.split()
li = []
i = 0
while i < len(l):
li.append(l[i][::-1])
i = i + 1
output = ' '.join(li)
print(output)
Check if a String is a Palindrome
s3 = input("Enter some string:")
s3 = s3.replace(" ", "").lower()
i = 0
length = len(s3) - 1
is_palindrome = True
while i < length:
if(s3[i] != s3[length]):
is_palindrome = False
break
i += 1
length -= 1
if (is_palindrome):
print("The string is palindrome")
else:
print("The string is not palindrome")
P4: Number Theory: Prime Numbers and Factors
Check Whether a Number is Prime or Composite
num = int(input("Enter a number:"))
i = 2
is_prime = True
if num == 1:
print("Neither prime nor composite")
elif num > 1:
while (i < num):
if(num % i == 0):
is_prime = False
break
i += 1
if(is_prime):
print("The number is prime")
else:
print("The number is composite")
Find Factors of a Number and Display Their Count
num3 = int(input("Enter a number:"))
k = 1
factors = 0
print("Factors of", num3, ":")
while (k <= num3):
if(num3 % k == 0):
print(k)
factors += 1
k += 1
print("The number of factors are:", factors)
Find All Two-Digit Prime Numbers and Display Count
num2 = 10
primes = 0
while (num2 < 100):
is_prime2 = True
j = 2
while (j < num2):
if (num2 % j == 0):
is_prime2 = False
break
j += 1
if (is_prime2):
primes += 1
num2 += 1
print("Total two-digit primes:", primes)
P5: Calculating HCF (GCD) and LCM
Find Highest Common Factor (HCF)
def find_hcf(x, y):
hcf = 1 # Initialize HCF to 1
for i in range(1, min(x, y) + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
hcf_result = find_hcf(num1, num2)
print("The highest common factor of the entered numbers is", hcf_result)
Find Least Common Multiple (LCM)
def find_lcm(a, b):
max_num = max(a, b)
while True:
if max_num % a == 0 and max_num % b == 0:
return max_num
max_num += 1
num3 = int(input("Enter a number: "))
num4 = int(input("Enter another number: "))
print("The L.C.M of", num3, "and", num4, "is", find_lcm(num3, num4))
P6: Number Reversal and Palindrome Check
Reversing an Integer
num = int(input("Enter a number: "))
def reversing_number(x):
reversed_num = 0
temp_x = x
while temp_x != 0:
digit = temp_x % 10
reversed_num = reversed_num * 10 + digit
temp_x = temp_x // 10
return(reversed_num)
print("The reversed number is", reversing_number(num))
Checking if a Number is a Palindrome
def palindrome_number(x, y):
if x == y:
print("The entered number is a palindrome.")
else:
print("The entered number is not a palindrome.")
palindrome_number(num, reversing_number(num))
P7: Data Visualization using Matplotlib and NumPy
Plotting Sine, Cosine, and Linear Functions
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.01)
plt.subplot(3, 3, 1)
plt.plot(x, np.sin(x), color='orange', linewidth = 3, marker = '.', markersize = 1, linestyle = "-")
plt.xlabel("Angle")
plt.ylabel("Magnitude")
plt.title("Sine Wave")
plt.subplot(3, 3, 3)
plt.plot(x, np.cos(x), color="blue", linewidth = 3, marker = ",", markersize = 1, linestyle = "--")
plt.xlabel("Angle")
plt.ylabel("Magnitude")
plt.title("Cosine Wave")
plt.subplot(3, 3, 7)
plt.plot(x, x, color = "red", linewidth = 2, marker = "o", markersize = 1, linestyle = "-.")
plt.xlabel("Values of x")
plt.ylabel("Values of y")
plt.title("Line: y=x")
plt.subplot(3, 3, 9)
plt.plot(x, 5 - x, color="purple", linewidth = 1, marker = "1", markersize = 1, linestyle = ":")
plt.xlabel("Values of x")
plt.ylabel("Values of y")
plt.title("Line: y=5-x")
plt.show()
English with a size of 6.74 KB