Basic Python Programs

Basic Python Programs

Basic Python Programs

Basic Python Programs

Basic Python Programs

WhatsApp
LinkedIn
Pinterest

Basic Python Programs

Table of Contents

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.

  1. Using “print()” function directly
  2. 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: 

hello world python program - Basic Python Programs
hello world python program – Basic Python Programs

Output:

hello world python program - Basic Python Programs

 

Print hello world in python using a user defined function.

Input: 

hello world python program - Basic Python Programs
hello world python program

Output:

hello world python program - Basic Python Programs

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.F

 

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…

  1. string slicing notation
  2. Loops
  3. the reversed() function
  4. 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: 

reverse a string in python - Basic Python Programs
reverse a string in python – Basic Python Programs

Output: 

reverse a string in python output - Basic Python Programs
reverse a string in python output – Basic Python Programs

 

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: 

reverse a string in python - Basic Python Programs
reverse a string in python – Basic Python Programs

Output: 

reverse a string in python output - Basic Python Programs
reverse a string in python output

 

Reverse a String in Python using the reversed() function and join() method

The reversed() and join() method approach to reverse a string involves…

  1. using the reversed() function to create a reverse iterator for the original string
  2. 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: 

reverse a string in python - Basic Python Programs
reverse a string in python – Basic Python Programs

Output: 

reverse a string in python output - Basic Python Programs
reverse a string in python output

 

Reverse a String in Python using recursion

Following are the steps for reversing a string in python using recursion…

  1. Define a recursive function that takes a substring of the original string as input.
  2. Check if the length of the substring is 0 or 1. If so, return the substring as is.
  3. If the length of the substring is greater than 1, call the function recursively on a smaller substring.
  4. Combine the results of the recursive calls to form the reversed string.

Input: 

reverse a string in python - Basic Python Programs
reverse a string in python – Basic Python Programs

Output: 

reverse a string in python output - Basic Python Programs
reverse a string in python output

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:

palindrome python - Basic Python Programs
palindrome python – Basic Python Programs

Python code to check palindrome Using the reversed() and join() methods:

  1. Reverse the original string using the reversed() method and convert it to a list.
  2. Join the reversed list of characters into a string using the join() method.
  3. Compare the reversed string to the original string. If they are the same, the original string is a palindrome.

Input:

palindrome python - Basic Python Programs
palindrome python – Basic Python Programs

 

 

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.

  1. brute force
  2. Sieve of Eratosthenes
  3. 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

  1. Define a function is_prime that takes an integer n as input.
  2. Check if the value of n is less than 2. If it is, return False.
  3. Use a for loop to iterate over all integers from 2 to the square root of n (using int(n**0.5) + 1).
  4. 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.
  5. If none of the integers divide n evenly, then n is prime, so return True.

Input: 

prime numbers python - brute force - Basic Python Programs
prime numbers python – brute force – Basic Python Programs

 

 

python program to check prime numbers using Sieve of Eratosthenes

 

  1. Create a boolean list primes of size limit+1, with all values set to True.
  2. Set primes[0] and primes[1] to False, as they are not considered prime.
  3. Use a for loop to iterate over integers from 2 to the square root of limit (using int(limit**0.5) + 1).
  4. For each integer i in the loop, check if primes[i] is True.
  5. 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.
  6. Create a list of all prime numbers up to the limit by filtering the indices of the primes list that are True.
prime numbers python - Sieve of Eratosthenes - Basic Python Programs
prime numbers python – Sieve of Eratosthenes – Basic Python Programs

python program to check prime numbers using Miller-Rabin primality test

prime numbers python - Miller-Rabin primality test - Basic Python Programs
prime numbers python – Miller-Rabin primality test – Basic Python Programs

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

 

  1. Define the radius of the circle (a positive number).
  2. 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.
  3. Return the calculated area.

Input:

area of circle in python - Basic Python Programs
area of circle in python – Basic Python Programs

Output:

area of circle in python - Output - Basic Python Programs
area of circle in python – Output – Basic Python Programs

Find Area of circle in Python Using the math module’s pow() function

 

  1. Define a function area_of_circle that takes radius as a parameter.
  2. Use “pow()” function from the math module to calculate “r^2”  –  “r_squared = math.pow(radius, 2)”
  3. Multiply “pi” and “r^2” to get the area of the circle – “area = math.pi * r_squared”
  4. Return the area of the circle: return area

Input:

area of circle in python - Basic Python Programs
area of circle in python – Basic Python Programs

Output:

area of circle in python - Output - Basic Python Programs
area of circle in python – Output

Area of circle in Python Using the * operator to multiply pi and r^2

  1. Define a function called “area_of_circle” that takes the radius of the circle as a parameter: “def area_of_circle(radius)”
  2. 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:

area of circle in python - Basic Python Programs
area of circle in python – Basic Python Programs

Output:

area of circle in python - Output - Basic Python Programs
area of circle in python – Output

Area of circle in Python Using a lambda function

 

  1. Import the “math” module which contains the constant “pi” and the “pow()” function
  2. Define a “lambda” function that takes a single argument “radius” and returns the “area of a circle” with that radius
  3. Call the “lambda” function with a “radius” value to calculate the “area of a circle”

Input:

area of circle in python - Basic Python Programs
area of circle in python – Basic Python Programs

Output:

area of circle in python - Output - Basic Python Programs
area of circle in python – Output

 

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:

generate a random number in python - input - Basic Python Programs
generate a random number in python – input – Basic Python Programs

 

 

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:

generate a random number in python - Basic Python Programs
generate a random number in python – Basic Python Programs

 

 

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:

generate a random number in python - Basic Python Programs
generate a random number in python – Basic Python Programs

 

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…

  1. using the “open()” function with the “read()” method
  2. using a “for loop” with “open()”
  3. 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

  1. In this approach, we open the file in read mode using the “open()” function.
  2. Then use the “read()” method to read the entire contents of the file into a “string variable” data.
  3. Print

Code: 

read from a file in python - Basic Python Programs
read from a file in python – Basic Python Programs

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: 

read from a file in python - Basic Python Programs
read from a file in python – Basic Python Programs

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: 

read from a file in python - Basic Python Programs
read from a file in python – Basic Python Programs

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,

  1. using the built-in “open()” function
  2. the “write()” method
  3. 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…

  1. First use the open() function to create / open a file named “myfile.txt”.
  2. Open it up in “w” / writing mode.
  3. Now, use the write() function to write the text / numbers data on the file.
  4. Close the file using the close() function.

Code: 

write a file in python - Basic Python Programs
write a file in python – Basic Python Programs

Write a file in Python Using a context manager with the with statement

 

  1. We establish a context manager using the “with” expression.
  2. The file closes automatically.
  3. Create a new file and open it in “write” mode using “open()”.
  4. Write text to the file with “write()”.

Code: 

write a file in python - Basic Python Programs
write a file in python – Basic Python Programs

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.

delete a file in python - Basic Python Programs
delete a file in python – Basic Python Programs

 

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.

delete a file in python - Basic Python Programs
delete a file in python – Basic Python Programs

 

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.

delete a file in python - Basic Python Programs
delete a file in python – Basic Python Programs

 

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!!

Aniket

Aniket

Leave a Reply

Your email address will not be published. Required fields are marked *

Blogs You May Like

Get in touch to claim Best Available Discounts.

If You Are Looking for Job Assistance Please Fill Up the Form.

× How can I help you?