编写一个 Python 程序,使用 While 循环和 For 循环打印自然数,并附带示例。
Python 使用 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 使用 While 循环打印自然数程序
在此 Python 自然数显示程序中,我们只需将 For 循环替换为 For 循环为 While 循环
# 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 程序与第一个示例相同。但这次,我们允许用户输入最小值和最大值。这意味着此程序打印从最小值到最大值的自然数。
# 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 = ' ')
