My lab asks me “Prompt for the input of a number, accept either a positive or negative number.Use a dual alternative “decision” structure and print a message indicating whether the number entered is positive or negative.”
I did my code but for some reason its not working….
def getNumFromUser():
num=input (“Please enter a number: “)
if num >= 0:
print "The number you entered is positive"
elif num <= 0:
print "The number you entered is negative"
else:
getNumFromUser()
And it won’t run my code for some reason, when I take out elif statement it ask me to enter number and if I enter negative it will ask me to re-enter number to get positive …I just don’t know how to combine negative and positive number in code so it would “print out message indicating whether the number entered is positive or negative.” *I’m new to python programming so I’m lost here, I would appreciate if someone would explain to me*
The
inputfunction in python2.x will try and evaluate the string you pass it as code. This can be considered undesirable or dangerous, and it is usually recommended to useraw_inputinstead.That being said,
raw_inputwill give you back a string. You will want to convert it to an int to compare to other ints:Keep in mind that if the user does not enter a number, that example would crash. You can check that a string is a number by using:
val_str.isdigit(). This works for ints, not floats. Part of your check can be to first confirm it is an int, otherwise ask again. Also,isdigitwon’t properly detect a negative number, which means you might want to learn how to catch an exception that can get raised…As for your overall structure, I feel a simply
whileloop check would serve you better than a recursive call togetNumFromUsereach time they enter bad information:It may not be part of your assignment to expect the user to enter anything other than a valid
int, but this example shows how to try and convert to int, and handle the failure.