Python 2
Python 2
How to Get Started with Python and Execute First Program in Python
Steps:
3. Open the terminal or command prompt, type python to enter the Python
interpreter.
print("Hello, World!")
Output:
Hello, World!
2. Start the Python Interpreter and Type help() to Start the Online Help Utility
Code:
help()
Output:
This will open the help utility, providing interactive help and documentation
about Python modules, functions, and objects.
3. Start a Python Interpreter and Use it as a Calculator
Code:
>>> 5 + 3
>>> 6 * 7
42
>>> 9 / 3
3.0
>>> 2 ** 3
Code:
filename = "example.txt"
lines = file.readlines()
print(line.strip())
Output:
Hello
World
Python
Python
World
if True:
Output:
Corrected Code:
if True:
6. Write a Program to Implement Half Adder, Full Adder, and Parallel Adder
Code:
return a ^ b, a & b
carry = 0
result = []
result.insert(0, sum_)
result.insert(0, carry).
return result.
print(half_adder(1, 0))
print(full_adder(1, 1, 0))
(1, 0)
(0, 1)
[1, 0, 0, 1]
Code:
A = P * (1 + R/100)**T
CI = A - P
Output:
Enter rate: 5
8. Given Coordinates (x1, y1), (x2, y2) Find the Distance Between Two Points
Code:
import math
x1, y1 = 1, 2
x2, y2 = 4, 6
print("Distance:", distance)
Output:
Distance: 5.0
Code:
print(f"Name: {name}")
print(f"Address: {address}")
print(f"Email: {email}")
print(f"Phone: {phone}")
Output:
Email: johndoe@example.com
Phone: 1234567890
10. Write a Program to Implement Digital Logic Gates – AND, OR, NOT, EX-OR
Code:
return a & b
return a | b
def NOT(a):
return ~a
return a ^ b
print(AND(1, 0))
print(OR(1, 0))
print(NOT(1))
print(XOR(1, 0))
Output: 0, 1, - 2, 1
Code:
print(f"{i} " * i)
Output:
44
333
2222
11111
12. Write a Python Code to Merge Two Given File Contents into a Third File
Code:
merged.write(file1.read())
merged.write(file2.read())
Output:
13. Write a Program to Check Whether the Given Input is Digit, Lowercase
Character, Uppercase Character, or a Special Character
Code:
if ch.isdigit():
print("Digit")
elif ch.islower():
print("Lowercase character")
elif ch.isupper():
print("Uppercase character")
else:
print("Special character")
Output:
Enter a character: a
Lowercase character
14. Write a Function that Reads a File file1 and Displays the Number of
Words, Number of Vowels, Blank Spaces, Lowercase Letters, and Uppercase
Letters
Code:
def file_analysis(filename):
content = file.read()
words = content.split()
print(f"Words: {len(words)}")
print(f"Vowels: {vowels}")
print(f"Spaces: {spaces}")
file_analysis('example.txt')
Output:
Words: 5
Vowels: 7
Spaces: 4
Lowercase letters: 15
Uppercase letters: 3
Here are the Python programs without the extra "Question" part:
15. Python Program to Print the Fibonacci sequence using while loop
n = int(input())
a, b = 0, 1
while a < n:
a, b = b, a + b
Output:
10
0112358
16. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
a = int(input())
b = int(input())
print("AND:", a & b)
print("OR:", a | b)
print("NOT:", ~a)
print("EX-OR:", a ^ b)
Output:
AND: 0
OR: 1
NOT: -2
EX-OR: 1
17. Python program to print all prime numbers in a given interval (use break)
start = 10
end = 20
if num % i == 0:
break
else:
11 13 17 19
18. Write a program to implement Half Adder, Full Adder, and Parallel Adder
sum = a ^ b
carry = a & b
sum = a ^ b ^ carry_in
Output:
19. Write a program to compute LCM of two numbers by taking input from
the user
import math
a = int(input())
b = int(input())
lcm = (a * b) // math.gcd(a, b)
print("LCM:", lcm)
Output:
5
LCM: 20
20. Write a GUI program to create a window wizard having two text labels,
two text fields, and two buttons as Submit and Reset
import tkinter as tk
window = tk.Tk()
window.title("Window Wizard")
label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
entry1 = tk.Entry(window)
entry1.grid(row=0, column=1)
entry2 = tk.Entry(window)
entry2.grid(row=1, column=1)
submit_button.grid(row=2, column=0)
reset_button.grid(row=2, column=1)
window.mainloop()
Output:
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print(num1 + num2)
Output:
$ python add.py 3 5
import scipy
from scipy import stats
print(scipy.__version__)
print(stats.norm.cdf(0))
Output:
1.9.3
0.5
import numpy as np
lst = [1, 2, 3, 4]
tup = (5, 6, 7, 8)
array_from_list = np.array(lst)
array_from_tuple = np.array(tup)
print(array_from_list)
print(array_from_tuple)
Output:
[1 2 3 4]
[5 6 7 8]
print(common_values)
Output:
[3 4]
25. Write a function called gcd that takes parameters a and b and returns
their greatest common divisor
import math
return math.gcd(a, b)
print(gcd(12, 15))
Output:
import scipy
print(scipy.__version__)
Output:
1.9.3
-2.0
27. Write a function called palindrome that takes a string argument and
returns True if it is a palindrome and False otherwise
def palindrome(string):
print(palindrome("madam"))
print(palindrome("hello"))
Output:
True
False
28. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
a = int(input())
b = int(input())
print("AND:", a & b)
print("OR:", a | b)
print("NOT:", ~a)
print("EX-OR:", a ^ b)
Output:
AND: 0
OR: 1
NOT: -2
EX-OR: 1
29. Find mean, median, mode for the given set of numbers in a list
import statistics
numbers = [1, 2, 2, 3, 4]
print("Mean:", statistics.mean(numbers))
print("Median:", statistics.median(numbers))
print("Mode:", statistics.mode(numbers))
Output:
Mean: 2.4
Median: 2
Mode: 2
30. Write a program for Creating a Pandas Series and Basic Operations on
Series
import pandas as pd
data = [1, 2, 3, 4]
series = pd.Series(data)
print(series)
print(series.mean())
Output:
0 1
1 2
2 3
3 4
dtype: int64
2.5
t = (1, 2, 3, 4)
print(t)
Output:
(1, 2, 3, 4)
32. Write a Python program to construct a Data Frame and explore Basic
Operations on DataFrame
import pandas as pd
df = pd.DataFrame(data)
print(df)
Output:
Name Age
0 Alice 24
1 Bob 27
2 Charlie 22
33. Write a Python program to create a tuple with different data types
print(t)
Output:
import pandas as pd
import plotly.express as px
df = pd.DataFrame(data)
fig.show()
Output:
Here are the Python programs for the tasks you've mentioned:
35. Write a Python program to check whether an element exists within a
tuple
t = (1, 2, 3, 4)
element = 3
print(element in t)
Output:
True
lst = [4, 1, 3, 2]
lst.sort()
print(lst)
Output:
[1, 2, 3, 4]
37. Write a function called is_sorted that takes a list as a parameter and
returns True if the list is sorted in ascending order and False otherwise
def is_sorted(lst):
print(is_sorted([1, 2, 3, 4]))
print(is_sorted([4, 3, 2, 1]))
Output:
True
False
import numpy as np
print("Square:", np.square(arr))
Output:
Add 2: [3 4 5 6]
Multiply by 2: [2 4 6 8]
Square: [1 4 9 16]
39. Write a function called has_duplicates that takes a list and returns True if
there is any element that appears more than once. It should not modify the
original list.
def has_duplicates(lst):
print(has_duplicates([1, 2, 3, 4]))
print(has_duplicates([1, 2, 2, 4]))
Output:
False
True
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 3, 2, 4]))
Output:
[1, 2, 3, 4]
ii) The wordlist I provided, words.txt, doesn’t contain single letter words. So
you might want to add “I”, “a”, and the empty string.
print(words)
Output:
iii) Write a python code to read dictionary values from the user. Construct a
function to invert its content. i.e., keys should be values and values should
be keys.
def invert_dict(d):
print(invert_dict(d))
Output:
word = "Apple"
print(",".join(word))
Output:
A,p,p,l,e
word = "Hello"
print(string.replace(word, ""))
Output:
world, again
iii) Write a function that takes a sentence as an input parameter and replaces
the first letter of every word with the corresponding uppercase letter and the
rest of the letters in the word by corresponding letters in lowercase without
using a built-in function
def capitalize_sentence(sentence):
words = sentence.split()
result = []
result.append(word[0].upper() + word[1:].lower())
return " ".join(result)
print(capitalize_sentence("hello world"))
Output:
Hello World
41. Writes a recursive function that generates all binary strings of n-bit
length
if len(s) == n:
print(s)
return
generate_binary_strings(n, s + "0")
generate_binary_strings(n, s + "1")
generate_binary_strings(3)
Output:
000
001
010
011
100
101
110
111
target = 30
if target in lst:
else:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
import numpy as np
print(arr[1:4])
Output:
[2 3 4]
45. Write a program to check whether a string is palindrome or not
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
print(is_palindrome("hello"))
Output:
True
False
import numpy as np
print(arr + 2)
print(np.mean(arr))
print(np.dot(arr, arr))
Output:
[3 4 5 6]
2.5
30
print(row)
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
47. ii) Write a Python program to perform addition of two square matrices.
print(row)
Output:
[6, 8]
[10, 12]
Output:
[19, 22]
print(add(5, 3))
print(subtract(5, 3))
print(multiply(5, 3))
print(divide(5, 3))
Output:
15
1.6666666666666667
lines = file.readlines()
print(line.strip())
50. Find the factorial of a number using recursion.
print(factorial(5))
Output:
120
import numpy as np
print(arr)
Output:
[1 2 3 4]
52. Write a function cumulative_product to compute cumulative product of a
list of numbers.
import numpy as np
print(cumulative_product([1, 2, 3, 4]))
Output:
[ 1 2 6 24]
53. Write a function that reads a file file1 and displays the number of words,
number of vowels, blank spaces, lower case letters, and uppercase letters.
def file_analysis(filename):
text = file.read()
words = text.split()
54. Write a function reverse to print the given list in the reverse order.
def reverse(lst): print(lst[::-1])
reverse([1, 2, 3, 4])
Output:
[4, 3, 2, 1]
55. Write a Python code to read text from a text file, find the word with most
number of occurrences.
def most_frequent_word(filename):
words = file.read().split()
most_common = Counter(words).most_common(1)
x=1/0
except Exception as e:
Output:
import geometry
print(geometry.area_of_circle(5))
print(geometry.area_of_rectangle(4, 6))
Output:
78.5
24
58. Write a program that raises an Exception (divide by zero error, voter’s
age validity).
try:
x=1/0
except ZeroDivisionError:
Output:
class A:
class B(A):
class C(B):
pass
C().method()
Output:
B method
60. Write a program that raises an Exception as string(), student mark range
validation.
def validate_marks(marks):
try:
validate_marks(150)
except ValueError as e:
print(e)
Output:
61. Write a Python code to merge two given file contents into a third file.
data1 = open('file1.txt').read()
data2 = open('file2.txt').read()
print(open('merged_file.txt').read())
file1.txt:
file2.txt:
62. Use the structure of exception handling for all general purpose
exceptions.
try:
x=1/0
except ZeroDivisionError:
print("ZeroDivisionError caught.")
except Exception as e:
Output:
ZeroDivisionError caught.
63. Write a Python code to merge two given file contents into a third file.
data1 = open('file1.txt').read()
data2 = open('file2.txt').read()
print(open('merged_file.txt').read())
file1.txt:
file2.txt:
64. Write a Python code to read a phone number and email-id from the user
and validate it for correctness.
Code:
import re
def validate_phone(phone):
pattern = r"^[0-9]{10}$"
def validate_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
Output:
65. Write a Python code to open a given file and construct a function to
check for given words present in it and display on found.
Code:
content = file.read()
if word in content:
Output:
Code:
root = Tk()
canvas.pack()
root.mainloop()
Output:
66. b. Add an attribute named color to your Rectangle objects and modify
draw_rectangle so that it uses the color attribute as the fill color.
Code:
class Rectangle:
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.color = color
root = Tk()
canvas.pack()
rect = Rectangle(50, 50, 150, 150, 'blue')
draw_rectangle(canvas, rect)
root.mainloop()
Output:
66. c. Write a function called draw_point that takes a Canvas and a Point as
arguments and draws a representation of the Point on the Canvas.
Code:
root = Tk()
canvas.pack()
root.mainloop()
Output:
66. d. Define a new class called Circle with appropriate attributes and
instantiate a few Circle objects. Write a function called draw_circle that draws
circles on the canvas.
Code:
class Circle:
self.y = y
self.radius = radius
self.color = color
root = Tk()
canvas.pack()
draw_circle(canvas, circle1)
draw_circle(canvas, circle2)
root.mainloop()
Output:
A window opens with two circles drawn on the canvas: one green and one
yellow.