Python - Ensuring a variable holds a positive number
I am unclear as to what you want to do -- either the variables can be negative, or they can't.
If you are decrementing a variable repeatedly and after doing so you want to check whether they are negative, do so with an
if
-- that's what it's for!if value < 0: # do stuff
If you think the variables should never be negative and you want to assert this fact in the code in the code, you do
assert value > 0
which may raise an
AssertionError
if the condition doesn't hold (assert
will not execute when Python is not run in debug mode).If you want the variable to be 0 if it has been decreased below 0, do
value = max(value, 0)
If you want the variable to be negated if it is negative, do
value = value if value > 0 else -value
or
value = abs(value)
Creating a loop to check a variable to make sure it is a positive integer
To expand a bit on what the others have given you:
n = -1
while n < 0:
try:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
except ValueError:
continue
Which will handle users who try to sneakily put in values like HELLO
instead of 5
If-Else Statement-Positive and Negative Integers
On the first 3 lines, you collect a number, but always into the same variable (num
). Since you don't look at the value of num
in between, the first two collected values are discarded.
You should look into using a loop, e.g. for n in range(3):
for n in range(3):
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
Python numpy.random.normal only positive values
The normal distribution, by definition, extends from -inf to +inf so what you are asking for doesn't make sense mathematically.
You can take a normal distribution and take the absolute value to "clip" to positive values, or just discard negative values, but you should understand that it will no longer be a normal distribution.
Related Topics
Unpivot Multiple Columns With Same Name in Pandas Dataframe
Drop Rows Containing Empty Cells from a Pandas Dataframe
Import Local Module in Jupyter Notebook
How to Decompile a Compiled .Pyc File into a .Py File
Change CSV Name to CSV Date Time Python
Numpy: How to Pick Rows from Two 2D Arrays Based on Conditions in 1D Arrays
How to Check for an Exact Word in a String in Python
Finding an Exact Substring in a String in Python
How to Display the Value of the Bar on Each Bar With Pyplot.Barh()
Python Key Error=0 - Can't Find Dict Error in Code
Plotting Categorical Data With Pandas and Matplotlib
Access Is Denied When Trying to Pip Install a Package on Windows
Pandas | Merge Rows With Same Id
Send a File Through Sockets in Python
Python Executable Not Finding Libpython Shared Library