×

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python.

  • Write a program to print “Hello Python”.
print(‘Hello Python’)

Output

Hello Python

Explanation

In the above line of code, we can print any line using just one line of code.

  • Write a program to find the maximum between two numbers.

Without using a function

a = 2
b = 4      
if a >= b:
    print (a)
else:
    print (b)

Using function

def max(x, y):
      
    if x >= y:
        return x
    else:
        return y
      
      
x = 2
y = 4
print(max(x, y))

Output

4

Explanation

In the above program, we solved the problem using two methods. We can write the code for finding the maximum between two numbers using a function and without using a function. In the first code, we have just used the conditional statement to compare the two numbers and whoever is larger will get printed. In the second code, we used a function for finding the maximum value. We have created a function name max( ) and passed the two values as parameters. Inside that function, we have used the if-else statement to find the maximum value. At last, we return the maximum value using the return statement.

  • Write a program to find the factorial of a number.

Using Recursion

def fact(n):
     
    # single line to find factorial
    if n==1 or n==0:
         return 1 
    else:
         return n * fact(n - 1);
 


num = 5;
x = fact(num)
print("Factorial of",num,"is",x)

Using Iterative

def fact(n):
    if n < 0:
        return 0
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact
 


num = 5;
x = fact(num)
print("Factorial of",num,"is",x)

Output

Factorial of 5 is 120

Explanation

In the above program, we have used two methods for finding the factorial between two numbers. In the first code, we used recursion for finding the factorial between two numbers. We have created a function name as fact() and inside that function, we have used the recursive method to find the factorial. In the second code, we used the iterative method for finding the factorial between two numbers. In this code, inside the function, we have used a while loop.

  • Write a program to find the nth Fibonacci number.

Using Recursion

# First Fibonacci number is 0
# Second Fibonacci number is 1
def fibo(n):
    if n<= 0:
        print("Incorrect input")
    
    elif n == 1:
        return 0
    
    elif n == 2:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)
 


print(fibo(5))

Output

3

Explanation

In the above line of code, we have used a recursive function for finding the nth Fibonacci number. We have used a function name fibo() and inside that function, we have passed the position as the parameter to calculate the nth position Fibonacci number.

  • Write a program to find if the number is a Prime number.
x = int(input("Enter a number: "))
  
if x > 1:
    for i in range(2, int(x/2)+1):
          if (x % i) == 0:
            print(num, "is not a prime number")
            break
    else:
        print(x, "is a prime number")
  
else:
    print(x, "is not a prime number")

Input

5

Output

5 is a prime number

Explanation

In the above code, we have used loop and conditional statements for finding if a number is prime or not.

  • Write a program to find the sum of the square of the first n natural number.
def square_sum(n) :
  
    sum = 0
    for i in range(1, n+1) :
        sum = sum + (i * i)
      
    return sum
  


n = 5
print(square_sum(n))

Output

55

Explanation

Sum = 1 + 4 + 9 + 16 + 25 = 55

In the above line of code, we have calculated the sum of squares of the first n natural number using a for loop. We used a variable name sum for storing the sum of squares number in each loop. After the loop end, we return the value stored in the variable sum.

  • Write a program to print the ASCII value of any given character.
ch = 'a'


print("The ASCII value of '" + ch + "' is", ord(ch))

Output

The ASCII value of 'a' is 97

Explanation

ASCII values are used to convert a character into an integer.
ASCII (A,…..,Z) = (65,…..,90)
ASCII (a,……,z) = (97,…..,122)

In the above code, we can print the ASCII value of an alphabet using the function name ord().

Note: ord() function is used to convert characters into integers in Python.

  • Write a program to find the area of a circle.
Area of circle: π * (r*r)
where r is the radius of the circle.

Code

# Area of circle
def area(r):
    pi = 3.142
    return pi * (r*r);


print("Area is %.2f" % area(3));

Output

Area is 28.28

Explanation

The area() function calculates the area of circle, and its value is returned. Since an area can be an integer and a float value, we have used %.2f to print the value. This means the value will be printed in a float value, and after the decimal, only two digits will be printed.

  • Write a program to find the largest element in an array.
def largest(arr,n):
  
    # Initialize maximum element
    max = arr[0]
  
    # Traverse array from second element
    
    for i in range(1, n):
        if arr[i] > max:
            max = arr[i]
    return max
  


arr = [6, 77, 320, 60, 100]
x = len(arr)
lar_num = largest(arr,x)
print ("Largest in given array is", lar_num)

Input

arr = [66, 77, 320, 60, 100]

Output

Largest in given array is 320

Explanation

In the above code, we have declared an array with given values. After that, we are calling a function name largest() with arguments as array and size of the array. We have used the function largest to find the largest element of an array by comparing the selected index value with the rest index value on its right side.  The returned value from the array is stored in a variable name lar_num.

  • Write a program to add of two matrices.

a = [[1,2,3],
    [11 ,12,13],
    [111 ,112,113]]
 
b = [[4,5,6],
    [14,15,16],
    [114,115,116]]
 
c = [[0,0,0],
       [0,0,0],
        [0,0,0]]
 
# iterate through rows and then column 
for i in range(len(a)):  
    for j in range(len(a[0])):
        c[i][j] = a[i][j] + b[i][j]
 
for r in c:
    print(r)

Input

a = [[1,2,3],
    [11 ,12,13],
    [111 ,112,113]]
 
b = [[4,5,6],
    [14,15,16],
    [114,115,116]]


c = a+b
c = [(1+4), (2+5), (3+6)]
      [(11+14), (12+15), (13+16)]
      [(111+114), (112+115), (113+116)]

Output:

[5, 7, 9]
[25, 27, 29]
[225, 227, 229]

Explanation

In the above code, for adding two matrices, we have used two loops which will be iterating over all the rows and columns of both the matrix, and then used another matrix for storing the added value.


Related Topics

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.