尝试在用户inpu上创建一个停止的循环

2024-04-24 06:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使一个计算器,要么重新启动脚本或停止它使用“继续”和“中断”。但是当我试着运行它时,它说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")

Tags: toanswerinputreturnifdefspeechmark
1条回答
网友
1楼 · 发布于 2024-04-24 06:31:05

下面是我的作品,@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")

相关问题 更多 >