12

Pythonをコードの先頭に戻す方法を見つけようとしています。SmallBasic では、

start:
    textwindow.writeline("Poo")
    goto start

しかし、Pythonでそれを行う方法がわかりません:/何かアイデアはありますか?

ループしようとしているコードはこれです

#Alan's Toolkit for conversions

def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

if op == "1":
    f1 = input ("Please enter your fahrenheit temperature: ")
    f1 = int(f1)

    a1 = (f1 - 32) / 1.8
    a1 = str(a1)

    print (a1+" celsius") 

elif op == "2":
    m1 = input ("Please input your the amount of meters you wish to convert: ")
    m1 = int(m1)
    m2 = (m1 * 100)

    m2 = str(m2)
    print (m2+" m")


if op == "3":
    mb1 = input ("Please input the amount of megabytes you want to convert")
    mb1 = int(mb1)
    mb2 = (mb1 / 1024)
    mb3 = (mb2 / 1024)

    mb3 = str(mb3)

    print (mb3+" GB")

else:
    print ("Sorry, that was an invalid command!")

start()

基本的に、ユーザーが変換を終了したら、最初にループバックするようにします。def関数を使用してループするたびに、「op」が定義されていないと表示されるため、これでループの例を実践することはまだできません。

4

7 に答える 7

18

無限ループを使用します。

while True:
    print('Hello world!')

これは確かにあなたのstart()関数にも当てはまります。を使用してループを終了するかbreak、 を使用returnして関数を完全に終了することができます。これにより、ループも終了します。

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")

同様に終了するオプションを追加する場合、それは次のようになります。

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

例えば。

于 2013-09-13T17:22:39.410 に答える
9

Python は、ほとんどの最新のプログラミング言語と同様に、「goto」をサポートしていません。代わりに、制御関数を使用する必要があります。これを行うには、基本的に 2 つの方法があります。

1.ループ

SmallBasic の例が行うことを正確に実行する方法の例は次のとおりです。

while True :
    print "Poo"

それはとても簡単です。

2.再帰

def the_func() :
   print "Poo"
   the_func()

the_func()

再帰に関する注意: これは、最初に戻りたい特定の回数がある場合にのみ行ってください (その場合、再帰を停止するケースを追加してください)。上で定義したような無限再帰を行うのは悪い考えです。最終的にメモリ不足になるからです!

より具体的に質問に答えるように編集

#Alan's Toolkit for conversions

invalid_input = True
def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
    if op == "1":
        #stuff
        invalid_input = False # Set to False because input was valid


    elif op == "2":
        #stuff
        invalid_input = False # Set to False because input was valid
    elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
        #stuff
        invalid_input = False # Set to False because input was valid
    else:
        print ("Sorry, that was an invalid command!")

while invalid_input: # this will loop until invalid_input is set to be False
    start()
于 2013-09-13T17:24:25.447 に答える
2

Python には、ステートメントの代わりに制御フロー ステートメントがありgotoます。制御フローの 1 つの実装は、Python のwhileループです。ブール条件 (Python ではブール値は True または False のいずれか) を与えることができ、ループはその条件が false になるまで繰り返し実行されます。永遠にループしたい場合は、無限ループを開始するだけです。

次のサンプル コードを実行する場合は注意してください。プロセスを強制終了したい場合は、実行中にシェルで Control+C を押します。これが機能するには、プロセスがフォアグラウンドにある必要があることに注意してください。

while True:
    # do stuff here
    pass

# do stuff hereは単なるコメントです。何も実行しません。pass基本的に「こんにちは、私はコード行ですが、何もしないのでスキップしてください」と言うpythonの単なるプレースホルダーです。

ここで、ユーザーに永遠に繰り返し入力を求め、ユーザーが文字 'q' を入力して終了する場合にのみプログラムを終了するとします。

次のようなことができます。

while True:
    cmd = raw_input('Do you want to quit? Enter \'q\'!')
    if cmd == 'q':
        break

cmdユーザーが入力したものを保存するだけです(ユーザーは何かを入力してEnterキーを押すように求められます)。cmd文字 'q' だけを格納すると、コードは強制的に囲んbreakでいるループから抜け出します。このbreakステートメントを使用すると、あらゆる種類のループをエスケープできます。無限でも!無限ループで頻繁に実行されるユーザー アプリケーションをプログラムする場合、学習することは非常に役立ちます。ユーザーが文字 'q' を正確に入力しないと、プロセスが強制終了されるか、ユーザーがこの厄介なプログラムに飽き飽きして終了したいと判断するまで、無限に繰り返しプロンプトが表示されます。

于 2013-09-13T17:23:03.883 に答える
2

ループで簡単にできます。ループには2つのタイプがあります

ループの場合:

for i in range(0,5):
    print 'Hello World'

Whileループ:

count = 1
while count <= 5:
    print 'Hello World'
    count += 1

これらの各ループは、「Hello World」を5 回出力します。

于 2013-09-13T17:27:06.783 に答える
0

for または while ループを作成し、すべてのコードをその中に入れますか? Goto 型プログラミングは過去のものです。

https://wiki.python.org/moin/ForLoop

于 2013-09-13T17:22:45.227 に答える
0

while ループを使用する必要があります。while ループを作成し、ループの後に命令がない場合、無限ループになり、手動で停止するまで停止しません。

于 2013-09-13T17:24:53.093 に答える
-1
def start():

Offset = 5

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Please be sensible try just the lower case')

def getMessage():
    print('Enter your message wanted to :')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (Offset))
        key = int(input())
        if (key >= 1 and key <= Offset):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return
于 2015-01-12T13:54:40.543 に答える