kubao112
kubao112

Reputation: 5

I wonder if there's a way to skip a specific line so it just doesn't get executed

I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.

This is my code:

num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
    print("Invalid operator")
    start()
num2 = float(input("Enter a number: "))

if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)
elif op == "^":
    print(pow(num1, num2))
elif op == "root":
    print(math.sqrt(num1))

restart = input("Continue?: ")

if restart == "yes":
    start()
else:
    sys.exit(0)

I want this to get ignored:

num2 = float(input("Enter a number: "))

When this is the case:

elif op == "root":
    print(math.sqrt(num1))

Upvotes: 0

Views: 58

Answers (3)

Jiho Choi
Jiho Choi

Reputation: 1321

There can be many different ways. One suggestion would be as below.

num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")

# HERE
if op != "root" and op in operators:
    num2 = float(input("Enter a number: "))
elif op not in operators:
    print("Invalid operator")
    start()

if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)
elif op == "^":
    print(pow(num1, num2))
elif op == "root":
    print(math.sqrt(num1))

restart = input("Continue?: ")

if restart == "yes":
    start()
else:
    sys.exit(0)

or

# HERE
if op in operators:
    if op != "root":
        num2 = float(input("Enter a number: "))
else:
    print("Invalid operator")
    start()

Upvotes: 0

WangGang
WangGang

Reputation: 533

To do this, you could do:

if op != "root":
    num2 = float(input("Enter a number: "))

This would skip the num2 input if op == "root"

Upvotes: 1

John Gordon
John Gordon

Reputation: 33343

Put the second number input statement behind an if:

op = input("Enter a operator: ")
if op != "root":
    num2 = float(input("Enter a number: "))

Upvotes: 1

Related Questions