Below is a function that I have wrote which works exactly the way I want. The user creates a list and then ultimately spits out a list that they created with no negative numbers. The problem I am having is removing my "Population not valid, please input a value higher then 0" after they execute my (-1 to quit). I want the user to be able to type -1 and then spit out the list with nothing else. So does anyone have any tips for my function below?
def getData():
import math
pop = []
while True:
user = raw_input("Please enter a population number (-1 to quit): ")
pop.append(user)
if user <= '0':
print "Population not valid, please input a value higher then 0"
if user == '-1':
break
new_pop = map(int, pop)
pop2 = filter(lambda x:x >=1, new_pop)
print "Your population list is: ", pop2
getData()
just reverse the order of the 2 ifs
def getData():
import math
pop = []
while True:
user = raw_input("Please enter a population number (-1 to quit): ")
pop.append(user)
if user == '-1':
break
if user <= '0':
print "Population not valid, please input a value higher then 0"
new_pop = map(int, pop)
pop2 = filter(lambda x:x >=1, new_pop)
print "Your population list is: ", pop2
getData()
You could invert the order of your two if
statements:
if user == '-1':
break
elif user <= '0':
print "Population not valid, please input a value higher then 0"
Your problem is this if statement:
if user <= '0':
change to this
if user <= '0' and user != '-1':
This way, -1 is the only other input below 0 that will be ignored.
Or as stated above, reverse the order of the if statements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.