[英]how to loop from the start when i want to keep using my calculator. and after i use it i want it to close if i type 9
When I want to quit my calculator it works, but when I want to keep using it there comes a problem:当我想退出我的计算器时它可以工作,但是当我想继续使用它时出现了问题:
File "main.py", line 54, in <module>
main()
NameError: name 'main' is not defined
I want to keep looping it from the start if I type y
or Y
so that I could keep using it.如果我输入y
或Y
,我想从头开始循环它,以便我可以继续使用它。
And if I type 9 after I use it, I can't come to the closing screen.而如果我用完后输入9,我就无法来到关闭画面。 So I want it to show the close screen and stop looping.所以我希望它显示关闭屏幕并停止循环。
here's my code:这是我的代码:
print("calculator")
print("1.Pluss")
print("2.Minus")
print("3.Ganging")
print("4.Deling")
print("9.Avslutt")
chr=int(input("1-4 eller Avslutt: "))
while True:
if chr==1:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=b+a
print("sum = ", c)
elif chr==2:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a-b
print("sum = ", c)
elif chr==3:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a*b
print("sum = ", c)
elif chr==4:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a/b
print("sum = ", c)
elif chr==5:
print("1-4 idiot")
elif chr==6:
print("1-4 idiot")
elif chr==7:
print("1-4 idiot")
elif chr==8:
print("1-4 idiot")
else:
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
It works if I want to quit, but it can't keep looping from the start after it comes to.如果我想退出它可以工作,但是它不能从头开始循环。
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
If you are offering an option to terminate (9. Avslutt) you don't need to ask user for confirmation of iteration.如果您提供终止选项 (9. Avslutt),则无需要求用户确认迭代。 Just repeat the input prompts.只需重复输入提示即可。
There's no need to convert the user input to int as the values are not used in any arithmetic context - ie, they're just strings.无需将用户输入转换为 int,因为这些值未在任何算术上下文中使用——即,它们只是字符串。
You may find this pattern useful:您可能会发现此模式很有用:
from operator import add, sub, mul, truediv
OMAP = {'1': add, '2': sub, '3': mul, '4': truediv}
while True:
print("calculator")
print("1. Pluss")
print("2. Minus")
print("3. Ganging")
print("4. Deling")
print("9. Avslutt")
if (option := input('1-4 eller avslutt: ')) == '9':
break
if (op := OMAP.get(option)) is None:
print('Ugyldig alternativ')
else:
x = float(input('Number 1: '))
y = float(input('Number 2: '))
print(f'Resultat = {op(x, y):.2f}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.