Ok the title is a bit weird. But, basically what i want to ask is:
read = input("Enter some numbers: ")
# The user should only enter numbers and nothing else
But the thing is the user can enter something else other than a numerical value.
How do i stop someone from entering an alphabet in realtime from the terminal?
Lets say the user inputs 123 then enters an "e". How do i make this e not even appear on the
terminal even if the user presses the e key?
you can repeat asking int values if user enters a string.
while True:
try:
# 👇️ use int() instead of float
# if you only accept integers
num = float(input('Your favorite number: '))
print(num)
break
except ValueError:
print('Please enter a number.')
Related
So I was trying to use a procedure(with a parameter)...I asked the user for inputs and created a validate function to check the inputs and see if they are strings...I checked it but the outputs are taking too long to output. How do I fix this?
I tried:
# Create Validate function
def validate_input(LETTER):
while True:
try:
if len(LETTER) == 0:
pass
except:
if len(LETTER) >= 2:
print('Sorry, please enter a single letter')
if LETTER.strip().isdigit():
print('Sorry, please enter a letter')
break
#Ask for inputs
# Create function to validate input that returns true or false. If false then ask for input again.
first_char = input('Enter first character(lower cases) or press Enter: ')
validate_input(first_char)
second_char = input('Enter second character(lower cases) or press Enter: ')
validate_input(second_char)
third_char = input('Enter third character(lower cases) or press Enter: ')
validate_input(third_char)
fourth_char = input('Enter fourth character(lower cases) or press Enter: ')
validate_input(fourth_char)
fifth_char = input('Enter fifth character(lower cases) or press Enter: ')
validate_input(fifth_char)
But it came out to be:
Enter first character(lower cases) or press Enter: 2
And from there it takes too much time to say it it must be a string...
Thank you in advance!
the input() function in python always take the inputs as string, if you want to get integer as input then the following functions would be used => int(input())
it is not taking too long to execute it just a logical error in your code ;)
lets say the the input is "hello" so the len("hello") is 5
now , the input goes to the validation function(your function) first it starts with infinite while loop with no terminal condition and starts to checks the condition len(LETTER) == 0 whether it is true or false but it won't raise any exception so it won't go to the except block where the actual terminal condition is located(break) so its keep running forever.
hope it'll be helpful for you, thank you.
Hello I am creating a registration program and need to ask the user to input their age . However I want to make sure its not a letter by just consisting of numbers. How do I limit the user to only getting a number and if they input other character a error message shows up
while True:
age = int(input("Age: "))
if not (age) != int:
print ("Not a valid age")
continue
else:
break
You can use try and except statements here.
try:
age=int(age) #Do not typecast the age variable before this line
except ValueError:
print("Enter number")
If you do not want the program to proceed until the user enters a number, you can use a flag variable and put the code block mentioned above in a while loop.
I'm taking an intro Python course and a little stuck on an assignment. Any advice or resources would be greatly appreciated!
Here's the problem:
Write a program in Python that will prompt the user to enter an account number consists of 7 digits.
After getting that account number from user, verify if the account is valid or not. You should have a list called current_accts that hold all valid accounts.
Current valid accounts are shown below and you must use them in your program.
5679034 8232322 2134988 6541234 3984591 1298345 7849123 8723217
Verifying the account number entered should be done in a function called check_account() that will accept the account entered by the user and also the list current_accts. This function should return a 1 if account is valid otherwise return 0 if account is not valid.
Here's what I've written so far, but I'm stuck and also receiving syntax errors for indentation in lines 6-15. I'm also receiving error messages saying that variable 'current_accts' is not defined.
prompt = "Please, enter the 8 digit account number: "
current_accts = current_accts[1:]
current_accts [-1] = "valid"
while True:
try:
userinput = current_accts(prompt)
if len(userinput ) > 8:
raise ValueError()
userinput = int(userinput)
except ValueError:
print('The value must be an 8 digit integer. Try again')
else:
break
userinput = str(userinput)
a =int(userinput[7])+int(userinput[5])+int(userinput[3])+int(userinput[1])
b1 = str(int(userinput[6])*20)
b2 = str(int(userinput[4])*20)
b3 = str(int(userinput[2])*20)
b4 = str(int(userinput[0])*20)
y = int(b1[0])+int(b1[1])+int(b2[0])+int(b2[1])+int(b3[0])+int(b3[1])+int(b4[0])+int(b4[1])
x = (a+y)
if x % 10 == 0:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
NOTE: If you are looking for cooked up code then please do not read the answer.
I can tell you the logic, I guess you are doing that wrong.
Logic:
Check whether the account number is 7 digit or not.
if condition 1 is true then Check if it is in the list of given accounts or not.
You can check condition 1 by checking is the condition 1000000<= user_input <10000000.
You can check the condition 2 by looping through the list.
You really have to go back and learn some of the basic syntax of python, because there are many problems with your code. Just google for python tutorials, or google specific issues, like how to get a user's input in python.
Anyway, I don't mean to insult, just to teach, so here's my solution to your problem (normally i wouldn't solve all of it, but clearly you made some effort):
current_accts = ['5679034', '8232322', '2134988', '6541234', '3984591', '1298345', '7849123', '8723217']
user_input = input("Please, enter the 7 digit account number: ")
if user_input in current_accts:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
I didn't place it in a function that returns 0 or 1 like your question demanded, I suggest you adapt this code to make that happen yourself
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have this code:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
phone = int(input("Enter your telephone no. : "))
I want the user to enter their telephone number. But if they type anything else apart from integers an error message comes up saying that you can only type integers. What I want to do is to loop this section of the code so that every time the user enters a non-integer value the error message comes up. So far all this code does is, it prints the error message only for the first time. After the first time if the user enters a non-integer value the program breaks.
Please provide a not too complicated solution...I'm just a beginner.
I'm thinking you're meant to use a while loop but I don't know how?
I believe the best way is to wrap it in a function:
def getNumber():
while True:
try:
phone = int(input("Enter your telephone no. : "))
return phone
except ValueError:
pass
You can do it with a while loop like this
while True:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
else: # this is executed if there are no exceptions in the try-except block
break # break out of the while loop
def erVal():
print("The value entered is not vaild, enter a valid value")
name = input("Enter your name ")
while True:
erVal()
if name.isalpha() is True:
break
does not loop back WHY??
i am trying to display the error message when the user leave the name input blank
the while loop works but it keeps running printing the errVal
To answer your question. Assuming the formatting is correct this code will enter an endless loop if a non alpha value is entered. It will not return to ask for the name again. Entering an alpha value for name will cause the break to be executed which will end the while loop.
I assume you meant something more like the following:
def erVal():
print("The value entered is not valid, enter a valid value.")
while True:
name = input("Enter your name ")
if name.isalpha() is True:
break # will exit the while if name is alpha
else:
erVal()
Python is very interactive, in the future I suggest you test smaller pieces of the code such as playing with the while loop to see what break does. This will improve your understanding of the code.