Thursday, August 25, 2016

Coding Warm Up 1

Previous | Home | Next

Before we start talking about while-loop, little

Coding Warm Up

Write a code to that ask user for a number and returns information weather the number was even or odd (hint: use modulo operator %). Don't check the below code unless you are completely stuck!

Let's say that we name the program even-odd.py and  when program runs it could show this:

pi@tron ~ $ python3 even-odd.py 
Please enter a number: 5
The number, 5 is ODD.
Nice talking to you. Bye!
pi@tron ~ $ python3 even-odd.py 
Please enter a number: 4
The number, 4 is EVEN.
Nice talking to you. Bye!
pi@tron ~ $


If you are stuck here's an example of code that does it:

number = int(input("Please enter a number: "))
if number % 2 == 0:
    print("The number,", number, "is EVEN.")
else:
    print("The number,", number, "is ODD.")

print("Nice talking to you. Bye!")

First, using function input() we ask user for a number. Remember that function input() will take a string (characters), not actual number. That is why we wrap this input with int(), which converts string into actual number that can be used for calculation. Try to do this without int and see what happens!

Then we check (true/false), if the number is evenly divided by 2 (no remainder). Then, remainder is equal to 0, which triggers first block of code (after semicolon):


print("The number,", number, "is EVEN.")

If there is reamineder, the value of the remainder is NOT zero! the block after else: is executed!

print("The number,", number, "is ODD.")

You can see the in my output above what it looks like!

That concludes the if statement. Program proceeds to the next line which gives us a final 'bye!'.
 
 Previous | Home | Next