python不满足条件重新输入_如果Python中不满足条件,则拒绝用户输入
我知道這個問題和我已經(jīng)問過的問題很相似,但它是一個擴展,因此它有自己的空間
我是一個Python新手,編寫一個代碼,它從用戶那里獲取輸入,然后將用戶輸入存儲在數(shù)組中(以后再做更多的工作),前提是滿足兩個條件:
1)總輸入加起來為1
2)沒有輸入本身大于1。在
我已經(jīng)有了some help with this question,但不得不修改一下,因為我的代碼輸入不能很容易地用按某個索引“n”分類的輸入編寫(提示輸入的問題不能真正格式化為“input(n),其中n從1到a”)
以下是我目前為止的嘗試: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
我很高興它可以編譯,但是Python不喜歡這行代碼
^{pr2}$
它會拋出錯誤:TypeError: unsupported operand type(s) for -: 'str' and 'int'
我知道這是因為“s”是一個字符串,而不是一個整數(shù),但是我想不出一個簡單的方法來解決這個問題,或者在這種情況下如何實現(xiàn)對用戶輸入的循環(huán)。在
如何改進此程序,使其僅在滿足條件時將用戶輸入寫入數(shù)組?在
謝謝你的時間和幫助!在
總結(jié)
以上是生活随笔為你收集整理的python不满足条件重新输入_如果Python中不满足条件,则拒绝用户输入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何调位置_如何知道手表是偷停还是真没动
- 下一篇: JAVA入门级教学之(char类型)