我是Python新手,这是我尝试的第一语言。我开始了解它的一点点,只需要一些帮助。我正在使用下面的代码制作一个简单的计算器,我想知道如何从头开始重新启动我的代码(你可以在底部看到我的尝试)。
import math
import time
def game():
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("What would you like to do?")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
a = int(input("Please choose 1, 2, 3, or 4."))
def choice():
if a == 1:
print("You are now adding.")
elif a == 2:
print("You are now subtracting.")
elif a == 3:
print("You are now multiplying.")
elif a == 4:
print("You are now dividing.")
choice()
first_num = int(input("What is the first number you want to use?"))
time.sleep(2)
second_num = int(input("What is the second number you want to use?"))
time.sleep(2)
def execute():
if a == 1:
print(first_num, "+", second_num, "=", add(first_num,second_num))
elif a == 2:
print(first_num, "-", second_num, "=", subtract(first_num,second_num))
elif a == 3:
print(first_num, "x", second_num, "=", multiply(first_num,second_num))
elif a == 4:
print(first_num, "/", second_num, "=", divide(first_num,second_num))
execute()
game()
def playagain():
input("Would you like to calculate another problem? Yes or No")
playagain()
while playagain == "Yes":
game()
答案 0 :(得分:1)
您可以使用简单的loop
来执行此操作,例如:
play_again = True
while play_again:
# your code goes here
inp = input("Would you like to calculate another problem? Yes or No")
play_again = inp.lower() == 'yes'
如果输入不是
,这会将play_again
更改为False
答案 1 :(得分:0)
您非常接近可行的解决方案:
return
您需要playagain()
从输入中键入的值,然后import xmltodict
def start_requests(self):
yield Request("https://www.gotdatjuice.com/sitemap.xml", callback=self.parse_sitemap)
def parse_sitemap(self,response):
obj = xmltodict.parse(response.body)
monString = json.dumps(obj)
json_data = json.loads(monString)
urls = json_data['urlset']['url']
for url in urls :
loc = url['loc']
会询问它们并将该值插入其中,然后将其与“是”进行比较。
您当前的方法没有什么特别的错误。
答案 2 :(得分:0)
你最终真的接近逻辑。不需要while语句,只需要if语句。
playagain = input("Would you like to calculate another problem? Yes or No")
if playagain == "Yes":
game()
如果您想在问题解决后继续询问,那么您可以在游戏功能内部而不是在外部执行if else,因此在询问问题后它将继续询问playagain变量。
playagain = raw_input("Would you like to calculate another problem? Yes or No")
if playagain == "Yes":
game()
else:
return