Parameters bypassing when a "ser" is entered rather than a number - python

I have a function that I need to return back with the original question if there is text input rather than the number in the range given.
When I type in SER for instance to test the program it comes back with an error. I need a number to be input which relates to a given piece of code based on that number. How can I alter this?
def Choice(question):
choiceanswer=input(question)
if choiceanswer in range(1,6):
return choiceanswer
else:
return Choice(question)
loop = True
while loop:
DisplayMenu()
choiceanswer = Choice('Please make your choice:')
if choiceanswer == 1:
student = []
n = numberofstudentstoadd('How many students do you wish to add? You
can add between 1 and 5')
for count in range(0, n):
when I test this code the question for choice is reoccurring each time I put a number from the range in or it crashes/error message when I type text.
I need the program to run so that when I type 1-6 the number corresponds with the task I have asked it to do so for this instance 1 is to input student data. When text is input I need the question to reappear to make the user insert a number 1 to 6 based on the range. Hope this make better sense.
This is what is shown in the program:
MAIN MENU
1. Enter and store student details
2. Retrieve details of any student
3. Student List: Birthday Order
4. Student Email List
5. Full Student List
6. Exit
Please make your choice:e
Traceback (most recent call last):
File "E:\BCS\From desktop\Validation 3\tutor.py", line 84, in <module>
choiceanswer = Choice('Please make your choice:')
File "E:\BCS\From desktop\Validation 3\tutor.py", line 72, in Choice
choiceanswer=int(input(question))
ValueError: invalid literal for int() with base 10: 'e'

question for choice is reoccurring each time I put a number from the range
Well of course, you are not setting the loop variable to False anywhere, so the while condition is always positive.
it crashes/error message when I type text
That's because input function evaluates input as Python code. When you enter SER, it doesn't mean a string "SER", but a variable SER – and you end up with NameError.
You should use raw_input instead. Besides being the reason for your error, the input function is also quite dangerous. And actually, in Python 3, input is replaced with raw_input.
solution
Your code could look like this
def choose(question):
choiceanswer = raw_input(question)
if choiceanswer == 'SER':
global loop
loop = False
return
if int(choiceanswer) in range(1, 6):
return choiceanswer
else:
return choose(question)
loop = True
while loop:
...

Related

Can someone explain why var = input() in python doesn't work?

You want to know your grade in Computer Science, so write a program
that continuously takes grades between 0 and 100 to standard input
until you input "stop", at which point it should print your average to
standard output.
NOTE: When reading the input, do not display a prompt for the user.
Use the input() function with no prompt string. Here is an example:
grade = input()
grade = input()
count = 0
sum = 0
while grade != "stop":
grade = input()
sum += int(grade)
count += 1
print(sum / count)
Please dont solve it for me, but if you can point out why setting grade as "input()" doesnt work
You input a line as the first operation and then correctly enter the loop only if it isn't "stop".
However, that should then be the value you use for summing rather than immediately asking the user for another value. In your current code, if the user enters "stop", there is no check before attempting to treat it as a number.
So, if you don't want a solution, I'd suggest you stop reading at this point :-)
Couldn't resist, could you? :-)
The solution is to simply move the second input call to the bottom of the loop, not the top. This will do the check on the last thing entered, be that before the loop starts or after the value has been checked and accumulated.
In addition, your print statement is inside the loop where it will print after every entry. It would be better
There's other things you may want to consider as well, such as:
moving your print outside the loop since currently you print a line for every input value. You'll also have to catch the possibility that you may divide by zero (if the first thing entered was "stop").
handling non-numeric input that isn't "stop";
handling numeric input outside the 0..100 range.
Don't use this since you're trying to educate yourself (kudos on you "please don't solve it for me" comment by the way) and educators will check sites like SO for plagiarism, but a more robust solution could start with something like:
# Init stuff needed for calculating mean.
(count, total) = (0, 0)
#Get first grade, start processing unless stop.
grade = input()
while grade != "stop":
# Convert to number and accumulate, invalid number (or
# out of range one) will cause exception and not accumulate.
try:
current = int(grade)
if current < 0 or current > 100:
throw("range")
# Only reaches here if number valid.
total += int(grade)
count += 1
except:
print(f'Invalid input: {grade}, try again')
# Get next grade and check again at loop start.
grade = input()
# If we entered at least one valid number, report mean.
if count > 0:
print(total / count)
the first input does not work, covered by the second input;
when input is "stop", int("stop") is wrong;
When reading the input, do not display a prompt for the user. you should print the ans after the while loop
you can use endless loop and break to solve this problem.
...
while True:
grade = input()
if grade == 'stop':
break
...
print(ans)

Python user defined list not being recognised within a while true loop

Thanks firstly for bearing with me as a relative newcomer to the world of Python. I'm working on a simple set of code and have been racking my brain to understand where I am going wrong. I suspect it is a relatively simple thing to correct but all searches so far have been fruitless. If this has been covered before then please be gentle, I have looked for a couple of days!
I'm working on the following and after catching and correcting a number of issues I suspect that I'm on the last hurdle:-
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(our_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(our_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(our_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
main()
else:
print("Goodbye")
break`
For some reason the appended (our_list) is not being recognised within the while true loop rendering the statistics calculation void. Any steer would be really appreciated as to where I am missing the obvious, thanks in advance.
Cheers
Bryan
I'm not sure exactly what you mean by "not being recognized", but our_list is a local variable inside main, so it can't be used anywhere but inside main.
So, if you try to use it elsewhere, you should get a NameError.
If your code actually has a global variable with the same name as the local variable that we aren't seeing here, things can be more confusing—you won't get a NameError, you'll get the value of the global variable, which isn't what you want.
The best solution here is to return the value from the function, and then have the caller use the returned value. For example:
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
return our_list
the_list = main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(the_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(the_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(the_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
the_list = main()
else:
print("Goodbye")
break
There are other options—you could pass in an empty list for main to fill, or use a global variable (or, better, a more restricted equivalent like an attribute on a class instance or a closure variable), or refactor your code so everyone who needs to access our_list is inside the same function… but I think this is the cleanest way to do what you're trying to do here.
By the way, this isn't quite the last hurdle—but you're very close:
After any mean, median, or mode, it's going to hit the "Goodbye" and exit instead of going back through the loop. Do you know about elif?
You mixed up '5' and '4' in the menu.
If the user enters 2 and 3 and asks for the mode, your code will dump a ValueError traceback to the screen; probably not what you want. Do you know try/except?
That's all I noticed, and they're all pretty simple things to add, so congrats in advance.
The issue is that our_list was defined in the main() function, and is not visible outside of the main() function scope.
Since you're doing everything in one chunk, you could remove line 1 and 6, taking the code from your main() function and putting it on the same indentation level as the code which follows.
This seems to be because you defined our_list within the main() function. You should probably define it as a global variable by creating it outside the main() function.
You could also put the while loop inside a function and pass in our_list as a parameter to the list.

Handling input data quality with checks & default value

I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))

Error Tapping a section of code

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

Function running differently in separate instances-python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I have written this program that takes a file called Sonnets and firstly, changes all the roman numerals in the sonnets to numbers, copies that to a new file, then asks the user for number input and shows them the sonnet corresponding to their number (if between 1 and 7).
For numbers outside 1 and 7, I would display appropriate error messages, giving specific directions on what they inputted and what they need to input again.
I wrote all of my functions separately, and everything runs when I put them together EXCEPT for the "except" part in function serve_poem(). It gave me the correct error message when I ran the function separately, however, now it just gives me the automatic error message instead of the specific message I encoded.
I posted my whole code below, because I figure that something in one of the other functions is messing with it(???) because it ran fine on its own.
def change_romans_to_numbers(s):
if s == "I.":
return("1.")
elif s == "II.":
return("2.")
elif s == "III.":
return("3.")
elif s == "IV.":
return("4.")
elif s == "V.":
return("5.")
elif s == "VI.":
return("6.")
elif s == "VII.":
return("7.")
else:
return s
def serve_poem():
sonnet=open(r"C:\Users\Emily\Documents\sonnets.txt", "r")
x=int(input("Please enter a number 1-7:"))
s=sonnet.readlines()
s=list(s)
try:
if x==1:
up=int(2+14*(x-1))
lower=int(2+14*(x-1)+14)
for i in range (up,lower):
print(s[i])
if 2<=x<=7:
up=int((2+14*(1-1))+(19*(x-1)))
lower=int((2+14*(1-1)+14)+(19*(x-1)))
for i in range (up,lower):
print(s[i])
if x<0:
print("You entered a negative number. Please enter a number between 1 and 7:")
serve_poem()
if x==0:
print("You entered 0. Please enter a number between 1 and 7:")
serve_poem()
if x>7:
print("You entered a number greater than 7. Please enter a number between 1 and 7:")
serve_poem()
except ValueError:
print("Error: Value Error. You did not enter a number at all! Please re-enter a number:")
serve_poem()
def writing_romans_to_numbers():
sonnet=open(r"C:\Users\Emily\Documents\sonnets.txt", "r")
sonnet_fixed=open(r"C:\Users\Emily\Documents\sonnets-fixed.txt", "w")
for line in sonnet:
new=change_romans_to_numbers(line.strip())
sonnet_fixed.write(new + '\n')
def main():
writing_romans_to_numbers()
serve_poem()
main()
Here is my error message (if user inputs q):
File "C:/Users/Emily/.spyder2-py3/temp.py", line 28, in serve_poem
x=int(input("Please enter a number 1-7:"))
ValueError: invalid literal for int() with base 10: 'q'
Your problem is that you aren't wrapping this line in the try...except block:
x=int(input("Please enter a number 1-7:"))
This line will raise an exception if given non-numeric input, but this exception will not handled by your try...except block. You would only need to put that one line in a try...except block, if that line passes it will be guaranteed to be numeric input, so your comparisons should work.
However, as Martjin said, that isn't the best approach.

Categories

Resources