This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I try to validate user input if is integer not in a function.
while True:
try:
number = int(input('Enter the number: '))
except ValueError:
print('Try again. Input phone number, must containing digits. ')
break
print (number)
If I enter number it works prints the number (however Pycharm tells me that variable number in last line might ve undefined) however when it crash instead asking for enter again:
Enter the number: s
Try again. Input phone number, must containing digits.
Traceback (most recent call last):
line 9, in <module>
print (number)
NameError: name 'number' is not defined
In a function it seems easier to make but in this case I'm lost.
break means you leave the loop, even if you've had the ValueError, despite number not being assigned yet.
Instead of putting the break outside the try, have you considered putting it inside, so it only triggers if number gets assigned successfully?
while True:
try:
number = int(input('Enter the number: '))
break
except ValueError:
print('Try again. Input phone number, must containing digits. ')
print(number)
Related
I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?
--Python
What's wrong in this code?
a=int(input('enter a number'))
b=list(range(1,11))
if a not in b:
int(input('enter a number'))
else :
print('ok')
output:
enter a number 89
enter a number 8
Please explain a bit further what it is you're trying to do, if you're trying to output "OK" for the second input of '8', then you need to change the logic of this code.
a=int(input('enter a number'))
this line prints "enter a number"
then your if statement checks if its within b
but if it's not it prints "enter a number" again without doing anything with it, as seen in the next line:
int(input('enter a number'))
try using a for loop or while loop if you want your code to run through the if-else blocks more than once.
also, notice that you didn't put the input inside variable a again.
EDIT: try this code:
print('enter a number')
a=int(input())
while a not in range(1,11):
print('enter a number')
a=int(input())
else :
print('ok')
I need to do this prompts in a function. Can someone please help me? I just don't understand how. I'm just a beginner.
This should be written in a function.
Prompt for two line numbers, one is the starting line of text to copy, and the second is the end line of the text to copy. Slice this part of the list, and add it to the end of the list as a single string.Check that the line numbers entered are valid. If they are invalid, ask for a line numbers again.
Prompt for a line number and then replace that line with a new one from the user. Check that the line number entered is valid. If it is invalid, ask for a line number again
Here's a skeleton to get you started. Use the input builtin function to get user input and check if they are valid in a while loop
def isValid(start, end):
# Check if your start and end numbers are value here
return start <= end
def getUserInput():
start = 0
end = -1
while True:
start = input("Enter starting line number: ")
end = input("Enter ending line number: ")
if not isValid(start, end):
print("Invalid input, try again")
else:
break
## Do what you want with the list here
return start, end
I'm new at Python and trying some exercises I found on-line. The one I'm busy with requires an text input first, folowed by an ineteger input.
I get stuck on the integer input which raises an error.
I've started by modifying the code slightly to test myself when I first got the error.
Eventually changed it backed to be exactly like the example/exercise had it, but both resulted in the same error, on the same line.
The error raised was:
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
I've checked around a bit and found it get's triggered when the input is empty, but according to what I've read the the rest of the code should handle that.
numOfGuests = int(input())
if numOfGuests:
I expected the code to ask for the input again if nothing was entered, but get the error instead.
Much appreciated.
Update:
I've managed to figure out a work-around, and even though it isn't a answer to my question, I'll take it.
For anyone that's interested, here's what I did:
I changed:
numOfGuests=int(input())
to:
numOfGuests=input()
Only once something was entered did I convert it:
numOfGuests=int(numOfGuests)
so the final block is:
numOfGuests=''
while not numOfGuests:
print('How many guests will you have?')
numOfGuests = input()
numOfGuests=int(numOfGuests)
Any ideas to improve it, or some insight, would be appreciated.
I know this question is 10 months old but I just want to share the reason why you are having an error ValueError.
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
Is because the input() function reads any value and convert it into a string type. Even if you try to input empty or blank.
Sample code:
any_input = input("Input something: ")
print(f"Your input is: [{any_input}]")
Ouput:
Input something:
Your input is: []
Then the blank or empty string will be passed inside the int() function. The int() function will try convert string into an integer with a base of 10. As we all know, there is no blank or empty numbers. That is why it is giving you a ValueError.
To avoid this, we need to use try-except/EAFP in your code:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
except:
# Handle Value Error
And put inside a While-loop to repeat until input is valid.
Sample code:
while True:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
# If input is valid go to next line
break # End loop
except:
# Handle Value Error
print("Invalid input!")
print(f"The number of guest/s is: {numOfGuests}")
Ouput:
How many guest will you have? 3
The number of guest/s is: 3
Basically I have a variable equal to a number and want to find the number in the position represented by the variable. This is what I
numbertocheck =1
loopcriteria = 1
while loopcriteria == 1:
if numbertocheck in ticketnumber:
entryhour.append[numbertocheck] = currenttime.hour
entryminute.append[numbertocheck] = currenttime.minute
print("Thank you. Your ticket number is", numbertocheck)
print("There are now", available_spaces, "spaces available.")
loopcriteria = 2
I get this error (in pyCharm):
Traceback (most recent call last): File
"/Users/user1/Library/Preferences/PyCharmCE2017.3/scratches/scratch_2.py",
line 32, in entryhour.append[numbertocheck] =
currenttime.hour TypeError: 'builtin_function_or_method' object does
not support item assignment
How do I do what I'm trying to do?
Though you haven't provided the complete code, I think you only have problem with using append. You cannot use [] just after an append. To insert into a particular position, you need insert
Putting the relevant lines you need to replace below...
entryhour.insert(numbertocheck,currenttime.hour)
entryminute.insert(numbertocheck,currenttime.minute)
# available_spaces-=1 # guessing you need this too here?
P.S. your loop doesn't seem to make sense, I hope you debug it yourself if it doesn't work the way you want.