Area of Circle: It is the area occupied by the circle.
Given by the formula,
Area = π*R*R
Value of π = 3.14, R is the radius of a circle.
Perimeter of Circle: Also known as the circumference. It is given by the formula,
Perimeter = 2*π*R
Value of π = 3.14, R is the radius of a circle.
We will use these formulas for finding the area and perimeter of the circle with a given radius. The value of π can
either be used directly or can be extracted using the pi value in the math library in Python.
Program to find area and perimeter of a circle
# Python program to find the
# area and perimeter of circle in python
# Initialising the value of PI
PI = 3.14
# Getting input from user
R = float(input("Enter radius of the circle: "))
# Finding the area and perimeter of the circle
area = (PI*R*R)
perimeter = (2*PI*R)
# Printing the area and perimeter of the circle
print("The area of circle is", area)
print("The perimeter of circle is", perimeter)
Output:
RUN 1:
Enter radius of the circle: 1.2
The area of circle is 4.521599999999999
The perimeter of circle is 7.536
RUN 2:
Enter radius of the circle: 35.63
The area of circle is 3986.2202660000007
The perimeter of circle is 223.7564
Explanation:
In the above code, we have initialized the value of PI with 3.14. Then asked the user for an input for the value of R.
Using the formulas, we calculated the value of area and perimeter and printed it.
We can also get the value of PI using the built-in value in Python's math library.
Syntax:
math.pi
Program to find area and perimeter of a circle using math library
# Python program to find the
# area and perimeter of a circle in python
from math import pi
# Getting input from user
R = float(input("Enter radius of the circle: "))
# Finding the area and perimeter of the circle
area = (pi*R*R)
perimeter = (2*pi*R)
# Printing the area and perimeter of the circle
print("The area of circle is ", "%.2f" %area)
print("The perimeter of circle is", "%.2f" %perimeter)
Output:
RUN 1:
Enter radius of the circle: 1.2
The area of circle is 4.52
The perimeter of circle is 7.54
RUN 2:
Enter radius of the circle: 35.63
The area of circle is 3988.24
The perimeter of circle is 223.87
Explanation:
In the above code, we have imported the value of pi from the math library for use in the program. Then asked the
user for an input for the value of R. Using the formulas, we calculated the value of area and perimeter and printed
it.
Write a Python program to generate Fibonacci series
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Write a Python program to compute the GCD of two numbers.
Algorithm
Initialize GCD = 1
Run a loop in the iteration of (i) between [1, min(num1, num2)]
Note down the highest number that divides both num1 & num2
If i satisfies (num1 % i == 0 and num2 % i == 0) then new value of GCD is i
Print value of GCD
num1 = 120
num2 = 60
gcd = 1
for i in range(1, min(num1, num2)):
if num1 % i == 0 and num2 % i == 0:
gcd = i
print("GCD of", num1, "and", num2, "is", gcd)
1. Write a Python program to generate first n prime numbers
numr=int(input("Enter range:"))
print("Prime numbers:",end=' ')
for n in range(1,numr):
for i in range(2,n):
if(n%i==0):
break
else:
print(n,end=' ')
1. Write a Python program to find the sum of squares of n natural numbers.
In this problem we will see how we can get the sum of squares of first n natural numbers. Here we are using one for loop, that runs from 1 to n.
In each step we are calculating square of the term and then add it to the sum. This program takes O(n) time to complete. But if we want to solve
this in O(1) or constant time, we can use this series formula −
Algorithm
squareNNatural(n)
begin
sum := 0
for i in range 1 to n, do
sum := sum + i^2
done
return sum
end
Example
Live Demo
#include<iostream>
using namespace std;
long square_sum_n_natural(int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i; //square i and add it with sum
}
return sum;
}
main() {
int n;
cout << "Enter N: ";
cin >> n;
cout << "Result is: " << square_sum_n_natural(n);
}
Output
Enter N: 4
Result is: 30
1. Write a Python program to find the sum of the elements in an array.
Python program to print the sum of all elements in an array
In this program, we need to calculate the sum of all the elements of an array. This can be solved by looping
through the array and add the value of the element in each iteration to variable sum.
Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.
ALGORITHM:
o STEP 1: Declare and initialize an array.
o STEP 2: The variable sum will be used to calculate the sum of the elements. Initialize it to 0.
o STEP 3: Loop through the array and add each element of the array to the variable sum as sum =
sum + arr[i].
PROGRAM:
#Initialize array
arr = [1, 2, 3, 4, 5];
sum = 0;
#Loop through the array to calculate sum of elements
for i in range(0, len(arr)):
sum = sum + arr[i];
print("Sum of all the elements of an array: " + str(sum));
Output:
Sum of all the elements of an array: 15
1. Write a Python program to find the largest element in the array.
Method 1 :
Declare a variable say max_element and initialize it with a[0].
Run a loop for range a.len().
Check if(a[i]>max_element) then set max_element to a[i]
After complete iteration print(max_element)
a = [10, 89, 9, 56, 4, 80, 8]
max_element = a[0]
for i in range(len(a)):
if a[i] > max_element:
max_element = a[i]
print (max_element)
2. Write a Python program to check if the given string is a palindrome or not.
3. Read the number or letter.
4. Hold the letter or number in a temporary variable.
5. Reverse the letter or number.
6. Compare the temporary variable with reverses letter or number.
7. If both letters or numbers are the same, print "this string/number is a palindrome."
8. Else print, "this string/number is not a palindrome."
Palindrome Program
string=raw_input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")
1. Write a Python program to store strings in a list and print them.
String to List in Python
So far, we have discussed various conversions in Python. In this tutorial, we will learn another one, which is
converting a string to a list in Python.
We will use the following methods to meet our objective-
1. Using split()
2. Using split() with a separator
3. Using strip()
4. Using map()
Let us discuss each one of them.
In the first program, we will make use of split() to convert the string to a list in Python.
t is IPO cycle."
str_val4 = "Then learn about the generation of computers."
#using split()
print(str_val1.split())
print(str_val2.split())
print(str_val3.split())
print(str_val4.split())
Output:
['Let', 'us', 'study', 'programming.']
['But', 'before', 'that', 'it', 'is', 'essential', 'to', 'have', 'a',
'basic', 'knowledge', 'of', 'computers.']
['So', 'first', 'study', 'what', 'is', 'IPO', 'cycle.']
['Then', 'learn', 'about', 'the', 'generation', 'of', 'computers.']
Explanation-
1. In the first step, we have initialized the four strings that we would like to convert.
2. After this, we have used the split() so that we obtain a list in which each word of a string represents
an element of the list.
In the second program, we have specified a separator in split().
Using split() with a Separator
Consider the given program,
# Initializing the string values
str_val1="Let @ us @ study @ programming."
str_val2="But # before # that # it # is # essential # to # have # a # basic # knowledge # of # computers."
str_val3="So $ first $ study $ what $ is $ IPO $ cycle."
str_val4="Then % learn % about % the % generation % of % computers."
# Using split()
print(str_val1.split("@"))
print(str_val2.split("#"))
print(str_val3.split("$"))
10. print(str_val4.split("%"))
Output:
['Let ', ' us ', ' study ', ' programming.']
['But ', ' before ', ' that ', ' it ', ' is ', ' essential ', ' to ', '
have ', ' a ', ' basic ', ' knowledge ', ' of ', ' computers.']
['So ', ' first ', ' study ', ' what ', ' is ', ' IPO ', ' cycle.']
['Then ', ' learn ', ' about ', ' the ', ' generation ', ' of ', '
computers.']
Explanation-
The approach is similar to the previous program, the only difference it takes an element in the list whenever a
separator occurs.
In this program, the separators in the strings were @, #, $ & %.
Now, let's see how to strip() can be used.
Using strip()
The following program illustrates the same-
# Initialising the string values
str_val1 = "Let us study programming."
str_val2 = "But before that it is essential to have a basic knowledge of computers."
# Using list()
print(list(str_val1.strip()))
print(list(str_val2.strip()))
Output:
['L', 'e', 't', ' ', 'u', 's', ' ', 's', 't', 'u', 'd', 'y', ' ', 'p',
'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', '.']
['B', 'u', 't', ' ', 'b', 'e', 'f', 'o', 'r', 'e', ' ', 't', 'h', 'a',
't', ' ', 'i', 't', ' ', 'i', 's', ' ', 'e', 's', 's', 'e', 'n', 't', 'i',
'a', 'l', ' ', 't', 'o', ' ', 'h', 'a', 'v', 'e', ' ', 'a', ' ', 'b', 'a',
's', 'i', 'c', ' ', 'k', 'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e', ' ', 'o',
'f', ' ', 'c', 'o', 'm', 'p', 'u', 't', 'e', 'r', 's', '.']
Explanation-
1. In the first step, we have initialized the two strings that we would like to convert.
2. After this, we have used the strip() so that we obtain a list, where each character represents of the
string represents an element in the list.
Convert Strings to List of Lists using map()
# Initializing the string values
str_val1="Let us study programming."
str_val2="But before that it is essential to have a basic knowledge of computers."
#using split()
str_val1 = str_val1.split()
str_val2 = str_val2.split()
list_str1 = list(map(list,str_val1))
list_str2 = list(map(list,str_val2))
#displaying the list values
10. print(list_str1)
11. print(list_str2)
Output:
[['L', 'e', 't'], ['u', 's'], ['s', 't', 'u', 'd', 'y'], ['p', 'r', 'o',
'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', '.']]
[['B', 'u', 't'], ['b', 'e', 'f', 'o', 'r', 'e'], ['t', 'h', 'a', 't'],
['i', 't'], ['i', 's'], ['e', 's', 's', 'e', 'n', 't', 'i', 'a', 'l'],
['t', 'o'], ['h', 'a', 'v', 'e'], ['a'], ['b', 'a', 's', 'i', 'c'], ['k',
'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e'], ['o', 'f'], ['c', 'o', 'm', 'p',
'u', 't', 'e', 'r', 's', '.']]
Explanation-
1. In the first step, we have initialized the two strings that we would like to convert.
2. After this, we have used the split() method followed by map() so that we map the list functionality to
each element of the string.
3. On executing the given program, the desired output is displayed.
Finally, in the last program we have used the string of integers,
Converting String of Integers
Consider the program given below,
#initialising the string values
str_val1 = "1 2 3 4 5 6 7 8 9"
str_val2 = "12 21 32 44 54 76 83"
#using split()
str_val1 = str_val1.split()
str_val2 = str_val2.split()
list_str1 = list(map(int,str_val1))
list_str2 = list(map(int,str_val2))
#displaying the list values
10. print(list_str1)
11. print(list_str2)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[12, 21, 32, 44, 54, 76, 83]
Explanation-
The logic is similar to the above program but here we have passed a string of integers and applied the 'int'
functionality on all the element
Write a Python program to find the length of a list, reverse it, copy it and then
clear it.
How to Find the Length of List in Python?
There are two most commonly used and basic methods that are used to find the length of the
list in Python:
Len() Method
Naive Method
Len() Method
There is a built-in function called len() for getting the total number of items in a list,
tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a
list and it returns the length of the given list.
The len() method is one of the most used and convenient ways to find the length of list in
Python. This is the most conventional technique adopted by all the programmers today.
Syntax:
1 len(list)
The List parameter is a list for which the number of elements are to be counted. It returns the
number of elements in the list.
Example:
Next
1 ListName = ["Hello", "Edureka", 1, 2, 3]
2 print ("Number of items in the list = ", len(ListName))
Output:5
Naive Method
The len() method is the most commonly used method to find the length of the list in Python.
But there is another basic method that provides the length of the list.
In the Naive method, one just runs a loop and increases the counter until the last element of
the list to know its count. This is the most basic strategy that can be used in the absence of
other efficient techniques.
Example:
1 ListName = [ "Hello", "Edureka", 1,2,3 ]
2 print ("The list is : " + str(ListName))
counter = 0
3
for i in ListName:
4
counter = counter + 1
5
print ("Length of list using naive method is : " +
6 str(counter))
Output:
The list is : ["Hello", "Edureka", 1,2,3]
Length of list using naive method is : 5
This was all about finding the length of list in Python. The len() method is the most popular
method. Whereas, you can also use the basic method of finding the length with the help of
Naive Method.
With this, we have come to the end of our article. I hope you understood how to find the
length of any list in Python.
Python program for reverse a list
Python List reverse()
In this tutorial, we will learn about the Python List reverse() method with the help of examples.
The reverse() method reverses the elements of the list.
Example
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# reverse the order of list elements
prime_numbers.reverse()
print('Reversed List:', prime_numbers)
# Output: Reversed List: [7, 5, 3, 2]
Run Code
Syntax of List reverse()
The syntax of the reverse() method is:
list.reverse()
reverse() parameter
The reverse() method doesn't take any arguments.
Return Value from reverse()
The reverse() method doesn't return any value. It updates the existing list.
Example 1: Reverse a List
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Run Code
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
There are other several ways to reverse a list.
Example 2: Reverse a List Using Slicing Operator
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Run Code
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
Example 3: Accessing Elements in Reversed Order
If you need to access individual elements of a list in the reverse order, it's better to use
the reversed() function.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
# Printing Elements in Reversed Order
for o in reversed(systems):
print(o)
Run Code
Output
Linux
macOS
Python program for clear a list
Python List clear()
In this tutorial, we will learn about the Python List clear() method with the help of examples.
The clear() method removes all items from the list.
Example
prime_numbers = [2, 3, 5, 7, 9, 11]
# remove all elements
prime_numbers.clear()
# Updated prime_numbers List
print('List after clear():', prime_numbers)
# Output: List after clear(): []
Run Code
Syntax of List clear()
The syntax of clear() method is:
list.clear()
clear() Parameters
The clear() method doesn't take any parameters.
Return Value from clear()
The clear() method only empties the given list. It doesn't return any value.
Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
Run Code
Output
List: []
Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method. You can use the
del operator instead.
Example 2: Emptying the List Using del
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
del list[:]
print('List:', list)
Run Code
Output
List: []
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made
in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Try it Yourself »
Another way to make a copy is to use the built-in method list().
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Try it Yourself »
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Try it Yourself »
Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)