python不满足条件重新输入_如果Python中不满足条件,则拒绝用户输入

初学者正在编写Python代码,从用户处获取输入并存储在数组中,但要求输入之和为1且每个输入不大于1。当前代码存在错误,导致TypeError。寻求帮助改进程序,以便只有当输入满足条件时才接受并存储输入。
摘要由CSDN通过智能技术生成

我知道这个问题和我已经问过的问题很相似,但它是一个扩展,因此它有自己的空间

我是一个Python新手,编写一个代码,它从用户那里获取输入,然后将用户输入存储在数组中(以后再做更多的工作),前提是满足两个条件:

1)总输入加起来为1

2)没有输入本身大于1。在

我已经有了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”是一个字符串,而不是一个整数,但是我想不出一个简单的方法来解决这个问题,或者在这种情况下如何实现对用户输入的循环。在

如何改进此程序,使其仅在满足条件时将用户输入写入数组?在

谢谢你的时间和帮助!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值