Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Range() for positive and negative numbers

Okay, so I'm trying to write a simple program that gives me both the positive and negative range of the number given by the user.

For example, if the user gives number 3 then the program should prints out -3 -2 -1 0 1 2 3

I've tried thinking but just can't think how to get the negative range outputs. But the code I got below only gives me the positive range outputs, so I was thinking may I need to do to make it gives me both the positive and negative outputs.

 s = int(input("Enter a number "))
 for i in range(s+1):
     print i+1
like image 556
avoid_frustration Avatar asked May 05 '14 12:05

avoid_frustration


People also ask

Does range work with negative numbers in Python?

Negative range() in PythonYou can use negative integers in range(). Most of the time, we use the negative step value to reverse a range. But apart from the step, we can use negative values in the other two arguments (start and stop) of a range() function.

Can range go from positive to negative?

No. Because the range formula subtracts the lowest number from the highest number, the range is always zero or a positive number.

What does range () do in Python?

Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

How do you find positive and negative numbers in Python?

Python Code:n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")


1 Answers

Range() can take two parameters: range(start, end), where start is inclusive, and end is exclusive. So the range you want for 3 is: range(-3, 4). To make it general:

s = int(input("Enter a number "))
for i in range(-s, s+1):
    print i
like image 141
Ikke Avatar answered Oct 08 '22 02:10

Ikke