How to Build Web scraping bot in Python
Last Updated :
02 Feb, 2022
In this article, we are going to see how to build a web scraping bot in Python.
Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our requirements.
Module needed
- bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
- requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests
- Selenium: Selenium is one of the most popular automation testing tools. It can be used to automate browsers like Chrome, Firefox, Safari, etc.
pip install selenium
Method 1: Using Selenium
We need to install a chrome driver to automate using selenium, our task is to create a bot that will be continuously scraping the google news website and display all the headlines every 10mins.
Stepwise implementation:
Step 1: First we will import some required modules.
Python3
# These are the imports to be made
import time
from selenium import webdriver
from datetime import datetime
Step 2: The next step is to open the required website.
Python3
# path of the chromedriver we have just downloaded
PATH = r"D:\chromedriver"
driver = webdriver.Chrome(PATH) # to open the browser
# url of google news website
url = 'https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en'
# to open the url in the browser
driver.get(url)
Output:
Step 3: Extracting the news title from the webpage, to extract a specific part of the page, we need its XPath, which can be accessed by right-clicking on the required element and selecting Inspect in the dropdown bar.
After clicking Inspect a window appears. From there, we have to copy the elements full XPath to access it:
Note: You might not always get the exact element that you want by inspecting (depends on the structure of the website), so you may have to surf the HTML code for a while to get the exact element you want. And now, just copy that path and paste that into your code. After running all these lines of code, you will get the title of the first heading printed on your terminal.
Python3
# Xpath you just copied
news_path = '/html/body/c-wiz/div/div[2]/div[2]/\
div/main/c-wiz/div[1]/div[3]/div/div/article/h3/a'
# to get that element
link = driver.find_element_by_xpath(news_path)
# to read the text from that element
print(link.text)
Output:
'Attack on Afghan territory': Taliban on US airstrike that killed 2 ISIS-K men
Step 4: Now, the target is to get the X_Paths of all the headlines present.
One way is that we can copy all the XPaths of all the headlines (about 6 headlines will be there in google news every time) and we can fetch all those, but that method is not suited if there are a large number of things to be scrapped. So, the elegant way is to find the pattern of the XPaths of the titles which will make our tasks way easier and efficient. Below are the XPaths of all the headlines on the website, and let's figure out the pattern.
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[3]/div/div/article/h3/a
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[4]/div/div/article/h3/a
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[5]/div/div/article/h3/a
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[6]/div/div/article/h3/a
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[7]/div/div/article/h3/a
/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[8]/div/div/article/h3/a
So, by seeing these XPath's, we can see that only the 5th div is changing (bolded ones). So based upon this, we can generate the XPaths of all the headlines. We will get all the titles from the page by accessing them with their XPath. So to extract all these, we have the code as
Python3
# I have used f-strings to format the string
c = 1
for x in range(3, 9):
print(f"Heading {c}: ")
c += 1
curr_path = f'/html/body/c-wiz/div/div[2]/div[2]/div/main\
/c-wiz/div[1]/div[{x}]/div/div/article/h3/a'
title = driver.find_element_by_xpath(curr_path)
print(title.text)
Output:
Now, the code is almost complete, the last thing we have to do is that the code should get headlines for every 10 mins. So we will run a while loop and sleep for 10 mins after getting all the headlines.
Below is the full implementation
Python3
import time
from selenium import webdriver
from datetime import datetime
PATH = r"D:\chromedriver"
driver = webdriver.Chrome(PATH)
url = 'https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en'
driver.get(url)
while(True):
now = datetime.now()
# this is just to get the time at the time of
# web scraping
current_time = now.strftime("%H:%M:%S")
print(f'At time : {current_time} IST')
c = 1
for x in range(3, 9):
curr_path = ''
# Exception handling to handle unexpected changes
# in the structure of the website
try:
curr_path = f'/html/body/c-wiz/div/div[2]/div[2]/\
div/main/c-wiz/div[1]/div[{x}]/div/div/article/h3/a'
title = driver.find_element_by_xpath(curr_path)
except:
continue
print(f"Heading {c}: ")
c += 1
print(title.text)
# to stop the running of code for 10 mins
time.sleep(600)
Output:

Method 2: Using Requests and BeautifulSoup
The requests module gets the raw HTML data from websites and beautiful soup is used to parse that information clearly to get the exact data we require. Unlike Selenium, there is no browser installation involved and it is even lighter because it directly accesses the web without the help of a browser.
Stepwise implementation:
Step 1: Import module.
Python3
import requests
from bs4 import BeautifulSoup
import time
Step 2: The next thing to do is to get the URL data and then parse the HTML code
Python3
url = 'https://finance.yahoo.com/cryptocurrencies/'
response = requests.get(url)
text = response.text
data = BeautifulSoup(text, 'html.parser')
Step 3: First, we shall get all the headings from the table.
Python3
# since, headings are the first row of the table
headings = data.find_all('tr')[0]
headings_list = [] # list to store all headings
for x in headings:
headings_list.append(x.text)
# since, we require only the first ten columns
headings_list = headings_list[:10]
print('Headings are: ')
for column in headings_list:
print(column)
Output:
Step 4: In the same way, all the values in each row can be obtained
Python3
# since we need only first five coins
for x in range(1, 6):
table = data.find_all('tr')[x]
c = table.find_all('td')
for x in c:
print(x.text, end=' ')
print('')
Output:
Below is the full implementation:
Python3
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
while(True):
now = datetime.now()
# this is just to get the time at the time of
# web scraping
current_time = now.strftime("%H:%M:%S")
print(f'At time : {current_time} IST')
response = requests.get('https://finance.yahoo.com/cryptocurrencies/')
text = response.text
html_data = BeautifulSoup(text, 'html.parser')
headings = html_data.find_all('tr')[0]
headings_list = []
for x in headings:
headings_list.append(x.text)
headings_list = headings_list[:10]
data = []
for x in range(1, 6):
row = html_data.find_all('tr')[x]
column_value = row.find_all('td')
dict = {}
for i in range(10):
dict[headings_list[i]] = column_value[i].text
data.append(dict)
for coin in data:
print(coin)
print('')
time.sleep(600)
Output:

Hosting the Bot
This is a specific method, used to run the bot continuously online without the need for any human intervention. replit.com is an online compiler, where we will be running the code. We will be creating a mini webserver with the help of a flask module in python that helps in the continuous running of the code. Please create an account on that website and create a new repl.
After creating the repl, Create two files, one to run the bot code and the other to create the web server using flask.
Code for cryptotracker.py:
Python3
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
# keep_alive function, that maintains continuous
# running of the code.
from keep_alive import keep_alive
import pytz
# to start the thread
keep_alive()
while(True):
tz_NY = pytz.timezone('Asia/Kolkata')
datetime_NY = datetime.now(tz_NY)
# this is just to get the time at the time of web scraping
current_time = datetime_NY.strftime("%H:%M:%S - (%d/%m)")
print(f'At time : {current_time} IST')
response = requests.get('https://finance.yahoo.com/cryptocurrencies/')
text = response.text
html_data = BeautifulSoup(text, 'html.parser')
headings = html_data.find_all('tr')[0]
headings_list = []
for x in headings:
headings_list.append(x.text)
headings_list = headings_list[:10]
data = []
for x in range(1, 6):
row = html_data.find_all('tr')[x]
column_value = row.find_all('td')
dict = {}
for i in range(10):
dict[headings_list[i]] = column_value[i].text
data.append(dict)
for coin in data:
print(coin)
time.sleep(60)
Code for the keep_alive.py (webserver):
Python3
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "Hello. the bot is alive!"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
Keep-alive is a method in networking that is used to prevent a certain link from breaking. Here the purpose of the keep-alive code is to create a web server using flask, that will keep the thread of the code (crypto-tracker code) to be active so that it can give the updates continuously.
Now, we have a web server create, and now, we need something to ping it continuously so that the server does not go down and the code keeps on running continuously. There is a website uptimerobot.com that does this job. Create an account in it
Running the Crypto tracker code in Replit. Thus, We have successfully created a web scraping bot that will scrap the particular website continuously for every 10 mins and print the data to the terminal.
Similar Reads
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python List Exercise List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an
3 min read
Python String Exercise Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove iâth character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in
4 min read
Python Tuple Exercise Basic Tuple ProgramsPython program to Find the size of a TuplePython â Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython â Adding Tuple to List and vice â versaPython â Sum of tuple elementsPython â Modulo of tuple elementsP
3 min read
Python Dictionary Exercise Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Python Set Exercise Basic Set ProgramsFind the size of a Set in PythonIterate over a set in PythonPython - Maximum and Minimum in a SetPython - Remove items from SetPython - Check if two lists have at-least one element commonPython program to find common elements in three lists using setsPython - Find missing and addit
2 min read
Python Matrix Exercises
Python program to a Sort Matrix by index-value equality countGiven a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the m
6 min read
Python Program to Reverse Every Kth row in a MatrixWe are given a matrix (a list of lists) and an integer K. Our task is to reverse every Kth row in the matrix. For example:Input : a = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]Using reversed() and loopWe c
4 min read
Python Program to Convert String Matrix Representation to MatrixGiven a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as
4 min read
Python - Count the frequency of matrix row lengthGiven a Matrix, the task is to write a Python program to get the count frequency of its rows lengths. Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]] Output : {3: 2, 2: 2, 1: 1} Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present. Input :
5 min read
Python - Convert Integer Matrix to String MatrixGiven a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
6 min read
Python Program to Convert Tuple Matrix to Tuple ListGiven a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 min read
Python - Group Elements in MatrixGiven a Matrix with two columns, group 2nd column elements on basis of 1st column. Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] Output : {5: [8, 4], 2: [0, 3, 9]} Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2
6 min read
Python - Assigning Subsequent Rows to Matrix first row elementsGiven a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix. Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]] Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]} Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th Input : test_list
3 min read
Adding and Subtracting Matrices in PythonIn this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of
4 min read
Python - Convert Matrix to DictionaryThe task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
4 min read
Python - Convert Matrix to Custom Tuple MatrixSometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used
6 min read
Python - Matrix Row subsetSometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have applications in data domains as a matrix is a key data type in those domains. Let's discuss certain way
7 min read
Python - Group similar elements into MatrixSometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
8 min read
Python - Row-wise element Addition in Tuple MatrixSometimes, while working with Python tuples, we can have a problem in which we need to perform Row-wise custom elements addition in Tuple matrix. This kind of problem can have application in data domains. Let's discuss certain ways in which this task can be performed.Input : test_list = [[('Gfg', 3)
4 min read
Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as evenGiven an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition: The elements of the matrix should be distinct i.e used only onceNumbers ranging from 1 to n^2Every sub-matrix you choose should have the sum of opposite co
6 min read
Python Functions Exercises
Python splitfields() MethodThe splitfields() method is a user-defined method written in Python that splits any kind of data into a list of fields using a delimiter. The delimiter can be specified as an argument to the method, and if no delimiter is specified, the method splits the string using whitespace characters as the del
3 min read
How to get list of parameters name from a function in Python?The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
4 min read
How to Print Multiple Arguments in Python?An argument is a value that is passed within a function when it is called. They are independent items or variables that contain data or codes. At the time of function call each argument is always assigned to the parameter in the function definition. Example:Pythondef GFG(name, num): print("Hello fro
4 min read
Python program to find the power of a number using recursionGiven a number N and power P, the task is to find the power of a number ( i.e. NP ) using recursion. Examples: Input: N = 2 , P = 3Output: 8 Input: N = 5 , P = 2Output: 25 Approach: Below is the idea to solve the above problem: The idea is to calculate power of a number 'N' is to multiply that numbe
3 min read
Sorting Objects of User Defined Class in PythonSorting objects of a user-defined class in Python involves arranging instances of the class based on the values of one or more of their attributes. For example, if we have a class Person with attributes like name and age, we might want to sort a list of Person objects based on the age attribute to o
5 min read
Assign Function to a Variable in PythonIn Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print(
3 min read
Returning a function from a function - PythonIn Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the
5 min read
What are the allowed characters in Python function names?The user-defined names that are given to Functions or variables are known as Identifiers. It helps in differentiating one entity from another and also serves as a definition of the use of that entity sometimes. As in every programming language, there are some restrictions/ limitations for Identifier
2 min read
Defining a Python Function at RuntimeOne amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. Itâs especially useful for things like metaprogramming, event-driven systems and running code dynamically
3 min read
Explicitly define datatype in a Python functionUnlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
4 min read
Functions that Accept Variable Length Key Value Pair as ArgumentsTo pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments (arguments passed with a specific name (key) along with their value)
2 min read
How to find the number of arguments in a Python function?Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones.Using ins
4 min read
How to check if a Python variable exists?Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Letâs explore different methods to efficiently check if a va
3 min read
Get Function Signature - PythonA function signature in Python defines the name of the function, its parameters, their data types , default values and the return type. It acts as a blueprint for the function, showing how it should be called and what values it requires. A good understanding of function signatures helps in writing c
3 min read
Python program to convert any base to decimal by using int() methodGiven a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. Examples: Input : '1011' base = 2 Output : 1
2 min read
Python Lambda Exercises
Python - Lambda Function to Check if value is in a ListGiven a list, the task is to write a Python program to check if the value exists in the list or not using the lambda function. Example: Input : L = [1, 2, 3, 4, 5] element = 4 Output : Element is Present in the list Input : L = [1, 2, 3, 4, 5] element = 8 Output : Element is NOT Present in the list
2 min read
Difference between Normal def defined function and LambdaIn this article, we will discuss the difference between normal 'def' defined function and 'lambda' function in Python.Def keywordâââââââIn Python, functions defined using def keyword are commonly used due to their simplicity. Unlike lambda functions, which always return a value, def functions do not
2 min read
Python: Iterating With Python LambdaIn Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the exp
2 min read
How to use if, else & elif in Python Lambda FunctionsLambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions.Using if-else in lambda functionThe lamb
2 min read
Python - Lambda function to find the smaller value between two elementsThe lambda function is an anonymous function. It can have any number of arguments but it can only have one expression. Syntax lambda arguments : expression In this article, we will learn how to find the smaller value between two elements using the Lambda function. Example: Input : 2 5 Output : 2 Inp
2 min read
Lambda with if but without else in PythonIn Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value. Since a lambda function must have a return value for every valid input, we
3 min read
Python Lambda with underscore as an argumentIn Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one num
1 min read
List comprehension and Lambda Function in PythonList comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts :Output expression,Input sequence,A vari
3 min read
Nested Lambda Function in PythonPrerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then
2 min read
Python lambdaIn Python, an anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.Python lambda Syntax:lambda arguments : expressionPython lambda Example:Pythoncalc = lambd
4 min read
Python | Sorting string using order defined by another stringGiven two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat =
2 min read
Python | Find fibonacci series upto n using lambdaThe Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Find the series of fi
2 min read
Overuse of lambda expressions in PythonWhat are lambda expressions? A lambda expression is a special syntax to create functions without names. These functions are called lambda functions. These lambda functions can have any number of arguments but only one expression along with an implicit return statement. Lambda expressions return func
8 min read
Python Program to Count Even and Odd Numbers in a ListIn Python working with lists is a common task and one of the frequent operations is counting how many even and odd numbers are present in a given list. The collections.Counter method is the most efficient for large datasets, followed by the filter() and lambda approach for clean and compact code. Us
4 min read
Intersection of two Arrays in Python ( Lambda expression and filter function )Finding the intersection of two arrays using a lambda expression and the filter() function means filtering elements from one array that exist in the other. The lambda defines the condition (x in array2), and filter() applies it to the first array to extract common elements.For example, consider two
1 min read
Python Pattern printing Exercises
Simple Diamond Pattern in PythonGiven an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4. Examples : For size = 5 * * * * * * * * * * * * For size = 8 * * * * * * * * * * * * * * * * * * * * * * * * * * For size = 11 * * *
3 min read
Python - Print Heart PatternGiven an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations. Example :For n = 8 * * * * * * * * * * G F G * * * * * * * * For n = 14 * * * * * * * * * * * * * * * * * * G F G * * * * * * * * * * * * * * Approach : The following steps
3 min read
Python program to display half diamond pattern of numbers with star borderGiven a number n, the task is to write a Python program to print a half-diamond pattern of numbers with a star border. Examples: Input: n = 5 Output: * *1* *121* *12321* *1234321* *123454321* *1234321* *12321* *121* *1* * Input: n = 3 Output: * *1* *121* *12321* *121* *1* * Approach: Two for loops w
2 min read
Python program to print Pascal's TrianglePascal's triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal's triangle.Example:Input: N = 5Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1Method 1: Using nCr formula i.e. n!/(n-r)!r!After using nCr formula, the pictorial representation becomes: 0C0 1C0
3 min read
Python program to print the Inverted heart patternLet us see how to print an inverted heart pattern in Python. Example: Input: 11 Output: * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ********************* ********* ******** ******* ****** ***** **** Input: 15 Output: * *** ***** *****
2 min read
Python Program to print hollow half diamond hash patternGive an integer N and the task is to print hollow half diamond pattern. Examples: Input : 6 Output : # # # # # # # # # # # # # # # # # # # # Input : 7 Output : # # # # # # # # # # # # # # # # # # # # # # # # Approach: The idea is to break the pattern into two parts: Upper part: For the upper half st
4 min read
Program to Print K using AlphabetsGiven a number n, the task is to print 'K' using alphabets.Examples: Input: n = 5 Output: A B C D E F A B C D E A B C D A B C A B A A A B A B C A B C D A B C D E A B C D E F Input: n = 3 Output: A B C D A B C A B A A A B A B C A B C D Below is the implementation. C++ // C++ Program to design the //
5 min read
Program to print half Diamond star patternGiven an integer N, the task is to print half-diamond-star pattern. ************************************ Examples: Input: N = 3 Output: * ** *** ** * Input: N = 6 Output: * ** *** **** ***** ****** ***** **** *** ** * Approach: The idea is to break the pattern into two halves that is upper half and
4 min read
Program to print window patternPrint the pattern in which there is a hollow square and plus sign inside it. The pattern will be as per the n i.e. number of rows given as shown in the example. Examples: Input : 6 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input : 7 Output : * * * * * * * * * * * * * *
7 min read
Python Program to print a number diamond of any given size N in Rangoli StyleGiven an integer N, the task is to print a number diamond of size N in rangoli style where N means till Nth number from number â1â. Examples: Input : 2 Output : --2-- 2-1-2 --2-- Input : 3 Output : ----3---- --3-2-3-- 3-2-1-2-3 --3-2-3-- ----3---- Input : 4 Output : ------4------ ----4-3-4---- --4-3
3 min read
Python program to right rotate n-numbers by 1Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.Examples: Input: 6 Output : 1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 5 6 1 2 3 4 6 1 2 3 4 5 Input : 3 Output : 1 2 3 2 3 1 3 1 2 Method 1: Below is the implementa
2 min read
Python Program to print digit patternThe program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. He
3 min read
Print with your own font using Python !!Programming's core function is printing text, but have you ever wished to give it a unique look by utilizing your own custom fonts? Python enables you to use imagination and overcome the standard fonts in your text outputs. In this article, we will do some cool Python tricks. For the user input, the
4 min read
Python | Print an Inverted Star PatternAn inverted star pattern involves printing a series of lines, each consisting of stars (*) that are arranged in a decreasing order. Here we are going to print inverted star patterns of desired sizes in Python Examples: 1) Below is the inverted star pattern of size n=5 (Because there are 5 horizontal
2 min read
Program to print the Diamond ShapeGiven a number n, write a program to print a diamond shape with 2n rows.Examples : C++ // C++ program to print diamond shape // with 2n rows #include <bits/stdc++.h> using namespace std; // Prints diamond pattern with 2n rows void printDiamond(int n) { int space = n - 1; // run loop (parent lo
11 min read