I am starting to learn python, I tried to generate random values by passing in a negative and positive number. Let say -1
, 1
.
How should I do this 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. ")
Note that rand()+1 is used to avoid 0 ; rand() does not return a negative value.
All the negative and positive numbers along with 0 comprise integers. Thus, the numbers that are greater than 0 are positive, whole numbers lesser than 0 are referred to as negative. This is the concept used in Python is negative program.
Use random.uniform(a, b)
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
import random
def r(minimum, maximum):
return minimum + (maximum - minimum) * random.random()
print r(-1, 1)
EDIT: @San4ez's random.uniform(-1, 1)
is the correct way. No need to reinvent the wheel…
Anyway, random.uniform()
is coded as:
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With