簡體   English   中英

程序在用戶指​​定的范圍內打印5的倍數

[英]Programme to print mulitples of 5 in a range specified by user

我是python的新手,正在嘗試編寫確定用戶指定范圍內5的所有倍數的代碼。 我讓代碼以5為單位上升。例如,如果范圍是6和21,則將說倍數是6,11,16,21。

a = int(input("Enter a value of a : "))
b = int(input("Enter a vlue of b : "))

if a%5 ==0:
    a = a+5

multiples = []

for value in range(a, b+1,5):
    multiples.append(value)

print(multiples)

我希望只打印5的倍數。

您可以在if語句中添加以下內容:

else:            # if it isn't a multiple of 5
    a += (5-a%5) # add enough to get to the next multiple of 5

我認為您需要找到input1的提醒,然后開始使用該提醒循環

    a = int(input("Enter a value of a : "))

    b = int(input("Enter a vlue of b : "))

    c=a%5 #reminder

    multiples = []

    for value in range(a+5-c, b+1,5):
       multiples.append(value)

    print(multiples)

如果您期望的6到21范圍的輸出是[10, 15, 20] ,那么您可以像if a % 5 == 0一樣首先測試起始點是否是5的倍數,如果是,我們可以重復加5直到達到范圍的終點,同時將所有步驟附加到輸出列表中。

但是,如果a % 5 == 0給您false,那么我們需要找到要添加到該起始點的值,以便我們可以得到此范圍內5的第一個倍數,即

diff = 5 - a % 5

並將此值添加到起點a ,我們得到第一個值:

first = a + diff

然后我們可以重復加5,直到達到范圍的終點。

將以上所有內容放入代碼中:

# get user input for the range a to b
a = int(input("Enter a value of a : "))
b = int(input("Enter a value of b : "))

output_list = []

# determine first value
if a % 5 == 0: 
    first_val = a
else: 
    first_val = a + (5 - (a % 5))

# go through the range between the first value and the end, with step=5
for val in range(first_val, b + 1, 5):
    # append value to the list
    output_list.append(val)

print(output_list)

暫無
暫無

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

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