Python Scripts For Beginners: Basic Operations

Collection of 100 Python scripts for beginners related to Basic Operations, each designed to help with fundamental tasks and provide useful examples.


100 Python Scripts For Beginners: Basic Operations

1. Hello World

print("Hello, World!")

Prints “Hello, World!” to the console.

2. Sum of Two Numbers

a = 5
b = 3
print(f"The sum is {a + b}")

Calculates and prints the sum of two numbers.

3. Subtraction of Two Numbers

a = 10
b = 4
print(f"The difference is {a - b}")

Calculates and prints the difference between two numbers.

4. Multiplication of Two Numbers

a = 7
b = 6
print(f"The product is {a * b}")

Calculates and prints the product of two numbers.

5. Division of Two Numbers

a = 20
b = 5
print(f"The quotient is {a / b}")

Calculates and prints the quotient of two numbers.

6. Integer Division

a = 20
b = 6
print(f"The integer division result is {a // b}")

Calculates and prints the integer division result.

7. Modulus Operation

a = 20
b = 6
print(f"The remainder is {a % b}")

Calculates and prints the remainder of division.

8. Power of a Number

a = 2
b = 3
print(f"{a} to the power of {b} is {a ** b}")

Calculates and prints the power of a number.

9. Absolute Value

a = -7
print(f"The absolute value is {abs(a)}")

Calculates and prints the absolute value of a number.

10. Square Root

import math
a = 16
print(f"The square root is {math.sqrt(a)}")

Calculates and prints the square root of a number.

11. Logarithm

import math
a = 100
print(f"The logarithm is {math.log10(a)}")

Calculates and prints the base-10 logarithm of a number.

12. Factorial of a Number

import math
a = 5
print(f"The factorial is {math.factorial(a)}")

Calculates and prints the factorial of a number.

13. Check Even or Odd

a = 7
if a % 2 == 0:
    print(f"{a} is even")
else:
    print(f"{a} is odd")

Checks if a number is even or odd.

14. Check Prime Number

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(11))

Checks if a number is prime.

15. Fibonacci Sequence

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b

fibonacci(10)

Prints the first n numbers in the Fibonacci sequence.

16. Factorial Using Recursion

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))

Calculates factorial using recursion.

17. List Sum

numbers = [1, 2, 3, 4, 5]
print(f"The sum of the list is {sum(numbers)}")

Calculates the sum of elements in a list.

18. List Average

numbers = [1, 2, 3, 4, 5]
print(f"The average is {sum(numbers) / len(numbers)}")

Calculates the average of elements in a list.

19. Find Maximum in List

numbers = [1, 5, 3, 9, 2]
print(f"The maximum value is {max(numbers)}")

Finds and prints the maximum value in a list.

20. Find Minimum in List

numbers = [1, 5, 3, 9, 2]
print(f"The minimum value is {min(numbers)}")

Finds and prints the minimum value in a list.

21. Reverse a List

numbers = [1, 2, 3, 4, 5]
print(f"The reversed list is {numbers[::-1]}")

Reverses and prints a list.

22. Sort a List

numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(f"The sorted list is {numbers}")

Sorts and prints a list.

23. Check if List Contains Element

numbers = [1, 2, 3, 4, 5]
print(3 in numbers)

Checks if a list contains a specific element.

24. Append to a List

numbers = [1, 2, 3]
numbers.append(4)
print(numbers)

Appends an element to a list.

25. Remove from a List

numbers = [1, 2, 3, 4]
numbers.remove(3)
print(numbers)

Removes an element from a list.

26. Join List into String

words = ['Hello', 'World']
print(' '.join(words))

Joins a list of strings into a single string.

27. Split String into List

text = "Hello World"
words = text.split()
print(words)

Splits a string into a list of words.

28. Dictionary Key Check

my_dict = {'a': 1, 'b': 2}
print('a' in my_dict)

Checks if a key exists in a dictionary.

29. Add Key-Value Pair to Dictionary

my_dict = {'a': 1}
my_dict['b'] = 2
print(my_dict)

Adds a new key-value pair to a dictionary.

30. Remove Key-Value Pair from Dictionary

my_dict = {'a': 1, 'b': 2}
del my_dict['a']
print(my_dict)

Removes a key-value pair from a dictionary.

31. Iterate Over Dictionary

my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

Iterates over key-value pairs in a dictionary.

32. Merge Two Dictionaries

dict1 = {'a': 1}
dict2 = {'b': 2}
merged_dict = {**dict1, **dict2}
print(merged_dict)

Merges two dictionaries.

33. Read from a File

with open('example.txt', 'r') as file:
    content = file.read()
print(content)

Reads content from a file.

34. Write to a File

with open('example.txt', 'w') as file:
    file.write("Hello, World!")

Writes a string to a file.

35. Append to a File

with open('example.txt', 'a') as file:
    file.write("Appending this line.")

Appends a string to an existing file.

36. Read File Line by Line

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

Reads a file line by line.

37. Count Lines in a File

with open('example.txt', 'r') as file:
    lines = file.readlines()
print(f"Number of lines: {len(lines)}")

Counts and prints the number of lines in a file.

38. Copy File

import shutil
shutil.copy('source.txt', 'destination.txt')

Copies a file from source to destination.

39. Delete File

import os
os.remove('example.txt')

Deletes a file.

40. Check File Existence

import os
print(os.path.exists('example.txt'))

Checks if a file exists.

41. Create a Directory

import os
os.makedirs('new_directory', exist_ok=True)

Creates a new directory.

42. List Files in Directory

import os
print(os.listdir('.'))

Lists all files and directories in the current directory.

43. Rename a File

import os
os.rename('old_name.txt', 'new_name.txt')

44. Get Current Working Directory

import os
print(os.getcwd())

Prints the current working directory.

45. Change Directory

import os
os.chdir('new_directory')
print(os.getcwd())

Changes the current working directory.

46. Calculate Length of String

text = "Hello, World!"
print(f"The length of the string is {len(text)}")

Calculates and prints the length of a string.

47. Convert String to Uppercase

text = "Hello, World!"
print(text.upper())

Converts a string to uppercase.

48. Convert String to Lowercase

text = "Hello, World!"
print(text.lower())

Converts a string to lowercase.

49. Strip Whitespace from String

text = "   Hello, World!   "
print(text.strip())

Removes leading and trailing whitespace from a string.

50. Replace Substring in String

text = "Hello, World!"
print(text.replace("World", "Python"))

Replaces a substring within a string.

51. Find Substring Index

text = "Hello, World!"
print(text.find("World"))

Finds and prints the index of a substring.

52. Count Substring Occurrences

text = "Hello, World! World!"
print(text.count("World"))

Counts the occurrences of a substring in a string.

53. Split String by Delimiter

text = "apple,banana,cherry"
print(text.split(","))

Splits a string into a list using a delimiter.

54. Join List into String

words = ['apple', 'banana', 'cherry']
print(','.join(words))

Joins a list of strings into a single string.

55. Convert List to Tuple

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)

Converts a list to a tuple.

56. Convert Tuple to List

my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)

Converts a tuple to a list.

57. Create a Set

my_set = {1, 2, 3}
print(my_set)

Creates and prints a set.

58. Add to a Set

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

Adds an element to a set.

59. Remove from a Set

my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)

Removes an element from a set.

60. Check if Set Contains Element

my_set = {1, 2, 3}
print(2 in my_set)

Checks if a set contains an element.

61. Set Union

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))

Finds the union of two sets.

62. Set Intersection

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.intersection(set2))

Finds the intersection of two sets.

63. Set Difference

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.difference(set2))

Finds the difference between two sets.

64. Set Symmetric Difference

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.symmetric_difference(set2))

Finds the symmetric difference between two sets.

65. List Comprehension

squares = [x ** 2 for x in range(10)]
print(squares)

Creates a list of squares using list comprehension.

66. Dictionary Comprehension

squares = {x: x ** 2 for x in range(5)}
print(squares)

Creates a dictionary of squares using dictionary comprehension.

67. Check Key in Dictionary

my_dict = {'a': 1, 'b': 2}
print('a' in my_dict)

Checks if a key exists in a dictionary.

68. Get Value from Dictionary

my_dict = {'a': 1, 'b': 2}
print(my_dict.get('a'))

Retrieves the value for a given key from a dictionary.

69. Merge Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)

Concatenates two lists.

70. List Multiplication

my_list = [1, 2, 3]
result = my_list * 3
print(result)

Repeats the elements of a list.

71. Dictionary Keys

my_dict = {'a': 1, 'b': 2}
print(my_dict.keys())

Prints the keys of a dictionary.

72. Dictionary Values

my_dict = {'a': 1, 'b': 2}
print(my_dict.values())

Prints the values of a dictionary.

73. Dictionary Items

my_dict = {'a': 1, 'b': 2}
print(my_dict.items())

Prints the items (key-value pairs) of a dictionary.

74. Create a Class

 class cl:  
def __init__(self, value): self.value = value def display(self): print(self.value) obj = MyClass(10) obj.display()

Defines and uses a simple class.

75. Inheritance

class Parent:
    def greet(self):
        print("Hello")

class Child(Parent):
    def greet(self):
        print("Hi")

obj = Child()
obj.greet()

Demonstrates inheritance and method overriding.

76. Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Handles division by zero exception.

77. Try Except Else

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Result is {result}")

Uses else in exception handling.

78. Finally Block

try:
    result = 10 / 2
finally:
    print("Execution completed.")

Executes code in the finally block.

79. File Read Lines

with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

Reads and prints lines from a file.

80. Check if File is Empty

import os
if os.path.getsize('example.txt') == 0:
    print("File is empty")
else:
    print("File is not empty")

Checks if a file is empty.

81. Write List to File

my_list = ['apple', 'banana', 'cherry']
with open('fruits.txt', 'w') as file:
    for item in my_list:
        file.write(f"{item}\n")

Writes a list of items to a file, one per line.

82. Read First N Lines of File

with open('example.txt', 'r') as file:
    for _ in range(5):
        print(file.readline().strip())

Reads and prints the first N lines of a file.

83. Read File in Binary Mode

with open('example.txt', 'rb') as file:
    content = file.read()
    print(content)

Reads a file in binary mode.

84. Write File in Binary Mode

with open('example.bin', 'wb') as file:
    file.write(b"Hello, World!")

Writes binary data to a file.

85. Get File Size

import os
print(f"File size: {os.path.getsize('example.txt')} bytes")

Gets the size of a file.

86. Find Maximum in List

numbers = [1, 3, 5, 7, 9]
print(max(numbers))

Finds and prints the maximum value in a list.

87. Find Minimum in List

numbers = [1, 3, 5, 7, 9]
print(min(numbers))

Finds and prints the minimum value in a list.

88. Create and Append to File

with open('example.txt', 'a') as file:
    file.write("New line added.")

Appends a new line to a file.

89. Remove Directory

import os
os.rmdir('new_directory')

Removes an empty directory.

90. Check If Directory Exists

import os
print(os.path.isdir('new_directory'))

Checks if a directory exists.

91. List All Files and Directories

import os
for item in os.listdir('.'):
    print(item)

Lists all files and directories in the current directory.

92. Create Empty File

with open('empty_file.txt', 'w') as file:
    pass

Creates an empty file.

93. Check File Type

import mimetypes
print(mimetypes.guess_type('example.txt')[0])

Checks the MIME type of a file.

94. Create and Use a Virtual Environment

python -m venv myenv
source myenv/bin/activate  # On Windows use `myenv\Scripts\activate`

Creates and activates a virtual environment.

95. Install a Package Using Pip

pip install requests

Installs a package using pip.

96. Uninstall a Package Using Pip

pip uninstall requests

Uninstalls a package using pip.

97. Display Python Version

import sys
print(sys.version)

Displays the current Python version.

98. Run Script from Command Line

bash python script.py

Runs a Python script from the command line.

99. Measure Execution Time

import time
start_time = time.time()
# Code to measure
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")

Measures the execution time of a code block.

100. Simple HTTP Server

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()

Starts a simple HTTP server.

This collection of 100 Python scripts for beginners is designed to enhance your understanding of basic operations with practical examples.

1 comment

comments user
Tanoi

Awesome work

Post Comment