0

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:

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()

4 Answers4

1

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • For this type of comparison, I would prefer the approach used by @eshirvana, using the `in` operator than a double comparison. – RufusVS Nov 26 '21 at 19:30
  • @RufusVS I'd prefer a straight `else` instead of an `elif` (but also maybe using `if ms.lower() in ["inch" , "in"]:`) – Elliott Frisch Nov 26 '21 at 19:42
1

the issue is with logic in your if if ms=="inch" or "in":

you can write it better with in:

def intocm():
    ms=input("What is it? (inch-in or centimeter-cm): ")
    am=int(input("How many of it: "))
    intocm=2.54
    if ms in ["inch" , "in"]:
        cm=am*intocm
        inch=am
    elif ms in ["centimeter" , "cm"]:
        cm=am
        inch=cm/intocm
    print(f'inch: {inch}, centimeter: {cm}')
intocm()
eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

if ms=="inch" or "in" is wrong. It should be if ms=="inch" or ms=="in". Otherwise it'll be treated as if ((ms=="inch") or ("in"))

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

The code is failing because of the first if condition. It should be similar to your elif condition.

In your code it is
if ms=="inch" or "in":

but it should be if ms=="inch" or ms=="in":