Course: Python

Progress (0%)

# Exercise: Any Number

Exercise 8 Very easy

Prerequisites for the exercise

2. Python Number Basics
3. All previous chapters

## Objective

Extend the Addition Calculator exercise to add any two numbers; not just two integers.

## Description

Back in the exercise Addition Calculator, we created a program that took as input two integers and then printed out their sum.

Recall that the entered values were converted into integers using `int()`. This meant that floating-point numbers couldn't be entered — they would've otherwise lead to an error.

Now, in this exercise, your task is to rewrite that simple program such that it accepts any two numbers; not just integers.

Furthermore, after performing the addition, if the result is an integer (whose fractional part is zero), output the result as an integer.

Shown below are two examples:

x: 5 y: 2.5 The sum is: 7.5

Here, since the sum `7.5` is not an integer, it is output as it is.

x: 1.5 y: 2.5 The sum is: 4

However, here the sum `4.0` is indeed an integer, and is likewise output as an integer — `4`.

## New file

Inside the directory you created for this course on Python, create a new folder called Exercise-8-Any-Number and put the .py solution files for this exercise within it.

## Solution

The description clearly says that we can't use `int()` to convert the input strings into a number, since it throws an error when given a string containing a floating-point number.

This can be seen as follows:

``int('1.5')``
Traceback (most recent call last): File "stdin", line 1, in <module> int('1.5') ValueError: invalid literal for int() with base 10: '1.5'

So with `int()` gone, do we have any other options to convert the input strings into numbers?

`float()`? Well, yes, it's the only option we've got right now. And guess what, it's just what's required.

`float()` can convert a stringified integer as well as a stringified float into an actual floating-point number. And then we could perform arithmetic on this float easily.

Therefore, to start with, we replace the calls to `int()` with `float()` in the program we created in the Addition Calculator exercise:

``````x = input('x: ')
y = input('y: ')

x = float(x)
y = float(y)

print('The sum is:', x + y)``````

But the story doesn't end here! The exercise requires one additional thing.

If the result of the addition is an integer, it should be output as an integer. For instance, if the result is `5.0`, then it should be output as `5`.

How to determine whether a float is an integer or not? Recall anything?

We'll need the `is_integer()` method of floats.

The idea is to call `is_integer()` on the expression `x + y`. If the method returns `True`, we convert `x + y` into an integer and then print it. However, if this is not the case, then we continue on with our normal float output.

``````x = input('x: ')
y = input('y: ')

x = float(x)
y = float(y)

if (x + y).is_integer():
print('The sum is:', int(x + y))
else:
print('The sum is:', x + y)``````
In line 7, the expression `x + y` in enclosed in parentheses to call the `is_integer()` method on the result of `x + y`. Without the parentheses, we'd have the expression `x + y.is_integer()`, which is adding `x` and `y.is_integer()`. Doesn't seem right, does it?

This solves our exercise.

## Improving the code

Despite the fact that the code above gives the correct output, there are a couple of problems in it.

The expression `x + y` is written thrice. Secondly, the `print()` statement, with exactly the same format, is written twice. This goes against the DRY principle, which we talked about earlier in the Rudimentary Arithmetic Exercise.

DRY (Don't Repeat Yourself) states not to repeat code unnecessarily — which is undoubtedly happening in the code above.

How can we prevent this repetition?

For `x + y`, we could just compute it once and then save it in a variable. That's it.

We'll call this variable `result`. First, let's get done with this thing in our code:

``````x = input('x: ')
y = input('y: ')

x = float(x)
y = float(y)

result = x + y

if result.is_integer():
print('The sum is:', int(result))
else:
print('The sum is:', result)``````

Next, let's analyse the `print()` statements.

How could we improve on them? What do you think is changing in the `print()` statements?

The difference between both `print()` calls above is that the first one has `int(result)` as the second arg, while the second one has `result` as the second arg. The rest is the same.

Whether the condition for `if` is true or false, a `print()` is regardless called, and something is, likewise, output. So, why not take the `print()` statement out of `if` and `else`.

What we could do is to write one `print()` statement after the whole block of `if..else` conditionals, and use those conditionals to determine the second arg to `print()`, instead:

``````x = input('x: ')
y = input('y: ')

x = float(x)
y = float(y)

result = x + y

if result.is_integer():
result = int(result)
else:
result = result

print('The sum is:', result)``````

In words, the conditionals here say that 'if `result` is an integer, assign to it the integer value of `result`, or else just keep it as it is.'

Beyond these conditionals, `result` is in the desired format, and is directly output using `print()`.

Amazing! We've improved our code a lot.

But there's one thing still left. Let's see whether you could figure it out..

Notice the `else` block above. If `result` is not an integer, `result` is assigned back to `result`. In other words, `result` remains whatever it is. This piece of code is redundant. Even if we were to remove it, `result` would remain whatever it is — it won't just change on its own!

And this is just what we'll do — remove the redundant `else` block:

``````x = input('x: ')
y = input('y: ')

x = float(x)
y = float(y)

result = x + y

if result.is_integer():
result = int(result)

print('The sum is:', result)``````

Now our code is simpler and much more flexible than the one we created previously.

One thing to keep in mind is that these small improvements at this novice stage of learning Python won't do wonders in the speed of execution of the program.

However, they'll teach you how to write clean code and apply coding principles to it. This is an essential skill to have when you go on to write highly complex applications in Python, or any other programming language.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage