如果不满足两个条件,则拒绝或循环遍历用户输入

编程入门 行业动态 更新时间:2024-10-12 05:44:46
本文介绍了如果不满足两个条件,则拒绝或循环遍历用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Python的真正初学者,尽管到目前为止我都很喜欢它的每一分钟.

I am a real beginner with Python, although I am loving every minute of it so far.

我正在制作一个小程序,接受用户输入,然后对其进行处理.我的问题是用户输入的数字必须

I am making a little program that takes user input and then does stuff with it. My issue is that the numbers the user inputs have to

(1)全部加起来不超过一个(即a1 + a2 + a3 \ leq 1)

(1) All add up to not more than one (i.e. a1+ a2+ a3 \leq 1)

(2)分别为< 1.

(2) Each individually be < 1.

到目前为止,这是我的代码(仅是关键的中间部分):

Here is my code thus far (just the essential middle bit):

num_array = list() a1 = raw_input('Enter percentage a (in decimal form): ') a2 = raw_input('Enter percentage b (in decimal form): ') ... an = raw_input('Enter percentage n (in decimal form): ') li = [a1, a2, ... , an] for s in li: num_array.append(float(s))

我很乐意构建一些东西,以使其要求用户在输入内容超出

And I would love to build in something to make it demand the user re-inputs things if their inputs either exceed the requirement that

a1 + a2 + a3> 1

a1+a2+a3 >1

或a1> 1,a2> 1,a3> 1等

or that a1>1, a2>1, a3>1 etc.

我觉得这真的很容易实现,但是由于我的知识有限,我被困住了!

I have a feeling this would be really easy to implement, but with my limited knowledge I am stuck!

任何帮助将不胜感激:-)

Any help would be much appreciated :-)

推荐答案

input_list = [] input_number = 1 while True: input_list.append(raw_input('Enter percentage {} (in decimal form):'.format(input_number)) if float(input_list[-1]) > 1: # Last input is larger than one, remove last input and print reason input_list.remove(input_list[-1]) print('The input is larger than one.') continue total = sum([float(s) for s in input_list]) if total > 1: # Total larger than one, remove last input and print reason input_list.remove(input_list[-1]) print('The sum of the percentages is larger than one.') continue if total == 1: # if the sum equals one: exit the loop break input_number += 1

更多推荐

如果不满足两个条件,则拒绝或循环遍历用户输入

本文发布于:2023-10-28 01:21:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535078.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   不满足   条件   两个   用户

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!