Home > Software design >  My "IF " and Elif Statements are not Working
My "IF " and Elif Statements are not Working

Time:10-31

So if and elif statements are not working

def weight_converter():
  print("Welcome to Weight Converter")
  operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram"))
   if operation == " 1":
     gram_one = int(input("Grams needed to convert to pound: "))
     print("You have", gram_one * 453.57,"pounds")
   elif operation == " 2":
     pound_one = int(inpu())
  
weight_converter()

So I am expecting for the if statement to run but then the gram_one input does not show up. Please help me to fix that.

CodePudding user response:

your code snippet should be like one of the below code snippets:

def weight_converter():
  print("Welcome to Weight Converter")
  operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram"))
   if operation == 1:
     gram_one = int(input("Grams needed to convert to pound: "))
     print("You have", gram_one * 453.57,"pounds")
   elif operation == 2:
     pound_one = int(input())
  
weight_converter()

or

def weight_converter():
  print("Welcome to Weight Converter")
  operation = input(" 1. Gram to Pound \n 2. Pound into Gram")
   if operation == "1":
     gram_one = int(input("Grams needed to convert to pound: "))
     print("You have", gram_one * 453.57,"pounds")
   elif operation == "2":
     pound_one = int(inpu())
  
weight_converter()

in both above code snippets by entering just 1 or 2 by the keyboard if/elif statements works ok.

CodePudding user response:

I think you were on the right track, just a few things that needed to be tweaked:

  1. It appears that there was an indentation issue you had, indenting it correctly fixes it.
  2. There was a typo in the elif block so I just made a tweak to fix that.
  3. Because you are using integers for your input, changing it to 2 rather than " 2" fixes that.
  4. Added an else block just in case the input is anything but 1 or 2.

Hope this helps put you in the right direction you're expecting.

def weight_converter():
  print("Welcome to Weight Converter")
  operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram"))
  if operation == 1:
    gram_one = int(input("Grams needed to convert to pound: "))
    print("You have", gram_one * 453.57,"pounds")
  elif operation == 2:
    pound_one = int(input())
  else:
      print("An error as occurred..")

weight_converter()
  • Related