You are reading the article How To Draw A Star In Python (Using Turtle): A Step updated in December 2023 on the website Katfastfood.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Draw A Star In Python (Using Turtle): A Step
The Turtle module in Python is a library that allows users to create simple graphics programs using a turtle. This guide teaches you how to use Turtle to draw a star with 5 edges as well as 10 edges.
In Python, Turtle is an object that can be moved around the screen, and it can be given commands to draw lines, change its color, and more. By moving the Turtle object in a specific way with a specific angle, you can generate a star-like shape.
Let’s jump into it!
5 Steps to Draw a Star Using Python TurtleTo draw a star with Python Turtle, you can use the following steps:
Import the turtle library in your Python code. This will give you access to the functions and methods you need to create turtle graphics.
import turtleCreate a new Turtle object. This will be the turtle that you use to draw the star.
t = turtle.Turtle()Use a for loop to repeat a sequence of steps that will draw the star. In each iteration of the loop, use the t.forward() method to move the turtle forward by a specified distance, and the t.right() method to turn the turtle to the right by a certain number of degrees.
for i in range(5): t.forward(100) t.right(144)This code draws a line 100 pixels forward and then turns 144 degrees towards the left. After doing this five times, you end up turning the turtle around by 5 * 144 = 720 degrees to stop it at the same place it started forming a star shape.
If you run this code, you should see a star with 5 edges:
To make the star have more edges, tweak the angle that the turtle turns after each forward movement. Instead of turning by 144 degrees, turn 108 degrees. This makes the turtle’s turns take place at less steep angles which means it will complete the star shape with more strokes. If you’re using 108 degrees as the angle of your star, it requires 1080 degrees of rotation to get the Turtle back to its starting position.
for i in range(10): t.forward(100) t.right(108)Running this piece of code gives you a star that looks like this:
Full CodeHere’s the complete code to draw a star with 5 edges in Python Turtle:
import turtle t = turtle.Turtle() for i in range(5): t.forward(100) t.right(144 - 36)And here’s the code to draw a star with 10 edges:
import turtle t = turtle.Turtle() for i in range(10): t.forward(100) t.right(108) How to Color the Star?If you want to add color to the star in Turtle, you can use the fillcolor() method to shade the area restricted by the Turtle strokes.
Here’s what it looks like in the code:
import turtle my_turtle = turtle.Turtle() # Set the turtle's pen color my_turtle.pencolor("black") # Set the star's fill color my_turtle.fillcolor("yellow") # Begin filling the star my_turtle.begin_fill() # Draw the star for i in range(5): my_turtle.forward(100) my_turtle.left(144) # End filling the star my_turtle.end_fill() # Keep the turtle window open turtle.done()Output:
Notice how the edge that points toward the top left looks out of place because there’s no stroke that would strike through the edge similar to the other edges. To overcome this issue, repeat the first stroke by adding one more iteration to the for loop:
import turtle my_turtle = turtle.Turtle() # Set the turtle's pen color my_turtle.pencolor("black") # Set the star's fill color my_turtle.fillcolor("yellow") # Begin filling the star my_turtle.begin_fill() # Draw the star for i in range(6): my_turtle.forward(100) my_turtle.left(144) # End filling the star my_turtle.end_fill() # Keep the turtle window open turtle.done()Output:
SummaryToday you learned how to use Turtle to draw a star in Python.
To recap, Python Turtle is a module that allows users to create simple graphics using turtle graphics in the Python programming language. It is commonly used to introduce beginners to the basics of programming and creating simple shapes and images.
The Turtle can be moved and instructed to draw lines, shapes, and other designs, making it a useful tool for creating interactive and visually appealing programs.
One great example is drawing a star with it which is what you learned today.
Thanks for reading. Happy coding!
Read AlsoHow to Draw a Christmas Tree in Python
You're reading How To Draw A Star In Python (Using Turtle): A Step
Speech To Text Conversion In Python – A Step
This article was published as a part of the Data Science Blogathon.
When it comes to our interactions with machines, things have gotten a lot more complicated. We’ve gone from large mechanical buttons to touchscreens. However, hardware isn’t the only thing that’s changing. Throughout the history of computers, the text has been the primary method of input. But thanks to developments in NLP and ML (Machine Learning), Data Science, we now have the means to use speech as a medium for interacting with our gadgets in the near future.
Virtual assistants are the most common use of these tools, which are all around us. Google, Siri, Alexa, and a host of other digital assistants have set the bar high for what’s possible when it comes to communicating with the digital world on a personal level.
IMAGE
For the first time in the history of modern technology, the ability to convert spoken words into text is freely available to everyone who wants to experiment with it.
When it comes to creating speech-to-text applications, Python, one of the most widely used programming languages, has plenty of options.
History of Speech to Text
Before diving into Python’s statement to text feature, it’s interesting to take a look at how far we’ve come in this area. Listed here is a condensed version of the timeline of events:
Audrey,1952: The first speech recognition system built by 3 Bell Labs engineers was Audrey in 1952. It was only able to read numerals.
IBM Shoebox (1962): Coils can distinguish 16 words in addition to numbers in IBM’s first voice recognition system, the IBM Shoebox (1962). Had the ability to do basic mathematical calculations and publish the results.
IMAGE
Defense Advanced Research Projects Agency(DARPA) (1970): Defense Advanced Research Projects Agency (DARPA) (1970): DARPA supported Speech Understanding Research, which led to the creation of Harpy’s ability to identify 1011 words.
Hidden Markov Model(HMM), the 1980s: Problems that need sequential information can be represented using the HMM statistical model. This model was used in the development of new voice recognition techniques.
Voice search by Google,2001: It was in 2001 that Google launched its Voice Search tool, which allowed users to search by speaking. This was the first widely used voice-enabled app.
IMAGE
Siri,2011: A real-time and convenient way to connect with Apple’s gadgets was provided by Siri in 2011.
IMAGE
Alexa,2014 & google home,2023: Voice-activated virtual assistants like Alexa and Google Home, which have sold over 150 million units combined, entered the mainstream in 2014 and 2023, respectively.
IMAGE
Problems faced in Speech to Text
Speech-to-text conversion is a difficult topic that is far from being solved. Numerous technical limitations render this a substandard tool at best. The following are some of the most often encountered difficulties with voice recognition technology:
1. Imprecise interpretation
Speech recognition does not always accurately comprehend spoken words. VUIs (Voice User Interfaces) are not as proficient at comprehending contexts that alter the connection between words and phrases as people are. Thus, machines may have difficulty comprehending the semantics of a statement.
2. Time
At times, speech recognition systems require an excessive amount of time to process. This might be due to the fact that humans possess a wide variety of vocal patterns. Such difficulties with voice recognition can be overcome by speaking slower or more precisely, but this reduces the tool’s convenience.
3. Accents
VUIs may have difficulty comprehending dialects that are not standard. Within the same language, people might utter the same words in drastically diverse ways.
4. Background noise and loudness
In a perfect world, these would not be an issue, but that is not the case, and hence VUIs may struggle to operate in noisy surroundings (public spaces, big offices, etc.).
How does Speech recognition work?
A complete description of the method is beyond the scope of this blog.А соmрlete desсriрtiоn оf the met in this blog. This is accomplished using the “Speech Recognition” API and the “PyAudio” library.
ownload the Python packages listed below
pip install SpeechRecognition
My audio (pip install Pyaudio)
Portaudio (pip install Portaudio)
Convert an audio file into textSteps
Import library for speech recognition
Initializing the recognizer class in order to do voice recognition. We аre utilizing Gооgle’s sрeeсh reсоgnitiоn teсhnоlоgy.
The following audio formats are supported by speech recognition: wav, AIFF, AIFF-C, and FLAC. In this example, I utilized a ‘wav’ file.
I’ve utilized an audio clip from a ‘stolen’ video that states “I have no idea who you are or what you want, but if you’re seeking for ransom, I can tell you I don’t have any money.”
Code
#import library import speech_recognition as sr #Initiаlize reсоgnizer сlаss (fоr reсоgnizing the sрeeсh) r = sr.Recognizer() # Reading Audio file as source # listening the аudiо file аnd stоre in аudiо_text vаriаble with sr.AudioFile('I-dont-know.wav') as source: audio_text = r.listen(source) # recoginize_() method will throw a request error if the API is unreachable, hence using exception handling try: # using google speech recognition text = r.recognize_google(audio_text) print('Converting audio transcripts into text ...') print(text) except: print('Sorry.. run again...')Output:
Speech is nothing more than a sound wave at its most basic level. In terms of acoustics, amplitude, peak, trough, crest, and trough, wavelength, cycle, and frequency are some of the characteristics of these sound waves or audio signals.
Due to the fact that these audio signals are continuous, they include an endless number of data points. To convert such an audio signal to a digital signal capable of being processed by a computer, the network must take a discrete distribution of samples that closely approximates the continuity of an audio signal.
Once we’ve established a suitable sample frequency (8000 Hz is a reasonable starting point, given the majority of speech frequencies fall within this range), we can analyze the audio signals using Python packages such as LibROSA and SciPy. On the basis of these inputs, we can then partition the data set into two parts: one for training the model and another for validating the model’s conclusions.
At this stage, one may use the Conv1d model architecture, a convolutional neural network with a single dimension of operation. After that, we may construct a model, establish its loss function, and use neural networks to prevent the best model from converting voice to text. We can modify statements to text using deep learning and NLP (Natural Language Processing) to enable wider applicability and acceptance.
Applications of Speech Recognition
There are more tools accessible for operating this technological breakthrough because it is mostly a software creation that does not belong to anyone company. Because of this, even developers with little financial resources have been able to use this technology to create innovative apps.
The following are some of the sectors in which voice recognition is gaining traction
Evolution in search engines: Speech recognition will aid in improving search accuracy by bridging the gap between verbal and textual communication.
Impact on the healthcare industry: The impact on the healthcare business is that voice recognition is becoming a more prevalent element in the medical sector, as it speeds up the production of medical reports. As VUIs improve their ability to comprehend medical language, clinicians will gain time away from administrative tasks by using this technology.
Service providers: Telecommunications companies may rely even more on speech-to-text technology that may help determine callers’ requirements and lead them to the proper support.
Conclusion
A speech-to-text conversion is a useful tool that is on its way to becoming commonplace. With Python, one of the most popular programming languages in the world, it’s easy to create applications with this tool. As we make progress in this area, we’re laying the groundwork for a future in which digital information may be accessed not just with a fingertip but also with a spoken command.
The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.v
Related
How To Create A Zip File Using Python?
ZIP is an archive file format used to for lossless data compression. One or more directories or files are used to create a ZIP file. ZIP supports multiple compression algorithms, DEFLATE being the most common. ZIP files have .zip as extension. In this article we are going to discuss how to create a Zip file using Python.
Creating uncompressed ZIP file in Python Using shutil.make_archive to create Zip filePython has a standard library shutil which can be used to create uncompressed ZIP files. This method of creating ZIP file should be used only to organize multiple files in a single file.
SyntaxFollowing is the syntax of shutil.make_archive −
shutil.make_archive(‘output file name’, ‘zip’, ‘directory name’) ExampleFollowing is an example to create ZIP file using shutil.make_archive −
import
shutilimport
os.
path archived=
shutil.
make_archive(
'E:/Zipped file'
,
'zip'
,
'E:/Folder to be zipped'
)
if
os.
path.
exists(
'E:/Zipped file.zip'
)
:
(
archived)
else
:
(
"ZIP file not created"
)
OutputFollowing is an output of the above code −
E:Zipped file.zip Creating compressed ZIP file in PythonCompressed ZIP files reduce the size of the original directory by applying compression algorithm. Compressed ZIP files result in faster file sharing over a network as the size of the ZIP file is significantly smaller than original file.
The zipfile library in python allows for creation of compressed ZIP files using different methods.
Creating ZIP file from multiple filesIn this method, ZipFile() creates a ZIP file in which the files which are to be compressed are added. This is achieved by creating object of ZipFile using with keyword and then writing the files using .write() method.
ExampleFollowing is an example to create ZIP file using multiple files −
import
osfrom
zipfileimport
ZipFilewith
ZipFile(
'E:/Zipped file.zip'
,
'w'
)
as
zip_object:
zip_object.
write(
'E:/Folder to be zipped/Greetings.txt'
)
zip_object.
write(
'E:/Folder to be zipped/Introduction.txt'
)
if
os.
path.
exists(
'E:/Zipped file.zip'
)
:
(
"ZIP file created"
)
else
:
(
"ZIP file not created"
)
OutputFollowing is an output of the above code −
ZIP file created Creating ZIP file from entire directoryIn this method, a for loop is used to traverse the entire directory and then add all the files present in the directory to a ZIP file which is created using ZipFile.
ExampleFollowing is an example to create ZIP file from entire directory −
import
osfrom
zipfileimport
ZipFilewith
ZipFile(
'E:/Zipped file.zip'
,
'w'
)
as
zip_object:
for
folder_name,
sub_folders,
file_namesin
os.
walk(
'E:/Folder to be zipped'
)
:
for
filenamein
file_names:
file_path=
os.
path.
join(
folder_name,
filename)
zip_object.
write(
file_path,
os.
path.
basename(
file_path)
)
if
os.
path.
exists(
'E:/Zipped file.zip'
)
:
(
"ZIP file created"
)
else
:
(
"ZIP file not created"
)
OutputFollowing is an output of the above code −
ZIP file created Creating ZIP file from specific files in a directoryIn this method, lambda function is used to filter files with specific extensions to be added in the ZIP file. The lambda function is passed as parameter to a function in which the files are filtered based on the extension.
ExampleFollowing is an example to create ZIP file using specific files in a directory −
import
osfrom
zipfileimport
ZipFiledef
zip_csv
(
directory_name,
zip_file_name,
filter
)
:
with
ZipFile(
zip_file_name,
'w'
)
as
zip_object:
for
folder_name,
sub_folders,
file_namesin
os.
walk(
directory_name)
:
for
filenamein
file_names:
if
filter
(
filename)
:
file_path=
os.
path.
join(
folder_name,
filename)
zip_object.
write(
file_path,
os.
path.
basename(
file_path)
)
if
__name__==
'__main__'
:
zip_csv(
'E:/Folder to be zipped'
,
'E:/Zipped file.zip'
,
lambda
name:
'csv'
in
name)
if
os.
path.
exists(
'E:/Zipped file.zip'
)
:
(
"ZIP file created with only CSV files"
)
else
:
(
"ZIP file not created"
)
OutputFollowing is an output of the above code −
ZIP file created with only CSV filesHow To Create A Slideshow In Lightroom (Step By Step)
While you’re likely familiar with the Library and Develop modules in Lightroom, there is another feature that you might find quite helpful, which is the Slideshow module. This allows you to create stunning slideshows of your images that can have various uses, from acting as a portfolio to presenting images to friends and family.
Creating a Slideshow may seem like a daunting task, especially as there is so much you can customize to your needs such as editing transitions and effects, adding text overlays and branding, and even including an audio track to play during the slideshow.
How To Create A Slideshow In LightroomFollow these steps to create your own customized slideshow in Lightroom, using the photos of your choice.
Step 1: Select The Photos For Your SlideshowThe first thing you’ll need to do before creating your slideshow is select the images you’d like to present. To do this, first, make sure you’ve uploaded all your images. Then, in the Library module, go through and select the photos you’d like to include.
Now you can either select images from the grid or in the filmstrip below. Selected photos will turn a lighter gray than the rest.
Once you’ve selected your chosen images, head to the Slideshow module to create the slideshow.
Step 2: Choose The Playback Order For Your PhotosHere, the images you chose appear selected in the film strip below. You’ll see other similar images to the ones you selected images if you go through the slideshow using the left and right arrow keys. Lightroom includes these as options to add to your slideshow. To arrange the order you’d like the photos to be presented, drag the photos around the filmstrip.
You can also randomize the order of slides by heading to the Playback panel on the right and checking Random Order.
Step 3: Add A Frame To Your Slideshow (Optional)This step is optional, but you’ll notice that a border sits around your images in the slideshow, and you can choose to customize this border if you’d like. Head to the Options panel on the right.
If you’d like your images to fill the frame, check Zoom to Fill Frame.
Underneath, you can check whether or not you’d like a border around your images. Drag the toggle to increase the width of the border’s stroke.
Below, you can set whether or not you’d like the image to cast a shadow by checking Cast Shadow. Then, set the shadow’s Opacity, Offset (the distance from the image where the shadow sits), Radius, and Angle.
Step 4: Add Text To Your Slideshow In The Overlays PanelThe next step is to add any overlays, such as text or a watermark, that you’d like to your images. This is useful if you’d like to display a caption on each slide or if you’d like to add personal branding to the slideshow. For this, we’ll work in the Overlays tab.
Step 5: Choose Your Transitions & Transition SpeedThe next way you can customize your slideshow is by setting the rate at which your slides and transitions will play. To do this, head to the Playback panel.
Drag to increase or decrease the Slide Length and the length of the Crossfade transition between slides.
Keep in mind that if you export your slideshow as a PDF, the playback settings like slide duration and transitions will not apply. The slide duration and transitions are used when exporting the slideshow as a video.
Step 6: Add Music In The Music PanelYou can select up to 10 files to play, and they’ll play sequentially in the order you selected the files. You can add, reorder, or remove the tracks in the Music panel.
Step 7: Add An Intro & Outro Title Card (Optional)To add an intro or outro, head to the Titles tab, and set a plain colored slide as the first and/or last slide of the slideshow, with or without an identity plate. Check the Intro Screen and/or Ending Screen to set these up.
Step 8: Play Your SlideshowYou can press the spacebar to pause and resume the slideshow and use the left and right arrow keys to move the slideshow forward or backward.
How To Create A Slideshow Template In LightroomA template is a set of preselected settings that act as a layout for your slideshow. You can create a template out of a slideshow you’ve made to use again in the future.
How To View A Slideshow In Full Screen In LightroomDo this for each panel, and make sure you’re working in full screen already. The slideshow will then take up as much of the screen as possible. You can also press Shift + Tab to toggle the view of all panels.
This only matters when you are still adjusting the settings of your slideshow since it automatically goes to full screen when you press Play on your slideshow.
How To Export A Slideshow From LightroomThere are different options for exporting your slideshow, and it’s important to know what features come with each. All options are available while working in the Slideshow module.
Remember that slideshows exported as PDFs will not include the music, randomized images, or any duration settings.
You can also export your slideshow as a series of JPEG files, including everything you see in each specific slide, including the layout, background, and any overlays. Again, Lightroom will not export transitions, playback options, and music.
Want A Fast Way To Edit Your Slideshow Images In Lightroom?Creating the slideshow is only half of the work you need to do. Before the slideshow is ever made, you need to edit all the photos beforehand to make them picture perfect. Depending on how many photos are in your slideshow, the editing process can take a lot longer than you hoped for. So to help speed up your photo editing, be sure to download my free Lightroom Starter Kit preset bundle that includes 12 Lightroom presets for faster photo editing!
How To Catch A Python Exception In A List Comprehension?
Before we understand how to catch a Python exception in a list comprehension, let us first learn what a list comprehension is.
List comprehension is a statement that allows you to create a list and execute a for loop, all in a single sentence.
This also allows the lists to be created from other iterables like tuples, strings, arrays, lists, and so on. The syntax of list comprehension is given below −
List = [expression(element) for element in list if condition]The python list and list comprehension capability, which may be used inside a single line of code to generate substantial functionality, are two of the language’s most distinguishing features.
There are no unique built-in methods in Python to handle exceptions that arise in list comprehensions. Hence, we can only do it using try/except blocks.
Example letters = [letter for letter in 'APPLE'] print(letters) Output ['A', 'P', 'P', 'L', 'E'] Exception Handling in List ComprehensionAn exception is an unexpected error or event that occurs during the execution of program. Errors and Exceptions are often confused as the same; when an error occurs in a program, it stops executing; but when an exception is encountered, the program deflects from its original course of execution. Hence, unlike errors, an exception can be handled. Therefore, you won’t have a program crash.
Many times, there are both valid and invalid exceptions. Exceptions are useful for managing errors and exceptional conditions in a program in a variety of ways. When you think that you have a code which can generate an error, you can utilize exception handling technique.
The raise exception statement can be used to raise an exception in your program. Raising an exception terminates current code execution and returns the exception until it is dealt with.
Handling Built-in ExceptionsLet’s look at some of the built-in exception handling in list comprehension.
ExampleSince we are working with lists, let us try to divide the elements of one list by the elements of another list. These lists can also include zero.
ZeroDivisionError is thrown when a finite number is divided by a zero. It is a built-in exception which is a part of the ArithmeticException class. This exception can be handled using a try-except block where we change the output whenever this exception is raised. We can understand this better using an example.
list_1 = [12, 23, 34, 45, 56] list_2 = [0, 1, 2, 3, 4] def func(a, b): try: return a/b except ZeroDivisionError: print("Division by zero not allowed") list_3 = [func(x, y) for x, y in zip(list_1, list_2)] print(list_3) Output Division by zero not allowed [None, 23.0, 17.0, 15.0, 14.0] ExampleValueError is an exception in Python which is raised when the argument passed to a function is of the correct data type but of invalid value. For example, passing negative integers to a function trying to find a square root of a number.
Consider a list that has integers, integers in string format, and words together. A new list must now be created by squaring the numerals (which are in string and int format). However, in this case, the string values must simply skip and no error notice must be issued.
list = ['10', '11', 7, 'abc', 'cats', 3, '5'] #helper function def func(a): try: return int(a)*int(a) except ValueError: pass # list comprehension new_list = [func(x) for x in list] print(new_list) OutputWe received no exception message since we only wanted to ignore the non-numerical values, and the None value was filled in the areas where an exception was raised.
[100, 121, 49, None, None, 9, 25]Other built-in exceptions can also be handled in the same way using the try-except block.
Handling User-defined ExceptionsThe user-defined exceptions can be anything from the value being in a specific range to the value being divisible by some number. A class that inherits the built in Exception class must be created for this. The exception can then be tested using the helper function. Consider the examples below.
ExampleConsider a list of integers. The goal is to pick out the integers that are divisible by two and form a new list. The number should be printed with an error message for the non-divisible numbers.
# creating class for user-defined exception handling class error(Exception): def __init__(self, a): chúng tôi = "The number "+str(a)+" is not divisible by 2" # helper function def util_func(a): try: if a % 2 != 0: raise error(a) return(a) except error as e: print(e.msg) # input list list = [12, 23, 34, 45, 56, 67] # list comprehension to choose numbers # divisible by 2 new_list = [util_func(x) for x in list] print("nThe new list has :", new_list) Output The number 23 is not divisible by 2 The number 45 is not divisible by 2 The number 67 is not divisible by 2 The new list has : [12, None, 34, None, 56, None] ExampleCreate a new list from the existing one with values ranging between 10 and 20. We are raising an exception if the values fall outside the specified range, as shown in the example below.
# class for user-defined exception handling class error(Exception): def __init__(self, a): chúng tôi = "The num "+str(a)+" is out of range!!!" # helper function def util_func(a): try: raise error(a) return(a) except error as e: print(e.msg) return 0 # input list new_list = [12, 23, 34, 45, 56, 67] # list comprehension to choose the numbers # in range 10 to 20 new_li = [util_func(x) for x in new_list] print("nThe new list are:", new_list) OutputOutput The output for the program above is displayed as follows −
The num 23 is out of range!!! The num 34 is out of range!!! The num 45 is out of range!!! The num 56 is out of range!!! The num 67 is out of range!!! The new list are: [12, 23, 34, 45, 56, 67]How To Create Named Ranges In Excel (A Step
What’s in the name?
In this tutorial, you’ll learn how to create Named Ranges in Excel and how to use it to save time.
If someone has to call me or refer to me, they will use my name (instead of saying a male is staying in so and so place with so and so height and weight).
Right?
Similarly, in Excel, you can give a name to a cell or a range of cells.
Now, instead of using the cell reference (such as A1 or A1:A10), you can simply use the name that you assigned to it.
For example, suppose you have a data set as shown below:
In this data set, if you have to refer to the range that has the Date, you will have to use A2:A11 in formulas. Similarly, for Sales Rep and Sales, you will have to use B2:B11 and C2:C11.
While it’s alright when you only have a couple of data points, but in case you huge complex data sets, using cell references to refer to data could be time-consuming.
Excel Named Ranges makes it easy to refer to data sets in Excel.
You can create a named range in Excel for each data category, and then use that name instead of the cell references. For example, dates can be named ‘Date’, Sales Rep data can be named ‘SalesRep’ and sales data can be named ‘Sales’.
You can also create a name for a single cell. For example, if you have the sales commission percentage in a cell, you can name that cell as ‘Commission’.
Here are the benefits of using named ranges in Excel.
When you create Named Ranges in Excel, you can use these names instead of the cell references.
For example, you can use =SUM(SALES) instead of =SUM(C2:C11) for the above data set.
Have a look at ṭhe formulas listed below. Instead of using cell references, I have used the Named Ranges.
Sum of all the sales done by Tom: =SUMIF(SalesRep,”Tom”,Sales)
SUMIF (SalesRep,”Joe”,Sales)*Commission
You would agree that these formulas are easy to create and easy to understand (especially when you share it with someone else or revisit it yourself.
Another significant benefit of using Named Ranges in Excel is that you don’t need to go back and select the cell ranges.
You can just type a couple of alphabets of that named range and Excel will show the matching named ranges (as shown below):
By using Named Ranges in Excel, you can make Excel formulas dynamic.
For example, in the case of sales commission, instead of using the value 2.5%, you can use the Named Range.
Now, if your company later decides to increase the commission to 3%, you can simply update the Named Range, and all the calculation would automatically update to reflect the new commission.
Here are three ways to create Named Ranges in Excel:
Here are the steps to create Named Ranges in Excel using Define Name:
Select the range for which you want to create a Named Range in Excel.
In the New Name dialogue box, type the Name you wish to assign to the selected data range. You can specify the scope as the entire workbook or a specific worksheet, If you select a particular sheet, the name would not be available on other sheets.
This will create a Named Range SALESREP.
Select the range for which you want to create a name (do not select headers).
Go to the Name Box on the left of Formula bar and Type the name of the with which you want to create the Named Range.
Note that the Name created here will be available for the entire Workbook. If you wish to restrict it to a worksheet, use Method 1.
This is the recommended way when you have data in tabular form, and you want to create named range for each column/row.
For example, in the dataset below, if you want to quickly create three named ranges (Date, Sales_Rep, and Sales), then you can use the method shown below.
Here are the steps to quickly create named ranges from a dataset:
Select the entire data set (including the headers).
In the Create Names from Selection dialogue box, check the options where you have the headers. In this case, we select top row only as the header is in the top row. If you have headers in both top row and left column, you can choose both. Similarly, if your data is arranged when the headers are in the left column only, then you only check the Left Column option.
This will create three Named Ranges – Date, Sales_Rep, and Sales.
Note that it automatically picks up names from the headers. If there are any space between words, it inserts an underscore (as you can’t have spaces in named ranges).
There are certain naming rules you need to know while creating Named Ranges in Excel:
The first character of a Named Range should be a letter and underscore character(_), or a backslash(). If it’s anything else, it will show an error. The remaining characters can be letters, numbers, special characters, period, or underscore.
You can not use names that also represent cell references in Excel. For example, you can’t use AB1 as it is also a cell reference.
You can’t use spaces while creating named ranges. For example, you can’t have
Sales Rep
as a named range. If you want to combine two words and create a Named Range, use an underscore, period or uppercase characters to create it. For example, you can have Sales_Rep, SalesRep, or SalesRep.
While creating named ranges, Excel treats uppercase and lowercase the same way. For example, if you create a named range SALES, then you will not be able to create another named range such as ‘sales’ or ‘Sales’.
A Named Range can be up to 255 characters long.
Sometimes in large data sets and complex models, you may end up creating a lot of Named Ranges in Excel.
What if you don’t remember the name of the Named Range you created?
Don’t worry – here are some useful tips.
Here are the steps to get a list of all the named ranges you created:
Go to the Formulas tab.
If you have some idea about the Name, type a few initial characters, and Excel will show a drop down of the matching names.
If you have already created a Named Range, you can edit it using the following steps:
In the Edit Name dialog box, make the changes.
Close the Name Manager dialog box.
Here are some useful keyboard shortcuts that will come handy when you are working with Named Ranges in Excel:
To get a list of all the Named Ranges and pasting it in Formula: F3
To create new name using Name Manager Dialogue Box: Control + F3
To create Named Ranges from Selection: Control + Shift + F3
So far in this tutorial, we have created static Named Ranges.
This means that these Named Ranges would always refer to the same dataset.
For example, if A1:A10 has been named as ‘Sales’, it would always refer to A1:A10.
If you add more sales data, then you would have to manually go and update the reference in the named range.
In the world of ever-expanding data sets, this may end up taking up a lot of your time. Every time you get new data, you may have to update the Named Ranges in Excel.
To tackle this issue, we can create Dynamic Named Ranges in Excel that would automatically account for additional data and include it in the existing Named Range.
For example, For example, if I add two additional sales data points, a dynamic named range would automatically refer to A1:A12.
This kind of Dynamic Named Range can be created by using Excel INDEX function. Instead of specifying the cell references while creating the Named Range, we specify the formula. The formula automatically updated when the data is added or deleted.
Let’s see how to create Dynamic Named Ranges in Excel.
Suppose we have the sales data in cell A2:A11.
Here are the steps to create Dynamic Named Ranges in Excel:
In the New Name dialogue box type the following:
Name: Sales
Scope: Workbook
Refers to:
=$A$2:INDEX($A$2:$A$100,COUNTIF($A$2:$A$100,””&””))
Done!
You now have a dynamic named range with the name ‘Sales’. This would automatically update whenever you add data to it or remove data from it.
To explain how this work, you need to know a bit more about Excel INDEX function.
Most people use INDEX to return a value from a list based on the row and column number.
But the INDEX function also has another side to it.
It can be used to return a cell reference when it is used as a part of a cell reference.
For example, here is the formula that we have used to create a dynamic named range:
Hence, here it returns =$A$2:$A$11
If we add two additional values to the sales column, it would then return =$A$2:$A$13
When you add new data to the list, Excel COUNTIF function returns the number of non-blank cells in the data. This number is used by the INDEX function to fetch the cell reference of the last item in the list.
Note:
This would only work if there are no blank cells in the data.
In the example taken above, I have assigned a large number of cells (A2:A100) for the Named Range formula. You can adjust this based on your data set.
You can also use OFFSET function to create a Dynamic Named Ranges in Excel, however, since OFFSET function is volatile, it may lead a slow Excel workbook. INDEX, on the other hand, is semi-volatile, which makes it a better choice to create Dynamic Named Ranges in Excel.
You may also like the following Excel resources:
Update the detailed information about How To Draw A Star In Python (Using Turtle): A Step on the Katfastfood.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!