Как мне создать цикл в python, который продвигается при нажатии клавиши с помощью команды exit?

#python #loops

#python #циклы

Вопрос:

Итак, я работаю над базовым калькулятором. Он должен продолжать выполнять новые вычисления, когда я нажимаю клавишу для ее продвижения, но когда я ввожу close в operator . Код должен объяснить это лучше.

 a=2
if a==2:

    l = int(input("Enter the left side of the equation: "))
    r = int(input("Enter the right side of the equation: "))
    o = input("Enter the operator: ")
    if o=="close":
        break
    
    from time import sleep

    import operator
    ops = { " ": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "abs": operator.abs, "%": operator.mod } # etc.

    print (ops[o](l,r))

    import os
    os.system("pause")


print("Closing in 3")
sleep(1)
print("Closing in 2")
sleep(1)
print("Closing in 1")
sleep(1)
 

Так что да. Это то, что я пробовал, но он просто немедленно завершается, когда я запускаю его сейчас.

a=2 Сделка была для меня просто простым способом создания цикла.

Комментарии:

1. с if a == 2 вы не создаете цикл. Вы можете напрямую заменить это на «while true:»

Ответ №1:

Вам нужно изменить if a==2 на while a==2 :

 a=2
while a==2:

    l = int(input("Enter the left side of the equation: "))
    r = int(input("Enter the right side of the equation: "))
    o = input("Enter the operator: ")
    if o=="close":
        break
    
    from time import sleep

    import operator
    ops = { " ": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "abs": operator.abs, "%": operator.mod } # etc.

    print (ops[o](l,r))

    import os
    os.system("pause")


print("Closing in 3")
sleep(1)
print("Closing in 2")
sleep(1)
print("Closing in 1")
sleep(1)