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.
Related
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.')
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 have a while statement which works well and I have a whole section of code that asks the user to input how many names they have which will then ask them for a name that amount of times and then each time a name will be entered.
I need the section of the names entered to be error tapped but I don't know how to do it, as I have a while statement and I may need to put another while statement in, although I have error tapped the section for amount of names in numbers.
Also there is code further on with a dictionary and sorts but I need help with the one section of error tapping started at while currentnum part
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
Yep. The easiest way to describe what you're doing is to use the .isalpha attribute in an if statement. First you will have to def your while loop
Like the following:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
Baisically you have to define the loop and then run it. The if statement(which is the part you should add to your loop) then checks if there is nothing other than letters. If true, your done with error trapping and the loop is exited. The program continues outside the loop. If not then the while is repeated because the Loop() function is called again.
Your code looks very good to me. I dont see what input can the user put that could cause an error, since most data in python can be stringed AND names can be pretty much anything!. If you could comment exactly what error could be caused i might be able to help you
I wrote this code that I'm trying to get it to work. What I am trying to do is to prompt user to enter names of employees and use a list to store the names.
Now the part that I am having trouble with is with the loop, the loop is suppose to stop when the user types 'done', and then display the number of names entered, and with another loop, display the names entered each on its own line.
I don't know what I am doing wrong with the code but, after the user enters then names it will say: 'Press enter to continues adding names' and it will also say: 'If you would like to stop adding names, type=done'
If the user hits enter, then it should ask for another name and repeat the questions to see if user wants to add more or stop. But for some reason, even if the user press enter to continue adding names, it still outputs the number of names entered and the list of names. I don't want that to happen, I'm trying to get it to where it will display the result ONLY if the user types 'done' but the word 'done, cannot be displayed in the output. I've looked over and over the code and can't figure out what if am doing wrong.
Here is my code:
employee_list=[]
stop='done'
while stop == 'done':
employee_name=input('Enter name of employee:')
employee_list.append(employee_name)
print('Press enter to continues adding names')
enter_another=input('If you would like to stop adding names, type=done ')
print()
list_size=len(employee_list)
print('The number of employees you have entered: ', list_size)
for index in range(list_size):
print(employee_list[index])
You haven't got a check in your code if a person types done.
For example:
if enter_another == "done":
stop == "finished now"
But this doesn't make sense, your check is saying "if stop is done then keep going", which makes no sense semantically.
Try this instead:
more_employees = True
while more_employees: # Never do thing == True
# ... your code
enter_another=input('If you would like to stop adding names, type=done ')
if enter_another == "done":
more_employees = False
# ... the rest of your code
As stated, PEP8 recommends against comparing thing == True:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
Try this. I have put your printing condition outside the loop.
employee_list=[]
stop='done'
while stop == 'done':
employee_name=raw_input('Enter name of employee: ')
employee_list.append(employee_name)
print 'Press enter to continue adding names'
enter_another=raw_input('If you would like to stop adding names, type=done \n')
if enter_another == 'done':
stop = 'random'
print
list_size=len(employee_list)
print 'The number of employees you have entered: ', list_size
for index in range(list_size):
print employee_list[index],
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.