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

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.

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.

Python - Validation to ensure input only contains characters A-Z

I'm creating a program in Python 3.x where it asks the user for their first name and then last name and stores these in variables which are then concatenated into one variable:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
I tried:
while True:
try:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
break
except ValueError:
print("That's invalid, please try again.")
which ensures that a string is inputted, but inputting 'bob38', '74' or '][;p/' all count as string values, so these would be accepted, which is not what I want to happen.
I want valid input to only contain the letters A-Z/a-z (both uppercase and lowercase), and if the input contains anything else, an error message is outputted (e.g. 'That's invalid, try again.') and the user is asked the question again. How would I do this?
What you want to do is actually check if your string is not isalpha() and output an error and continue your loop until you get a valid entry.
So, to give you an idea, here is a simple example:
while True:
name = input("input name")
if name.isalpha():
break
print("Please enter characters A-Z only")
print(name)
Note, that as mentioned in the comments to this question, this is limited to only names that contain letters. There are several valid names that will contain ' and - that should probably be considered when wanting to validate names.
There is another solution. It's not as efficient as using re or isalpha but allows you to easily customize the characters you allow:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# Just insert other characters into that string if you want to accept anything else.
while True:
firstName = input("What's your first name? ")
if all(char in valid_characters for char in firstName):
break
print("That's invalid, please try again.")
The all checks if all characters from firstName are contained in the valid_characters string and returns False if any of them is not in it.
So to add whitespace and minus - you can alter it slightly:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -'
# whitespace is here ------------------------------^
assert all('a'<=letter<='z' or 'A'<= letter <= 'Z' for letter in name)
This will throw an error if name contains a non alphabet letter.
You can use a simple regular expression for this -
import re
is_valid_name = r'[a-zA-Z]+'
if bool(re.match(firstName, is_valid_name)) and bool(re.match(lastName, is_valid_name)):
name = firstName + lastName
else:
print('thats invalid')

Python : Another Name Error

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!

Issue with my python code

anwser=str(input("Do you need a new phone? "))
if answer== "no":
print ("You are now finished. ")
else:
question1=str(input("Do you know what phone you want? ")
if question1== "no":
print("Research different phones and chose which pne you like best.")
else:
question2=str(input("Do you want to go on a contract? ")
if question2== "no":
question3=str(input("Do you have enought money to pay full price for your phone? ")
What is wrong? How do I improve? It keeps coming up with a syntax error and I don not know why.
You're missing closing parentheses on your question lines:
question1 = str(input("Do you know what phone you want? ")
Should be:
question1 = str(input("Do you know what phone you want? "))
You also don't need to convert the input to a string, because input() already does that for you:
input([prompt])
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that.

Python Encryption

So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Use raw_input if you expect a string:
plainNum = raw_input("enter a number to encode ")
input() interprets the input as if it is Python code; enter 5 and it'll return an integer, enter 'some text' (with quotes) and it'll return a string. raw_input() on the other hand returns the entered input uninterpreted.
Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):
This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.
you maybe also wanna change key to Key to reflect what variable is declared
and also make codeNum initially equal to '' instead of ' ' (no space vs space)
just book keeping stuff

Categories

Resources