Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my code giving wrong output, translating inches into centimetres and vice versa

My code is giving incorrect output while everything seems to be alright.

The purpose of the code is to translate inches into centimetres and vice versa.

For example, with inpput cm then 6, the output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

inch: 6, centimeter: 15.24

But it should be:

inch: 2.362, centimeter: 6


 
Code:
```py
def intocm():
    ms = input('What is it? (inch-in or centimeter-cm): ')
    am = int(input('How many of it: '))
    intocm = 2.54
    global inch
    global cm

    if ms == 'inch' or 'in':
        cm = am * intocm
        inch = am

    elif ms == 'centimeter' or ms == 'cm':
        cm = am
        inch = cm / intocm

    print(f'inch: {inch}, centimeter: {cm}')


intocm()

>Solution :

You missed an equality test in your if statement, and you should be using float (not int). Like,

def intocm():
    ms=input("What is it? (inch-in or centimeter-cm): ")
    am=float(input("How many of it: "))
    intocm=2.54
    global inch
    global cm
    if ms=="inch" or ms=="in":
        cm=am*intocm
        inch=am
    elif ms=="centimeter" or ms=="cm":
        cm=am
        inch=cm/intocm
    print(f'inch: {inch}, centimeter: {cm}')

Which I ran

What is it? (inch-in or centimeter-cm): cm
How many of it: 2.54
inch: 1.0, centimeter: 2.54

(twice)

What is it? (inch-in or centimeter-cm): in
How many of it: 1
inch: 1.0, centimeter: 2.54

Which seems correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading