Handling input data quality with checks & default value - python

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")))

Related

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.

Beginner - Script recognizing "pi" and "e" and converting them into numbers

I am completely new to any coding at all.
As one of my first little tasks I tried to design a program comparing numbers. I wanted to add a function that distinguishes "pi" and "e" entries and converts them into respective floats. This function, however, doesnt work fine.
# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", (number))
elif pismeno == "e":
number= float(2.71)
print ("word e converted to number:", (number))
else:
number = float(pismeno)
print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*
I guess that it has something to do with the output being stored inside the function and not "leaking" outside to the general code. Please keep in mind that I have literally NO experience so stick to a child language rather than the usual professional speech.
If you are writing a function, you need a return statement. A simplified example of your code:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", number)
return number
else:
....
....
input1=input("insert a number:")
print(convert(input1))
I really suggest you to study basic concepts of programming. You may start here: https://www.learnpython.org/. More about functions: https://www.learnpython.org/en/Functions
The number you chose is: pi" instead of "The number you chose is: 3.14"
Your current final print just prints the input you originally gave it (input1)
You need to provide a way to return a value from the function and then set that to a variable where you call it
def convert(pismeno):
... Code ...
return number
# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )

error displaying when trying to error capture

I am having the problem where i need some code to be error captioned, so if the user does not enter a number it should tell them that they have done something wrong. Below is the code that i would like to error capture, and i am not sure how to do about doing this.
if cmd in ('L', 'LEFT'):
Left_position = (int(input("How many places would you like to move left")))
if args:
step = int(args[0])
else:
step = Left_position
y -= step
This line:
Left_position = (int(input("How many places would you like to move left")))
Will throw an error if the input is not a string that can be turned into an integer. To capture this, surround this with a try block:
try:
Left_position = (int(input("How many places would you like to move left")))
except ValueError:
print('Error is handled here')
if args:
....
You might want to rearrange your code slightly. As far as I can see, you only actually want to ask the user for input if args haven't been provided. If this is the case, the following should work:
if args:
step = int(args[0])
else:
while True:
try:
Left_position = (int(input("How many places would you like to move left")))
break
except ValueError:
print 'This is not an integer! Please try again'
step = Left_position
y -= step
First, if there are args we use the first element and carry on. If there aren't, we enter a (potentially infinite) loop where the user is asked to provide an input. If this is not wrappable as an integer, an error message is printed and then the user is asked again for an input value. This terminates once an integer is provided - the break line can only be reached if an error isn't thrown by the input.

Python 3.x - Input only returns first item

I have been having problems with a block of code in a little project and I can't seem to fix it.
In the below code, I define inputrace() so that a process is carried out where the player types in a number that is above 0 and below 13 (there are 12 choices, each dictated by a number); it also checks for blank lines and strings and has the program state that there is an error and ask for user input again if they are detected. If it passes the check, RaceInp is returned and set to RaceChoice which allows the code below it to assign a Race to the player based on their selection.
#race check
def inputrace():
print ("Input number")
RaceInp = input()
Check = RaceInp
try:
int(RaceInp)
except ValueError:
print("Numbers only!")
inputrace()
if not int(Check)>12 or int(Check)<1:
return RaceInp
print (RaceInp) #this is here so I can check the value returned
Race = "NA"
RaceChoice = inputrace()
print (RaceChoice)
#assign race
if RaceChoice == "1":
Race = "Human"
#continues down to twelve
Everything works when valid strings are put in (any number 1-12), but things break when I purposefully put in an invalid string. It seems like RaceInp only retains the first user input and does not change, even after the function is recalled from an error. That means if I were to put in "a," the program will tell me it is wrong and ask again. However, when I put in "1" in an attempt to correct it, it accepts it but still keeps RaceInp as "a."
Is there any fix to this? I have no clue what's going on.
I appreciate the help and sorry if I got anything wrong in the question!
It seems that the problem is that you put the inputrace in a recursion instead of a loop. Something like this would probably be better:
def input_race():
while True:
print("Input a number between 1 and 12.")
race_input = input()
try:
race_input = int(race_input)
if race_input >= 1 and race_input <= 12:
return race_input
except ValueError:
pass
print ("'{input}' is not a number.".format(input=race_input))
race = "NA"
race_choice = input_race()
if race_choice == 1:
race = "Human"
print(race)

While Loop Break usage

I am totally going insane over this function I wrote, the while loop wont work for the love of god
while (something something):
print("at anytime enter 0 for both origin and destination to exit the game")
o=input("Enter origin stool's index (Must be int) ")
d=input("Enter destination stool's index (Must be int) ")
if isinstance(o,int) and isinstance(d,int):#if input d,o are int
#do bla bla
elif o==0 and d==0:#to exit manually
print("Exiting Manually...")
break
elif not (isinstance(o,int) and isinstance(d,int)):
print ("Invalid entry, exiting...")
break
The code should exit when o AND d are 0, and it should also exit when o OR d is not an int
However it seems that it doesn't matter what I enter, (i tried 0,0 and 0,1) it returns invalid entry, exiting...
Whats wrong with the conditions?
In Python 3, the input function always returns a string. It doesn't eval the user input like it used to do in Python 2. As a result, o and d are both strings, not integers. You need to wrap your input calls with int(input('...')) in order to turn them into ints, so your conditionals have a chance of success.
In this case, if the user inputs values that aren't numbers, the int call should fail with a ValueError. The standard way to deal with this is to wrap any calls to user input with a try-except block, to deal with users who provide bad input. So the relevant part of your code might look something like this:
try:
o=int(input("Enter origin stool's index (Must be int) "))
d=int(input("Enter destination stool's index (Must be int) "))
except ValueError:
print("Invalid entry, exiting...")
break
As a side note, your logic in the conditionals is kind of weird/broken. Your first conditional checks whether a and d are both ints, and then does processing. Then your next conditional (the first elif block) tries to compare those to 0, which will always fail since if you get to that test, that means the first conditional failed, so they weren't both ints and therefore can never be equal to 0.
Your first "if" will pass when o and d are ints regardless of their values. Only if that condition fails will it continue through to the next "elif".
Try something more like:
if isinstance(o,int) and isinstance(d,int) and (o != 0 or d != 0):
#Conditions met, carry on
else:
break

Categories

Resources