2016-08-01 7 views
0

私は以前のコーディング経験のないPythonの初心者です。私はこの言語を学ぶために "絶対初心者のためのPythonプログラミング"をMike Dawsonが使用しています。割り当ての1つは - フォーチュンクッキーをシミュレートするためのプログラムで、実行するたびに5つのユニークな運勢のうちの1つをランダムに表示する必要があります。Python_Random関数を使用した変数の割り当て

私は以下のコードが、プログラムを正常に実行することができないが書かれている -

# Fortune Cookie 
# Demonstrates random message generation 

import random 


print("\t\tFortune Cookie") 
print("\t\tWelcome user!") 

# fortune messages 
m1 = "The earth is a school learn in it." 

m2 = "Be calm when confronting an emergency crisis." 

m3 = "You never hesitate to tackle the most difficult problems." 

m4 = "Hard words break no bones, fine words butter no parsnips." 

m5 = "Make all you can, save all you can, give all you can." 

message = random.randrange(m1, m5) 

print("Your today's fortune " , message) 

input("\n\nPress the enter key to exit") 
+0

なぜプログラムを実行できませんか?エラーが発生していますか、起動しないか、起動しますが何もしませんか? –

+0

おそらく 'randrange'の誤用。 user6576756はそれが魔法によって動作することを期待していました。 – wim

答えて

0

あなたのエラーがmessage = random.randrange(m1, m5)です。このメソッドは整数としてパラメータを取るだけです。代わりに、リストにあなたの文章を入れて試してみて、次のことをテストする必要があります。

import random 

print("\t\tFortune Cookie") 
print("\t\tWelcome user!") 

messages = [ 
    "The earth is a school learn in it.", 
    "Be calm when confronting an emergency crisis.", 
    "You never hesitate to tackle the most difficult problems.", 
    "Hard words break no bones, fine words butter no parsnips.", 
    "Make all you can, save all you can, give all you can." 
    ] 

print("Your today's fortune ", random.choice(messages)) 

input("\n\nPress the enter key to exit") 

random.choiceリストからランダムな要素になります。乱数を生成してインデックスで呼び出すこともできますが、それほど明確ではありません:

index = random.randint(0, len(messages) - 1) 
print("Your today's fortune ", messages[index]) 
+0

は、ルックスの行単位の書式設定ですか?私の意見では、初心者が正規版を学ぶ方が効果的です。 – baranskistad

+0

@bjskistadええ、見た目です。それは私がこれと一緒に行ったので、ラインが何百もの文字を伸ばしているときにはっきりと見えません。それは本当に理解することがずっと難しいですか? –

+1

ありがとうございました。 1つの簡単な質問 - 例えば1000個のアイテムを一覧表示してランダムに生成しなければならない場合、コード本体内の各アイテムを列挙するこのプロセスは煩雑なものにならないでしょうか?効果的なプロセスは何でしょうか?あなたのコードを見直し、あなたの回答を提供してくれてありがとう、ありがとう。 – Kyo

関連する問題