Basic Python Programs
Want to learn Python? Python is great for newbies & pros alike. Writing basic Python programs is a great way to learn. We'll teach you some basic Python applications in this blog. We'll cover "Hello World," prime number generation, number factorials, and more. These simple, powerful Python programs will teach you loops, functions, and conditionals. This blog will teach you fundamental Python programming and prepare you for more advanced subjects. Grab your favorite drink and delve into Python programming!
If are hyped up about the Python language, check out our course. Technogeeks can guide you through the roadmap of a Python developer. So, click on the link below and enter the awesome world of Python Programming!!
Click on the link below!
Hello World Python Program
A simple program that prints "hello world" in Python. It is a starting program for almost every programming language.
For this program, we are going to use a simple built-in function – "print()". Now, there are two ways to print "Hello world" in Python.
Using "print()" function directly
Using a UDF (User Defined Function)
In this code, we define a function called "hello_world" that simply prints "Hello, world!" to the console. We then call the function using "hello_world()" and it will execute the code inside the function, printing the message to the console.
Print hello world in python using only the "print()" statement.
Input: print("Hello, World!")
Output: Hello, World!
Print hello world in python using a user defined function.
Input: def print_hello():
print("Hello, World!")
print_hello()
Output: Hello, World!
Here we used the "print()" function. The "print()" function displays anything we put into the brackets. In this case, we gave the string "Hello, World!" to it.
Reverse a String in Python Program
Reversing a string or number is a common programming task that involves changing the order of its characters or digits. You can easily reverse a string in Python using…
string slicing notation
Loops
the reversed() function
recursion.
Reversing a number in Python requires converting it to a string first and then reversing the resulting string.
Reverse a String in Python using string slicing notation
This approach selects a range of characters from the original string, starting from the end and moving backwards with a step size of -1. This creates a new string with the characters in reverse order.
Input: text = "Hello, World!"
reversed_text = text[::-1]
print(reversed_text)
output - !dlroW ,olleH
Reverse a String in Python using a Loop
Looping through the original string's characters and adding them to a new string in reverse order reverses a string.
Initialize an empty string loop over the old string's characters, adding them to the new
string.
This produces a string containing reversed characters.
Examine equality.
Input: text = "Hello, World!"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(reversed_text)
output - !dlroW ,olleH
Reverse a String in Python using the reversed() function and join() method
The reversed() and join() method approach to reverse a string involves…
using the reversed() function to create a reverse iterator for the original string
using the join() method to concatenate the characters in the reverse iterator into a new
string.
Specifically, we use the syntax "".join(reversed(s))" to create a new string with the
characters in reverse order.
Input:
text = "Hello, World!"
reversed_text = ''.join(reversed(text))
print(reversed_text)
Output:
!dlroW ,olleH
Reverse a String in Python using recursion
Following are the steps for reversing a string in python using recursion…
Define a recursive function that takes a substring of the original string as input.
Check if the length of the substring is 0 or 1. If so, return the substring as is.
If the length of the substring is greater than 1, call the function recursively on a smaller
substring.
Combine the results of the recursive calls to form the reversed string.
Input: def reverse_string(s):
# Base case
if len(s) <= 1:
return s
# Recursive case
return reverse_string(s[1:]) + s[0]
# Example
text = "Hello, World!"
result = reverse_string(text)
print(result)
Output: !dlroW ,olleH
All of these approaches will produce the same output, which is the reverse of the original string. You can choose the approach that you find most readable or suitable for your specific use case.
Python program to check if a given string is a palindrome or not
Create a program in Python to determine whether a given string is a palindrome or not.
A palindrome is a word, phrase, number, or other set of characters that reads the same
forward and backward.
For Example – "racecar" or "madam".
This program takes in a "string" and checks for palindrome.
Python code to check palindrome Using string slicing notation
In this approach, we use slicing notation "[::-1]" to reverse the original string s.
We then compare the reversed string to the original string using the == operator.
If the two strings are same, the original string is a palindrome & the function returns
"True".
Otherwise, the original string is not a palindrome and the function returns "False".
Input: def is_palindrome(s):
return s == s[::-1]
# Example
text = "madam"
result = is_palindrome(text)
print(result)
output - True
Python code to check palindrome Using the reversed() and join() methods:
Reverse the original string using the reversed() method and convert it to a list.
Join the reversed list of characters into a string using the join() method.
Compare the reversed string to the original string. If they are the same, the original
string is a palindrome.
Input: def is_palindrome(s):
reversed_str = ''.join(reversed(s))
return s == reversed_str
# Example
text = "madam"
result = is_palindrome(text)
print(result)
output - True
Python program to check prime numbers
Check whether a number is prime or not using Python code for prime numbers. In this course, we'll go through many methods for using Python to figure out whether a particular integer is prime.
brute force
Sieve of Eratosthenes
Miller-Rabin primality test
Let's take a deep dive into Python's prime number library!
python program to check prime numbers using Brute Force method
Define a function is_prime that takes an integer n as input.
Check if the value of n is less than 2. If it is, return False.
Use a for loop to iterate over all integers from 2 to the square root of n (using
int(n**0.5) + 1).
For each integer in the loop, check if it divides n evenly (using the modulo operator %). If
it does, return False, as the number is not prime.
If none of the integers divide n evenly, then n is prime, so return True.
Input:
def is_prime(n):
# Check if number is less than 2
if n < 2:
return False
# Check from 2 to sqrt(n)
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Example
num = 29
result = is_prime(num)
print(result)
output - True
python program to check prime numbers using Sieve of Eratosthenes
Create a boolean list primes of size limit+1, with all values set to True.
Set primes[0] and primes[1] to False, as they are not considered prime.
Use a for loop to iterate over integers from 2 to the square root of limit (using
int(limit**0.5) + 1).
For each integer i in the loop, check if primes[i] is True.
If primes[i] is True, mark all multiples of i as False in the primes list, starting from i*i
and incrementing by i each time, using another loop.
Create a list of all prime numbers up to the limit by filtering the indices of the primes
list that are True.
input - def sieve_of_eratosthenes(n):
# Step 1: Assume all numbers are prime
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
# Step 2: Mark multiples as non-prime
for i in range(2, int(n**0.5) + 1):
if is_prime[i]:
for j in range(i *
i, n + 1, i):
is_prime[j]
= False
# Step 3: Collect all prime numbers
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
return primes
# Example
num = 30
result = sieve_of_eratosthenes(num)
print(result)
output - [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
python program to check prime numbers using Miller-Rabin primality test
input - import random
def miller_rabin(n, k=5):
# Handle small cases
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# Write n-1 as d * 2^r
d = n - 1
r = 0
while d % 2 == 0:
d //= 2
r += 1
# Perform k tests
for _ in range(k):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
# Example
num = 29
result = miller_rabin(num)
print(result)
output - True
Area of circle in Python Program
Formula: area = pi * r^2 where r is the radius of the circle and pi is the mathematical constant pi (3.14159)
Area of circle in Python Using the formula
Define the radius of the circle (a positive number).
If you know the radius of a circle and the mathematical number pi (about 3.14159), you can
use the calculation "area = pi * r2" to get the circle's surface area.
Return the calculated area.
Input:
import math
def area_of_circle(r):
return math.pi * r * r
# Example
radius = 5
area = area_of_circle(radius)
print(area)
Output: 78.53981633974483
Find Area of circle in Python Using the math module's pow() function
Define a function area_of_circle that takes radius as a parameter.
Use "pow()" function from the math module to calculate "r^2" – "r_squared = math.pow(radius,
2)"
Multiply "pi" and "r^2" to get the area of the circle – "area = math.pi * r_squared"
Return the area of the circle: return area
Input: import math
def area_of_circle(radius):
r_squared = math.pow(radius, 2)
area = math.pi * r_squared
return area
# Example
radius = 5
result = area_of_circle(radius)
print(result)
Output: 78.53981633974483
Area of circle in Python Using the * operator to multiply pi and r^2
Define a function called "area_of_circle" that takes the radius of the circle as a parameter:
"def area_of_circle(radius)"
Calculate the area of the circle using the formula "area = pi * r^2"; Where "pi" is the
mathematical constant pi (3.14159) and "r" is the radius of the circle.
Input: def area_of_circle(radius):
pi = 3.14159
area = pi * radius * radius
return area
# Example
radius = 5
result = area_of_circle(radius)
print(result)
Output:
78.53975
Area of circle in Python Using a lambda function
Import the "math" module which contains the constant "pi" and the "pow()" function
Define a "lambda" function that takes a single argument "radius" and returns the "area of a
circle" with that radius
Call the "lambda" function with a "radius" value to calculate the "area of a circle"
Input: import math
# Lambda function
area_of_circle = lambda radius: math.pi * math.pow(radius, 2)
# Example
radius = 5
result = area_of_circle(radius)
print(result)
Output:
78.53981633974483
Generate a random number in Python Program
The program generates a random number in Python using a random number generator. There are multiple ways to generate a random number in Python..
secrets module
numpy module
Random module
The program's goal is to demonstrate how to generate a random number in Python using one of these approaches.
Generate a Random Number in Python Using the Random Module
The "random" module is a built-in Python module that allows you to generate random
numbers.
To use the "random" module, you first need to import it at the beginning of your code.
The "random" module has a method – "randint(a, b)". This method can generate a random
integer between two given integers "a" and "b".
In this approach, we use the "randint(a, b)" method to generate a random integer between 1
and 100.
Input: import random
# Generate a random number between 1 and 100
random_number = random.randint(1, 100)
print(random_number)
output - 57
Generate a Random Number in Python Using the secrets module
The "secrets" module is a Python standard library module that is used for generating
cryptographically secure random numbers.
The "secrets.randbelow(n)" function generates a random integer in the range "[0, n)" using a
secure random number generator.
The "secrets.choice(seq)" function can also be used to randomly select an item from a
sequence (e.g. list, tuple, string) using a secure random number generator.
The "secrets" module uses an underlying cryptographic module in the Python standard library
to generate random numbers, which ensures that the generated numbers are highly
unpredictable and secure.
"random" module is suitable for non-cryptographic use cases. "secrets" module is
specifically designed for generating random numbers in cryptographic applications.
Input: import secrets
# Generate a random number between 1 and 100
random_number = secrets.randbelow(100) + 1
print(random_number)
output - 42
Generate a Random Number in Python Using the numpy module
"numpy" is a Python library used for scientific computing and data analysis.
It provides a random module that allows you to generate random numbers –
"numpy.random.randint()".
In this approach, we use the "numpy.random.randint()" function to generate a random integer
between 1 and 100 (inclusive).
Input: import numpy as np
# Generate a random integer between 1 and 100
random_number = np.random.randint(1, 101)
print(random_number)
output - 73
Read a file in Python Program
Learn how to "read" from a file with this sample Python application. A file may be read in one of 3 ways in Python…
using the "open()" function with the "read()" method
using a "for loop" with "open()"
and using the "readlines()" method
The file's contents are read into a "string" or "list" variable for subsequent processing. When working with files in Python, it's crucial to ensure that they are closed correctly after being read to prevent data corruption and file locking problems.
Read a file in Python Using open() function with read() method
In this approach, we open the file in read mode using the "open()" function.
Then use the "read()" method to read the entire contents of the file into a "string
variable" data.
Print
Code: # Open the file in read mode
file = open("example.txt", "r")
# Read the entire content
content = file.read()
# Print the content
print(content)
# Close the file
file.close()
Read a file in Python Using open() function with a for loop
The "open()" method opens the file in read mode again, but this time we use a "for loop" to cycle over each line. The console displays each line.
Code:
# Open the file in read mode
file = open("example.txt", "r")
# Read file line by line
for line in file:
print(line.strip())
# Close the file
file.close()
Read a file in Python Using readlines() method
"open()" opens the file in read mode, and "readlines()" reads all the lines into a "list variable" lines. We print the list.
Code:
# Open the file in read mode
file = open("example.txt", "r")
# Read all lines into a list
lines = file.readlines()
# Print each line
for line in lines:
print(line.strip())
# Close the file
file.close()
Write a file in Python Program
This program demonstrates how to write a text file in Python using different approaches. File handling in Python is various operations performed on a file, including reading & writing a file in Python. In this program, we focus specifically on writing to a file in Python,
using the built-in "open()" function
the "write()" method
the "print()" function with a file argument
Writing to a file is a fundamental operation in many programming tasks, as it allows us to store and manipulate data across different sessions or applications.
Write a file in Python Using the open() function and the write() method
This approach has a simple flow…
First use the open() function to create / open a file named "myfile.txt".
Open it up in "w" / writing mode.
Now, use the write() function to write the text / numbers data on the file.
Close the file using the close() function.
Code:
# Open the file in write mode
file = open("example.txt", "w")
# Write content to the file
file.write("Hello, this is a sample file.\n")
file.write("Welcome to Python file handling.")
# Close the file
file.close()
Write a file in Python Using a context manager with the with statement
We establish a context manager using the "with" expression.
The file closes automatically.
Create a new file and open it in "write" mode using "open()".
Write text to the file with "write()".
Code:
with open("example.txt", "w") as file:
file.write("Hello, this is a sample file.\n")
file.write("Welcome to Python file handling.")
Delete a file in Python Program
Python has numerous ways to remove files. The "os.remove()" method deletes the file at the specified location. The "pathlib.Path.unlink()" function also accepts the file path and deletes it. To remove the file, use "os.unlink()". If the file doesn't exist at the supplied location, these methods will generate a "FileNotFoundError", therefore error handling code is necessary. Python's built-in methods and modules make file deletion easy.
Delete a file in Python Using os.remove()
This approach uses the os module's remove() function to delete the file at the specified file path.
code - import os
file_path = "example.txt"
# Check if file exists before deleting
if os.path.exists(file_path):
os.remove(file_path)
print("File deleted successfully.")
else:
print("File does not exist.")
Delete a file in Python Using pathlib.Path.unlink()
This approach uses the pathlib module's Path object to represent the file path, and then calls the unlink() method to delete the file.
code - from pathlib import Path
file_path = Path("example.txt")
# Check if file exists before deleting
if file_path.exists():
file_path.unlink()
print("File deleted successfully.")
else:
print("File does not exist.")
Delete a file in Python Using os.unlink()
This approach is similar to the first approach, but uses the os module's unlink() function instead of remove() to delete the file.
input - import os
file_path = "example.txt"
# Check if file exists before deleting
if os.path.exists(file_path):
os.unlink(file_path)
print("File deleted successfully.")
else:
print("File does not exist.")
Conclusion
In conclusion, learning Python programming requires fundamental Python applications. By learning Python's loops, functions, and conditionals, you'll be ready to tackle increasingly difficult programming problems.
We've covered "Hello World," prime number generation, factorial calculation, and more in this blog. These simple, powerful programs will provide the groundwork for Python programming.
Python is a great language! Whether you want to make apps, pursue a software development profession, or learn something new, Python will help you. Python is utilized in data research, web development, and other industries because of its simplicity of use and adaptability.
Have Fun Coding!!