用例子寫一個 Python 程序,用 While 循環和 For 循環列印自然數。
這個用於自然數的 Python 程序允許用戶輸入任何整數值。接下來,該程序使用 For 循環列印從 1 到用戶指定值的自然數。
# Python Program to Print Natural Numbers from 1 to N
number = int(input("Please Enter any Number: "))
print("The List of Natural Numbers from 1 to {0} are".format(number))
for i in range(1, number + 1):
print (i, end = ' ')
Python 自然數輸出
Please Enter any Number: 10
The List of Natural Numbers from 1 to 10 are
1 2 3 4 5 6 7 8 9 10
在這個顯示自然數的 Python 程序中,我們只是將 For Loop 替換為 While Loop
# Python Program to Print Natural Numbers from 1 to N
number = int(input("Please Enter any Number: "))
i = 1
print("The List of Natural Numbers from 1 to {0} are".format(number))
while ( i <= number):
print (i, end = ' ')
i = i + 1
Python 自然數使用 while 循環輸出
Please Enter any Number: 25
The List of Natural Numbers from 1 to 25 are
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
這個用於自然數的 Python 程序與第一個示例相同。但是這次,我們允許用戶輸入最小值和最大值。這意味著這個程序列印從最小到最大的自然數。
# Python Program to Print Natural Numbers within a range
minimum = int(input("Please Enter the Minimum integer Value : "))
maximum = int(input("Please Enter the Maximum integer Value : "))
print("The List of Natural Numbers from {0} to {1} are".format(minimum, maximum))
for i in range(minimum, maximum + 1):
print (i, end = ' ')
原創文章,作者:GDNM9,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126697.html