试图使循环停止于用户输入

时间:2019-11-10 16:33:00

标签: python if-statement while-loop

我正在尝试制作一个可以重新启动脚本或使用“ continue”和“ break”将其停止的计算器。但是当我尝试运行它时,它说Continue不在循环中,有人可以帮忙吗?

代码如下:

import os
import sys

def add (x, y):
    return x + y

def subtract (x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x ,y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")
if choice > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
    while True:
        print ("Invalid Input")
        answer = input('Run again? (y/n): ')
    if answer in ('y', 'n'):
            if answer == "y":
                continue
            if answer == "n":
                break

num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
    print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
    print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
    print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
    print(num1,"/",num2,"=", divide(num1,num2))
else:
    print("Invalid Input")

1 个答案:

答案 0 :(得分:0)

下面为我工作,@ busybear是正确的,缩进已关闭。

import os
import sys

def add(x, y):
    return x + y


def subtract(x, y):
    return x - y


def multiply(x, y):
    return x * y


def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")
if choice > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
    while True:
        print("Invalid Input")
        answer = input('Run again? (y/n): ')
        if answer in ('y', 'n'):
            if answer == "y":
                continue
            if answer == "n":
                break

num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
    print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
    print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
    print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
    print(num1,"/",num2,"=", divide(num1,num2))
else:
    print("Invalid Input")