簡體   English   中英

如果不滿足兩個條件,則拒絕或循環遍歷用戶輸入

[英]Reject or loop over user input if two conditions not met

我是Python的真正初學者,盡管到目前為止我都很喜歡Python。

我正在制作一個小程序,需要用戶輸入,然后使用它進行處理。 我的問題是用戶輸入的數字必須

(1)全部加起來不超過一個(即a1 + a2 + a3 \\ leq 1)

(2)分別為<1。

到目前為止,這是我的代碼(僅是關鍵的中間部分):

 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))

我很樂意構建一些東西,以使其要求用戶在輸入超過要求的情況下重新輸入東西。

a1 + a2 + a3> 1

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

我覺得這真的很容易實現,但是由於我的知識有限,我被卡住了!

任何幫助將非常感激 :-)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM