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!!
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.
Print hello world in python using a user defined function.
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…
- string slicing notation
- the reversed() function
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.
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.
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.
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.
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”.
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.
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.
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 and primes 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.
python program to check prime numbers using Miller-Rabin primality test
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.
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
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.
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”
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.
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.
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).
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.
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.
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.
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.
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()”.
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 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 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.
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!!