If I'm printing (0,n) in a for loop, how do i make the program print the last number?
Question:
I’m coding a simple for loop to print out all the numbers of a user inputted n using this code:
if __name__ == '__main__':
n = int(input())
for i in range (1,n):
print(i, end=" ")
I expected a result like:
Input:
5
Output:
1 2 3 4 5
but instead, I am getting this output:
1 2 3 4
Answers:
Just add 1. The range
function, when used as range(start, stop)
, does not include stop
, and it stops when the next number is greater than or equal to stop
.
if __name__ == '__main__':
n = int(input())
for i in range(1,n + 1):
print(i, end=" ")
I’m coding a simple for loop to print out all the numbers of a user inputted n using this code:
if __name__ == '__main__':
n = int(input())
for i in range (1,n):
print(i, end=" ")
I expected a result like:
Input:
5
Output:
1 2 3 4 5
but instead, I am getting this output:
1 2 3 4
Just add 1. The range
function, when used as range(start, stop)
, does not include stop
, and it stops when the next number is greater than or equal to stop
.
if __name__ == '__main__':
n = int(input())
for i in range(1,n + 1):
print(i, end=" ")