I know this question is similar to one I have already asked, but it is an extension and so justified its own space :-)
I am a Python newbie writing a code which takes input from a user and then stores that user input in an array (to do more stuff with later), provided two criteria are met:
1) The total inputs add up to one
2) There is no input itself greater than one.
I have already had some help with this question, but had to modify it a bit since my code inputs can't easily be written with the inputs being classified by some index "n" (the questions prompting input can't really be formatted as "input (n), where n runs from 1 to A")
Here is my attempt so far:
num_array = list()
input_number = 1
while True:
a1 = raw_input('Enter concentration of hydrogen (in decimal form): ')
a2 = raw_input('Enter concentration of chlorine (in decimal form): ')
a3 = raw_input('Enter concentration of calcium (in decimal form): ')
li = [a1, a2, a3]
for s in li:
num_array.append(float(s))
total = sum([float(s)])
if float(s-1) > 1.0:
num_array.remove(float(s-1))
print('The input is larger than one.')
continue
if total > 1.0: # Total larger than one, remove last input and print reason
num_array.remove(float(s-1))
print('The sum of the percentages is larger than one.')
continue
if total == 1.0: # if the sum equals one: exit the loop
break
input_number += 1
I am rather glad it compiles, but Python doesn't like the line
if float(s-1) > 1.0:
for which it throws the error:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I know this is because the "s" is a string, not an integer, but I can't think of an easy way around the problem, or for how to implement a loop over user inputs in this case in general.
How to improve this program to only write user input to the array if the criteria are met?
Thanks for your time and help!
float(s)-1
– asongtoruinSyntaxError
which is kinda close - it happens before the actual interpretation step. The python docs liken the generation of bytecode to compilation. – MisterMiyagi"can't easily be written with the inputs being classified by some index "n""
? It's perfectly fine to do anfor element in ('hydrogen', 'chlorine', 'calcium'):
and would prevent problems such ass
being checked only for the last element. – MisterMiyagicontinue
statements should be indented one more level, to fall within the priorif
statements. – Jeff