In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what to do if the user's input is wrong in Python". In the daily operation, I believe that many people have doubts about what to do if the user's input is wrong in Python. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the question of "what to do if the user's input is wrong in Python". Next, please follow the editor to study!
The problem comes from life. When I was working on an amateur project last week, I encountered a very interesting design question: "what if the user typed incorrectly?" If you enter an error, the following occurs:
Dictionaries in Python represent keys (keys) and values (values). For example:
Student_grades = {'John':' Aids, 'Rob':' B'} # To check grade of John, we call print (student_grades ['John']) # Output: a
What happens when you try to access a key that doesn't exist?
Print (student_grades ['Maple']) # Output: KeyError Traceback (most recent call last) in-> print (student_grades [' Maple']) KeyError: 'Maple'
You will receive a key error (KeyError) prompt.
KeyError occurs whenever the dict () request object is a key that does not exist in the dictionary. This error is common when receiving user input. For example:
Student_name = input ("Please enter student name:") print (student_ grades [student _ name])
This article will provide you with several ways to deal with the Python dictionary keyerror. Try to build an python intelligent dictionary that can help you deal with user input errors.
Set default value
A very easy way to do this is to return the default value if the requested key does not exist. You can do this using the get () method:
Default_grade = 'Not Available' print (student_grades.get (' Maple',default_grade)) # Output: # Not Available
Solve the case problem
Suppose you build an Python dictionary that contains population data for a specific country. The code will require the user to enter a country name and output to show its population.
# population in millions. (Source: https://www.worldometers.info/world-population/population-by-country/) population_dict= {'China':1439,' India':1380, 'USA':331,' France':65,'Germany':83 'Spain':46} # getting userinput Country_Name=input (' Please enterCountry Name:') # Access populationusing country name from dict print (population_ requests [country _ Name]) # Output Please enter Country Name: France 65
However, suppose the user typed 'france'. At present, in our dictionary, the first letters of all keys are capitalized. So what will the output be?
Pleaseenter Country Name:france-KeyError Traceback (most recentcall last) in 2 Country_Name = input ('Pleaseenter Country Name:') 3-> 4 Print (population_ requests [country _ Name]) KeyError: 'france'
Because 'france' is not a key in the dictionary, you will receive an error message.
A simple solution: store all country names in lowercase letters. In addition, all content entered by the user is converted to lowercase.
# keys (Country Names) are now alllowercase population_dict = {'china':1439,' india':1380, 'usa':331,' france':65,'germany':83, 'spain':46} Country_Name=input (' Please enterCountry Name:'). Lower () # lowercase input print (population_ countries [country _ Name]) Please enterCountry Name:france 65
Deal with spelling mistakes
However, suppose the user entered 'Frrance' instead of' France'. How can we solve this problem?
One way is to use conditional statements.
We will check whether the given user input can be used as a key. If not available, the output displays a message. It's best to put it in a loop statement and break on some special flag input (such as exit).
Population_dict = {'china':1439,' india':1380, 'usa':331,' france':65,'germany':83 'spain':46} while (True): Country_Name=input (' Please enterCountry Name (type exit to close):'). Lower () # break from code if user enters exit ifCountry_Name=='exit': Break ifCountry_Nameinpopulation_dict.keys (): print (population_ requests [country _ Name]) else: print ("Pleasecheck for any typos. Data not Available for ", Country_Name)
The loop continues to run until the user enters exit.
Optimization method
Although the above methods are "effective", they are not "intelligent" enough. We want the program to be powerful and able to detect simple spelling errors, such as frrance and chhina (similar to Google search).
I found several libraries suitable for solving key error, of which my favorite is the standard python library: difflib.
Difflib can be used to compare files, strings, lists, and so on, and generate different forms of information. This module provides various classes and functions for comparing sequences. We will use two functions of difflib: SequenceMatcher and get_close_matches. Let's take a quick look at these two functions.
1. # SequenceMatcher
SequenceMatcher is a class in difflib that is used to compare two sequences. The objects we define are as follows:
Difflib.SequenceMatcher (isjunk=None,a='', baked cards, autojunk=True)
Isjunk: used to mark unwanted junk elements (white space, newline characters, etc.) when comparing two blocks of text. Thus forbidding the passage of questionable text.
An and b: compare strings.
Autojunk: a heuristic that automatically treats some sequence items as junk.
Let's use SequenceMatcher to compare the strings chinna and china:
From difflib importSequenceMatcher# import # creating aSequenceMatcher object comparing two strings check = SequenceMatcher (None, 'chinna',' china') # printing asimilarity ratio on a scale of 0 (lowest) to 1 (highest) print (check.ratio ()) # Output # 0.90909090909091
In the above code, the ratio () method is used. Ratio returns a measure of sequence similarity as a floating-point value in the range [0meme1].
2. # get_close_matches
A method of comparing two strings based on similarity is provided.
What happens if we want to find all strings that are similar to a particular string (stored in the database)?
Get_close_matches () returns a list of the best matches in the list of possibilities.
Difflib.get_close_matches (word,possibilities, nasty 3, cutoff=0.6)
Word: a matching string is required.
Possibilities: a list of strings that match words.
Optional n: the maximum number of matches to return. By default, it is 3; it must be greater than 0.
Optional cutoff: the similarity must be higher than this value. The default is 0.6.
The potential best n matches will be returned to a list and sorted by similarity score, with the most similar first.
Take a look at the following example:
From difflib importget_close_matches print (get_close_matches ("chinna", ['china','france','india','usa'])) # Output # [' china'] so far, the study of "what to do if the user's input is wrong in Python" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.