当前位置: 动力学知识库 > 问答 > 编程问答 >

loops - A simple looping command In Python

问题描述:

So, I recently got into programming in python and decided to make a simple code which ran some simple maths e.g calculating the missing angle in a triangle and other simple things like that. After I made the program and a few others, I thought that maybe other people I know could use this so I decided to try and make this as simple as possible. The code can be found below:

a = int(input("What's one of the angles?"))

b = int(input("What's the other angle in the triangle?"))

c = (a + b)

d = 180

f = int(180 - c)

print(f)

The code itself does work but, the only problem is that if you have more than 1 question, it becomes tedious and a rather cumbersome task to constantly load up Python and hit F5 so, my idea was to have it loop an infinite number of times until you decided to close down the program. Every time I tried searching for a way to do this, all of the while True: statements were for bigger and more complicated pieces of code and with this being maybe my fifth or tenth piece of code, I couldn't understand a few of the coding for it.

I'd appreciate any help or advice for this subject as it'd make my day if anyone's willing to help.

网友答案:

You could put the code in a function, something like:

def simple():
    a = int(input("What's one of the angles?"))
    b = int(input("What's the other angle in the triangle?"))
    c = (a + b)
    d = 180
    f = int(180 - c)
    print(f)

and then simply type:

simple()

each time to use it.

网友答案:
while True:
    a = int(input("What's one of the angles?" + '\n'))
    b = int(input("What's the other angle in the triangle?"+ '\n'))
    c = (a + b)
    f = int(180 - c)
    print(f)
    if input("Would you like to do another? 'y' or 'n'"+ '\n').lower() == 'y':
        pass
    else:
        break

You can just ask if they want to go again. y will restart the loop, n will end it. The .lower() is in case they type Y or N.

As @Two-BitAlchemist mentioned d=180 is unecessary.

网友答案:

while True is good enough for this script, why abandon it?

while True:

    a = int(input("What's one of the angles?"))
    b = int(input("What's the other angle in the triangle?"))
    c = (a + b)
    d = 180
    f = int(180 - c)
    print(f)
分享给朋友:
您可能感兴趣的文章:
随机阅读: