在 python 中编写计算器,需要一些帮助
Coding a calculator in python, need some assistance
请帮助我理解我做错了什么:尝试编写计算器代码。
我试过使用调试器。无济于事。
我总是收到缩进错误,我不确定自己做错了什么。也许是我的循环?
试过四处移动,仍然没有给我任何输出。有人可以看看我的循环并给我建议吗?
请帮助指导一个正在努力学习的年轻编码员!
while False:
options = [1, 2, 3, 4]
choice = input('Enter choice(1/2/3/4):')
try:
choice = int(choice)
if choice not in options:
print("Invalid input.")
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
except:
print("Please use one of the following(1/2/3/4): ")
continue
break
choice = int(choice)
if choice == 1:
print_result(multiply(num1, num2))
elif choice == 2:
print_result(divide(num1, num2))
elif choice == 3:
print_result(subtract(num1, num2))
elif choice == 4:
print_result(add(num2, num1))
else:
print("Invalid input")
while True:
try:
retry = str(input("Do you wish to do another calculation(y/n): "))
except:
if retry == 'y':
break
elif retry == 'n':
break
else:
print("Invalid Input - Use y or n")
continue
if retry == 'n':
print("Thanks for using our amazing calculator!!!")
break
print("Restarting...")
time.sleep(2)
我在你的代码中看到的唯一问题是第一行说 while Fasle:
它应该是 while True:
要执行的循环条件必须始终为真。
我看到你的代码中有错误,请按照以下说明改正:
缩进必须统一,即四个空格或一个制表符,使用其中之一
while False:
永远不会执行,改成while true
确保定义所有函数,如 multiply
等
尝试内置 eval()
函数,但不要用于任何生产,因为它会执行发送给它的任何 python 代码
print( eval( input("Input equation here:") ) )
- 将整个计算器代码写在一个函数中,并使用 return 语句立即退出每个循环以结束程序,如下所示:
def myfunc():
...some code...
if retry == 'n':
return 0
else:
...more code...
一定要查看 this free e-book
希望对您有所帮助!!
请帮助我理解我做错了什么:尝试编写计算器代码。
我试过使用调试器。无济于事。
我总是收到缩进错误,我不确定自己做错了什么。也许是我的循环?
试过四处移动,仍然没有给我任何输出。有人可以看看我的循环并给我建议吗?
请帮助指导一个正在努力学习的年轻编码员!
while False:
options = [1, 2, 3, 4]
choice = input('Enter choice(1/2/3/4):')
try:
choice = int(choice)
if choice not in options:
print("Invalid input.")
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
except:
print("Please use one of the following(1/2/3/4): ")
continue
break
choice = int(choice)
if choice == 1:
print_result(multiply(num1, num2))
elif choice == 2:
print_result(divide(num1, num2))
elif choice == 3:
print_result(subtract(num1, num2))
elif choice == 4:
print_result(add(num2, num1))
else:
print("Invalid input")
while True:
try:
retry = str(input("Do you wish to do another calculation(y/n): "))
except:
if retry == 'y':
break
elif retry == 'n':
break
else:
print("Invalid Input - Use y or n")
continue
if retry == 'n':
print("Thanks for using our amazing calculator!!!")
break
print("Restarting...")
time.sleep(2)
我在你的代码中看到的唯一问题是第一行说 while Fasle:
它应该是 while True:
要执行的循环条件必须始终为真。
我看到你的代码中有错误,请按照以下说明改正:
缩进必须统一,即四个空格或一个制表符,使用其中之一
while False:
永远不会执行,改成while true
确保定义所有函数,如
multiply
等尝试内置
eval()
函数,但不要用于任何生产,因为它会执行发送给它的任何 python 代码
print( eval( input("Input equation here:") ) )
- 将整个计算器代码写在一个函数中,并使用 return 语句立即退出每个循环以结束程序,如下所示:
def myfunc():
...some code...
if retry == 'n':
return 0
else:
...more code...
一定要查看 this free e-book
希望对您有所帮助!!