I'm using Pycharm and
I'm new to programming and I made something using input:
try:
name = (input("Enter your name: "))
print("Hello " + name)
age = int(input("Enter your age: "))
print(age)
except ValueError:
print("Invalid Input")
I would like the "name" string to only accept words not numbers
like when I run the program usually it looks like this:
Enter your name: "name"
Hello "name"
but when I put a number into it:
Enter your name: "14"
Hello "14"
I would like it to only accept words as an answer and input an error when an integer was put
Python has raise keyword to help us raise exceptions manually.
We check if the name is a number and raise a ValueError if so:
try:
name = input("Enter your name: ")
if name.isdigit():
raise ValueError
print("Hello " + name)
age = int(input("Enter your age: "))
print(age)
except ValueError:
print("Invalid Input")
On run:
Enter your name: 14
Invalid Input
Related
This is my code. I can input, but when I press enter, I get the error.
import math
x = 13
age = input("Please input your age.")
if x < age:
print("Nice, you can use this website!")
if x > age:
print("Sorry, you are too young")
if x == age:
print("Nice, you can use this website!")
input returns a str, not an int.
...
age = int(input("Please input your age"))
...
Also, consider consolidating your if statements like so:
if x <= age:
print("Nice, you can use this website!")
else:
print("Sorry, you are too young")
here is my code
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
age = int(age)
if age >18:
print("welcome")
#here i want to add my password number + strings
password = input("type your code now")
password = int(password)
if password==1234xyz:
print("okay")
else :
print("wrong")
if age < 18:
print("chole jao")
i want to add passwor liek 12323rtrt
You could do the error handling like follows -
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
if age.isdigit() == True:
age = int(age)
if age >18:
print("welcome")
else :
print('age should be a positive integer')
In the second case, you need to know that you cannot convert a string which as alphabets into an integer. So int(password) won't work if the password has some characters. Also, you don't really need to convert the password to an integer. You can directly check/compare the user-inputted password against correct password as follows -
password = input("type your code now")
if password=='1234xyz': # note '1234xyz' which is string can directly be used and this is correct way
print("okay")
else :
print("wrong")
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
If the password input is right it will print('OKAY') , and if the input is wrong it will say print('wrong password')
name=input("Enter your name: ")
print("Hello, " + name)
LEGAL_AGE=18
age = int(input("Please enter your age: "))
if age<18 :
print("GO HOME")
else:
password =input("TYPE YOUR PASSWORD : ")
if password==int(12345):
print('YES , YOU CAN ENTER NOW')
else:
print('WRONG')
You need to do it like this for it to work -
name=input("Enter your name: ")
print("Hello, " + name)
LEGAL_AGE=18
age = int(input("Please enter your age: "))
if age<18 :
print("GO HOME")
else:
password =input("TYPE YOUR PASSWORD : ")
if int(password)==12345:
print('YES , YOU CAN ENTER NOW')
else:
print('WRONG')
In your code, you are converting an already integer to int in the statement int(12345) which essentially doesn't have any effect. You need to convert the password to integer which is read by python as a string.
Do note that you are not required to convert the password to an integer, you can check it against a string as well like -
name=input("Enter your name: ")
print("Hello, " + name)
LEGAL_AGE=18
age = int(input("Please enter your age: "))
if age<18 :
print("GO HOME")
else:
password =input("TYPE YOUR PASSWORD : ")
if password=='12345':
print('YES , YOU CAN ENTER NOW')
else:
print('WRONG')
Both the above methods are correct.
I have a program that asks the user's name:
while True:
try:
name = str(input("Please enter your name > "))
except ValueError:
print("Please enter a valid name")
continue
else:
break
I want to prevent the user from entering an integer, but with the code above integers are accepted in a string. How can I prevent the user from entering an integer in the string?
Firstly, do not cast str as input returns an str. Note from the docs
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that
After you get the input into name you can have a if condition.
name = str(input("Please enter your name > "))
if (re.search('\d',name)):
print("Sorry your name contains a number")
And don't forget to import re
break when trying to cast to an int if an exception is raised as it is not an int:
while True:
name = input("Please enter your name > ")
try:
int(name)
except ValueError:
break
print("Please enter a valid name")
str.digit might work also but will fail on negative input.
To check if any character is a digit use any:
while True:
name = input("Please enter your name > ")
if any(ch.isdigit() for ch in name):
print("Please enter a valid name")
else:
break
You could also create a set of accepted characters:
from string import ascii_letters
st = set(ascii_letters)
while True:
name = input("Please enter your name > ")
if not st.issuperset(name):
print("Please enter a valid name")
else:
break
Where you might want to add -, " " and any other potential characters.
You can use the string method isdigit() to check if the string is just integers.
name = input("Please enter your name: ")
if name.isdigit() == True:
print ("That's not a name!")
Likewise, you can also use the method isalpha() to check if the string is just text. However, if there's a space, it will return False.
name = input("Enter your name: ")
if name.isalpha() != True:
print ("That's not a name!")
Maybe:
if len(set(name) - set('1234567890')) < len(set(name)):
name = input("Please enter a valid name: ")
Let's say you're asked for input, such as your age, but instead of putting your age in, you accidentally hit 'enter.' The program, however, ignores the keystroke and goes to the next step. Your age is not entered but is regarded as empty/null value.
How do you code to fix this problem?
Thank you
With a while loop, you do not need to write the input() function twice:
while True:
age = input('>> Age: ')
if age:
break
print('Please enter your age')
You might also check if the input is an integer and get an integer from the string. An empty string for age will also raise a ValueError exception:
while True:
try:
age = int(input('>> Age: '))
except ValueError:
print('Incorrect input')
continue
else:
break
age = raw_input("Age: ")
while not age: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error!"
age = raw_input("Age: ")
You can create a wrapper function for this.
def not_empty_input(prompt):
input = raw_input(prompt)
while not input: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error! No input specified."
input = raw_input(prompt)
return input
Then:
address = not_empty_input("Address: ")
age = not_empty_input("Age: ")