Check whether a number is positive or negative. Python Programming

neg

As the title suggests, the purpose of this program is to tell you whether the number you enter is a positive or a negative number. 

Lets get some input from the user. We need to convert it to an integer using int and assign the input to a variable we are going to call number. Don’t forget the double brackets.

number = int(input(“Enter a number: “))

Now the engine of the program; the if statements. The first to test whether the number entered is smaller than 0. If so then its a negative number..

if number < 0:

        print(“This number is negative.”)

Next we need to take care of numbers is bigger than 0, which of course is a positive

elif number > 0:

        print(“This number is positive.”)

Now we need to account for the fact that the user may enter a 0

elif number == 0:

        print(“You have entered Zero”)

 

Now test this. Input 0, -1 and 6 for instance. Just to test that its working.

It is a bit inconvenient having to keep restarting the program, so lets add a while loop..

 

Lets create a random variable and just call it var. Again lets assign it a random number, say 1

var = 1

In order to keep the while loop alive we must ensure its always equivalent to 1

while var = 1:

 

now we just stick our code underneath. Don’t forget to indent.

 

The full Program:

Don’t forget the indents after the while and if statements

var = 1

while var == 1:

        number = int(input(“Enter a number: “)) 

        if number < 0:

                print(“This number is negative.”)

       elif number > 0:

               print(“This number is positive.”)

       elif number == 0:

              print(“You have entered Zero”)

 

And there we go, another simple Python Program!

http://www.unleashthepython.com 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s