Basic Python Programs with Easy Examples

Photo of author

Tamal Maity

Updated:

5 min read
0
(0)

Python is a popular object-orientedgeneral-purpose, Interpreted, high-level programming language that can be used for a wide range of applications. Created in 1991 by Guido van Rossum.

To understand the basic programs, you should know about the Python Programming :

Basic Python Programs with code examples

Here are some examples of basic Python programs with code :

1. Print ” Hello World ”

Source Code :

# This program prints Hello, world!
print("Hello, World!")

Output

Hello, world!

This prints out the statement “Hello, World!” to the console. It demonstrates basic printing in Python. Here we use Python’s built-in ” print () ” function to print a string (Character of sequence).

2. Add Two Numbers

Source Code :

# This program add two numbers 

num1 = 10
num2 = 20

# Add two numbers
sum = num1 + num2

# Display the result 
print("The sum is :" , sum)

Output

The sum is : 30

Numerical values are assigned to variables num1 and num2. Then add two numbers and print the sum result.

3. Taking User Input

Source Code :

# Store the inputs 

name = input("What is your name? ")
print("Hello! ", name)

Output

What is your name? Tamal
Hello!  Tamal

In this Python program, we are asking the user to tell your name and then display the name. Here we use the built-in ” input() ” function to take the input and store in “name” and then return the string.

4. Add Two Numbers With User Input

Source Code :

# Store the numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

sum = num1 + num2

print("Sum:", sum)

Output

Enter first number: 20
Enter second number: 30
Sum: 50

In this program, we are asking the user to put the numbers and then display the sum of these numbers. The ” input() ” function is used to get numerical input from the user. The text is stored in numbers in num1 and num2. These values are printed out.

5. Make a simple calculator

Source Code :

# Store the numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2

print("The sum is :", sum)
print("The difference is:", difference)  
print("The product is:", product)
print("The quotient is:", quotient)

Output

Enter first number: 10
Enter second number: 20

The sum is : 30
The difference is: -10
The product is: 200
The quotient is: 0.5

Numerical values are assigned to variables num1 and num2. Mathematical operations like addition, subtraction, multiplication and division are performed on these variables. The results are printed out.

6. Swap Two Variables

Source Code :

# Initialize variables 
a = 10
b = 20

# Before swapping
print("Before swapping:")
print("Value of a:", a)
print("Value of b:", b)

# Use a temporary variable to swap a and b
temp = a 
a = b
b = temp

# After swapping
print("After swapping:")
print("Value of a:", a)
print("Value of b:", b)

Output

Before swapping
Value of a: 10
Value of b: 20

After swapping
Value of a: 20
Value of b: 10

This program first initializes two variables a and b with values 10 and 20 respectively.

It prints the original values of a and b before swapping.

To swap the values, a temporary third variable temp is used to store the value of a.

The value of b is then assigned to a and the stored value in temp (original value of a) is assigned to b.

Finally, the new swapped values of a and b are printed.

7. Solve Quadratic Equation

Source Code :

import cmath

print("Quadratic Equation Solver")

a = float(input('Enter coefficient a: '))
b = float(input('Enter coefficient b: '))
c = float(input('Enter coefficient c: '))

d = (b**2) - (4*a*c)

sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solutions are {0} and {1}'.format(sol1,sol2))

Output

Quadratic Equation Solver
Enter coefficient a: 2
Enter coefficient b: 2
Enter coefficient c: 1
The solutions are (-0.5-0.5j) and (-0.5+0.5j)

This program first takes coefficient inputs a, b and c from the user.

It then calculates the discriminant d using the formula: d = b2 – 4ac

Next, it uses the quadratic formula to calculate two solutions sol1 and sol2:

sol1 = (-b – sqrt(d)) / (2a) sol2 = (-b + sqrt(d)) / (2a)

The cmath module is imported for complex number operations in case the discriminant is negative.

Finally, the solutions are printed out. The .format() method formats the solutions nicely for printing.

8. Find the Square Root

Source Code :

number = 25 

sqrt = 1
while sqrt*sqrt <= number:
    sqrt += 0.0001
    
print(f'Square root of {number} is approximately {sqrt}')

Output

Square root of 25 is approximately 5.00000000000178

The logic is :

  1. Start with sqrt = 1
  2. Increment sqrt by a small amount (0.0001) in each iteration of the loop
  3. Repeat the loop until sqrt * sqrt is greater than the target number.
  4. The current value of sqrt will be the approximate square root of the number.

This uses a Brute Force method of incrementing sqrt and checking against the number in a loop. No advanced math functions are used.

The advantage is it’s very simple to implement. The drawback is that it may take many iterations to converge for very large numbers. For decimals, we can tweak the increment amount and number of decimal places to get a precise square root.

9. Generate a Random Number

Source Code :

import random

# Generate random number between 0 to 1
print("Generating a random number between 0 and 1")

random_num = random.random()

print("Random number: ", random_num)

Output

Generating a random number between 0 and 1
Random number:  0.44525159364377787

To generate a random number in Python, we import the random module.

The random() function of random module generates a floating point number between 0 and 1.

We store this randomly generated number in random_num variable and print it out.

This will print out a different random number between 0 and 1 each time the code is run.

10. Generate a Random integer between two numbers

Source Code :

import random

lower = 10
upper = 50

random_int = random.randint(lower, upper) 
print("The random number is: ", random_int)

Output

The random number is:  12

The randint() function takes the lower and upper ranges and generates an integer randomly between the range (inclusive).

We can also choose random elements from a list using random.choice() function.

So the random module provides many ways to generate random data in Python.

You may like this :

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share this post

Hello friends, I am Tamal Maity. I am a content writer and founder of this website. I share all the information about technology, mobile, computer, coding and other tech related contents in my website.


Leave a Comment

TechNextVerse Logo

Welcome to TechNextVerse, where we explore the amazing worlds of technology, AI innovation, and digital!

DMCA.com Protection Status

Subscribe to our newsletter!