2015-04-03 5 views
0

Хорошо, я только начинаю изучать питон и не знаю, где еще задать этот вопрос. Я написал этот калькулятор, и он работает.Как бесконечно зацикливать эту программу на python?

a,b=input("Enter two numbers (sperated by a comma): ") 
operator=raw_input("Do you want to add, subtract, multiply, or divide? ") 
if operator=="divide": 
    print "Your answer is", a/b 
if operator=="multiply": 
    print "Your answer is", a * b 
if operator=="add": 
    print "Your answer is", a + b 
if operator=="subtract": 
    print "Your answer is", a - b  
repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 

Теперь, я хочу знать, как начать эту программу заново, если ввод да. Я искал ответ, но я не мог понять, как выполнить цикл для всего. Как и в цикле while, вы должны дать команду после условия, но что это за команда? ples halp.

+0

Можно ставить верно как условие –

ответ

0
Try this
You can use while True: with this the code written inside the for loop
will execute infinitely,
To stop execution you can use Ctrl + C
while True:
    a,b=input("Enter two numbers (sperated by a comma): ")
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ")
    if operator=="divide":
        print "Your answer is", a/b
    if operator=="multiply":
        print "Your answer is", a * b
    if operator=="add":
        print "Your answer is", a + b
    if operator=="subtract":
        print "Your answer is", a - b
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ")     if repeat == "no":         break
+3

Это просто продолжает цикл навсегда, даже если пользователь имеет ответил «нет», чтобы повторить –

+0

Попробуйте внести новые изменения, надеемся, что это сработает – abhijeetmote

2
while True: 
    a,b=input("Enter two numbers (sperated by a comma): ") 
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ") 
    if operator=="divide": 
     print "Your answer is", a/b 
    if operator=="multiply": 
     print "Your answer is", a * b 
    if operator=="add": 
     print "Your answer is", a + b 
    if operator=="subtract": 
     print "Your answer is", a - b  
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 
    if repeat == 'no': 
     break 

Хотя Правда продолжает зацикливания, она может быть разбита на перерыв (ключевое слово прорывается ближайшего цикла (для или во время)).

При обработке ввода от пользователя для определения условия предпочтительнее проверить, начинается ли вход пользователя с «y» (да) или начинается с «n» (нет), так как пользователь может ввести y вместо о да, и он может связываться с капитализацией, вот код, который реализует эти:

while True: 
    a,b=input("Enter two numbers (sperated by a comma): ") 
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ") 
    if operator=="divide": 
     print "Your answer is", a/b 
    if operator=="multiply": 
     print "Your answer is", a * b 
    if operator=="add": 
     print "Your answer is", a + b 
    if operator=="subtract": 
     print "Your answer is", a - b  
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 
    if repeat.lower.startswith('n'): 
     break 

«повторить» является строкой, то есть метод (похоже на функцию) называется «нижним», этот метод возвращает в нижнем регистре строки, тогда вы можете проверить, если это строчное представление (также строка) начинается с буквы «n», используя другой метод, называемый startswith.

3

Заверните его в while цикле:

repeat = "yes" 
while repeat.lower().strip() == 'yes': 
    a,b=input("Enter two numbers (sperated by a comma): ") 
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ") 
    if operator=="divide": 
     print "Your answer is", a/b 
    if operator=="multiply": 
     print "Your answer is", a * b 
    if operator=="add": 
     print "Your answer is", a + b 
    if operator=="subtract": 
     print "Your answer is", a - b  
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 

Это будет цикл до тех пор, как ответ «да» (без учета регистра). Первоначальный «повтор» должен гарантировать, что цикл выполняется не реже одного раза.

Кстати, вы можете превратить ваш if тест в Словаре:

import operator 
ops = {'divide': operator.div, 
     'multiply': operator.mul, 
     'add': operator.add, 
     'subtract': operator.sub} 
repeat = "yes" 
while repeat.lower().strip() == 'yes': 
    a,b=input("Enter two numbers (sperated by a comma): ") 
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ").lower().strip() 
    if operator not in ops: 
     print 'Invalid operator:', operator 
     continue 
    print "Your answer is", ops[operator](a,b) 
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 
+1

Ник: я бы использовал 'if repeat.lower(). strip() в 'yes': ...' - многие программы поддерживают с помощью только «y» вместо «yes» – Dunno

+0

Я думал из этого, но вопрос, заданный специально, спросил «(да или нет)», так что это то, что я задал как действительный ответ. – TheBlackCat

0

Попробуйте это:

while True:  
    a,b=input("Enter two numbers (sperated by a comma): ") 
    operator=raw_input("Do you want to add, subtract, multiply, or divide? ") 
    if operator=="divide": 
     print "Your answer is", a/b 
    if operator=="multiply": 
     print "Your answer is", a * b 
    if operator=="add": 
     print "Your answer is", a + b 
    if operator=="subtract": 
     print "Your answer is", a - b  
    repeat=raw_input("Do you want to perform another calculation(yes or no)? ") 
    if repeat == "no": 
     break 
Смежные вопросы