Python : Another Name Error - python

I have two sets of code that essentially have the same goal but neither work and come up with the same name error. I'm trying to make it so they only letters are accept as answers, not numbers. When a number is entered as the input the program works fine but letters do not. Pleases also note that I am still new to python and am looking for basic commands if possible. I know their are many other questions like this one but none that I found answered my question. The error that comes up specifically points out the Name = input("What's your name?\n") line. Thank you in advance!
1
LetterCheck = True
while LetterCheck == True:
Name = input("What's your name?\n")
if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):
print('Your name must NOT include numbers.')
else:
LetterCheck = False
print(Name)
2
LetterCheck = True
while LetterCheck == True:
Name = input("What's your name?\n")
global Name
try:
Name = int(Name)
except ValueError:
Name = str(Name)
LetterCheck = False
else:
print("Your name must NOT include numbers")
print(Name)
The Error
What's your name?
45
Your name must NOT include numbers
What's your name?
Will
Traceback (most recent call last):
File "C:/Users/Will/Documents/Python/Task 1 Debugging.py", line 3, in <module>
Name = input("What's your name?\n")
File "<string>", line 1, in <module>
NameError: name 'Will' is not defined

if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):
This will always tell you there is a number in your name, because "0" is a non-zero length string and therefore truthy. Python sees if "0" or and stops there because it already knows the whole thing must be true.
What you probably want is something more like:
if any(digit in Name for digit in "0123456789"):
Or, arguably better:
if any(char.isdigit() for char in Name):
The other one where you're trying to convert the name to an integer will only succeed in the conversion if the name is all digits, not if it contains a digit. That's not what you want so you shouldn't do it that way.

You're running this in Python2. In Python2, input evaluates the user's input AS CODE. This means when you do:
>>> input("Name: ")
Name: Will
It tries to evaluate to some variable named Will. There is no such variable, so it throws a NameError. You can test this by entering "Will" (note the quotes). Now it evaluates it as a string and should work properly. But of course you could also write import os; os.listdir() and get a list of the current directory followed by what will likely be a TypeError. input is not safe in Python2.
Instead (in Python2), use raw_input.

I would just like to point out a few things:
First, "1" or "2" or "3" or "4" will evaluate "1" or "2" which is true and stop. You have to write out "1" in name or "2" in name, etc. That's highly inefficient and you should look at the posted function for has_int() as that would be a better way to implement it.
Also a name may have digits and still won't probably be parsed as an int() and raise an error so the second check is not effective at determining if a string has any numbers, only if the string is only numbers
Finally, it's not necessary but it is good practice to name your variables with lowercase letters.
Also, your name error could be because of input if you python version is not 3. Try using raw_input() if that is the case.

The goal here is to check if a string contains numbers.
if it does, ask again.
else, quit
# return true if given string does not have any numbers in them.
def has_int(s):
return any(char.isdigit() for char in s)
# ask what the name is
name = input('What is your name?')
# check if this user input has int
while has_int(name):
# if it does, re-prompt
print('Name cannot include numbers')
name = input('What is your name?')
# finally, say the name
print('Your name is {}'.format(name))

Very glad that you have decided to reach out.
I think regular expressions (python module re) (more info here: https://docs.python.org/2/library/re.html) are right up your alley. Regular expressions will allow you to determine if your string matches a "mold" or a pattern, which you can define by yourself
Regular expressions are a very broad and deep subject that take a bit of time to get used to, but I think they're absolutely worth your time. Take this introductory, friendly tutorial: http://regexone.com/
Then, in python, you can try this:
import re
input_str = raw_input(">?") #reads user input
if re.match('[0-9]+', input_str): #if the input matches the pattern "one or more numbers in the string"
print "Only letters a-z allowed!" #error out of the program
sys.exit()
The thing of importance here is the part with [0-9]+, which means "one or more numbers, any of them from 0 to 9".
Alright, I know I messed up with my previous code but to make up for it I present a working alternative, OP can refactor their program a bit like the following:
import re
while True:
input_str = raw_input("What's your name? ") #reads user input
if ( re.match('[0-9]+', input_str) ): # while the input doesn't match the pattern "one or more numbers in the string"
print "Your name must NOT include numbers." #error out of the program
else:
break
print "if you see this, the entered name fullfilled the logical condition"
Good luck!

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

Assigning and Calling built-in functions from a dictionary (Python)

everyone. I am trying to solve a coding challenge as follows:
get a string from the user. Afterward, ask the user "What would you like to do to the string?", allow the user to choose the next functionalities:
"upper" - makes all the string upper case
"lower" - makes all the string lower case
" "spaces2newline" - reaplce all spaces in new lines
...
print the result
*Use a dictionary to "wrap" that menu
So, what I am getting from this is that I need to make a dictionary from which I can call commands and assign them to the string.
Obviously, this doesn't work:
commands = {"1" : .upper(), "2" : .lower(), "3" : .replace(" ",\n)}
user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)\n
\t1. Make all characters capital\n
\t2. Make all characters lowercase")
#other options as input 3, 4, etc...
But perhaps someone can recommend a way to make the idea work?
My main questions are:
Can you somehow assign built-in functions to a variable, list, or dictionary?
How would you call a function like these from a dictionary and add them as a command to the end of a string?
Thanks for any assisstance!
Use operator.methodcaller.
from operator import methodcaller
commands = {"1": methodcaller('upper'),
"2": methodcaller('lower'),
"3": methodcaller('replace', " ", "\n")}
user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")
result = commands[option](user_string)
The documentation shows a pure Python implementation, but using methodcaller is slightly more efficient.
Well, chepner's answer is definitely much better, but one way you could have solved this is by directly accessing the String class's methods like so:
commands = {"1" : str.upper, "2" : str.lower, "3" : lambda string: str.replace(string, " ", "\n")} # use a lambda here to pass extra parameters
user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")
new_string = commands[option](user_string)
By doing this, you're saving the actual methods themselves to the dictionary (by excluding the parenthesis), and thus can call them from elsewhere.
maybe you could do:
command = lambda a:{"1" : a.upper(), "2" : a.lower(), "3" : a.replace(" ",'\n')}
user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)")
print("output:",command(user_string)[options])
#\t1. Make all characters capital\n

Detecting keywords in input

So I am completely new to Python. I started a week ago. I am writing a simple chatbot and have come to a point where I would like to ask an open-ended question, and if it picks up certain keywords in the input, it will print a certain response. I basically need an if command to be able to detect if a certain word is used. I hope there is some way of doing this.
To detect substrings you can use the in operator.
Example:
>>> "Hello" in "Hello World!"
True
>>> "Python" in "Hello World!"
False
There are multiple ways of doing this best solution would be to use regular expressions that way you can detect multiple keywords easily instead of having a dozen of if and elif under each other.
An example :
import re
regex_name = re.compile(r'name?$', flags=re.IGNORECASE)
regex_age = re.compile(r'age?$', flags=re.IGNORECASE)
my_input = input("Name : John")
if (regex_name.match(my_input)):
print("The string Name was found")
elif( regex_age.math(my_input)):
print("The string age was found")
else:
print("Neither Name or Age were found")
You can do it like this:
inpt = input("How are you?")
if "good" in inpt:
print("Okay you are good")
else:
print("what happend?")
The input() asks the user for input and the if statement checks for keywords of the users answer.

Prevent input() from being anything but alphabet characters

I am attempting to make a program for the sake of self-knowledge. I want to ask the user what their name is, and I only want the user to be able to use letters from the alphabet to answer, or only strings. I do not want them to be able to answer with numbers, symbols, etc.
def cc():
name = (input("""Hello, what happens to be your first name?
> """))
if type(name) is str:
print("You have entered a name correctly.")
elif type(name) is int:
print("Your name cannot be an integer. Try again.")
cc()
cc()
You can enforce this requirement using str.isalpha. From the documentation:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
Here is an example program:
while True:
name = input('Enter a name using only alphabetic characters: ')
if name.isalpha():
break
Demo:
Enter name using only alphabetic characters: Bo2
Enter name using only alphabetic characters: Bo^&*(
Enter name using only alphabetic characters: Bob
Note this method will not work for people with hyphenated names such as "Anne-Marie".
I agree that this question is a little misleading. However, with what you have said, you just need to use a regex to accomplish this.
import re
...
if not re.findall('[^a-zA-Z]', 'abc1'):
print("You have entered a name correctly.")
else
print("Your name cannot be an integer. Try again.")
cc()

Python - Can't get "string.isalnum():" to work properly

I cannot get the code below to work properly. It works if the user enters numbers for the name and it prints the theName.isdigit. But if the user enters both numbers and letters, it accepts this and moves onto a welcome message that follows. Looking at this, is there a reason you can find why theName.isalnum is not working here but the one above is?
theName = raw_input ("What is your name?? ")
while theName.isdigit ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
elif theName.isalpha ():
print "Ok, great"
break
theName = raw_input ("What is your name?? ")
theName = raw_input ("What is your name?? ")
while not theName.isalpha ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
theName = raw_input ("What is your name?? ")
print "Ok, great"
The while condition should tell you when to stop looping, that is, when the input isalpha. Then, because the while loop stops when the input is correct, you can move the logic for what to do in that case below the loop.
Looping on isdigit is problematic because the string abc123 doesn't meet that condition, so you break out of the loop even though the name doesn't meet your criteria.
As mentioned by others your code has a few problems.
First, if the theName contains anything other than digits, you will never enter the while loop, because isdigit() will return False.
Next, the order of your tests means that you will only reach the isalpha() test if the entered name contains something other than letters or digits.
However, it is also overly complex. Assuming your goal is to get the user to enter a name consisting only of letters (i.e. no spaces, digits, or special characters)
theName = "1" # preseed with invalid value
firstTime = True
while not theName.isalpha():
if not firstTime:
print "Your name should not contain anything other than letters"
theName = raw_input("Please enter your name: ")
firstTime = False
print "OK, great. Hi " + theName
This will repeatedly prompt until the user enters a valid name.

Categories

Resources