2016-09-24 10 views
1

私はPythonを初めて使いました。 私はしかし、私はいくつかの問題に実行しているよ、私は通常、毎週手で印刷するドキュメントのセットのプリントプログラムを作成しようとしている:ここでPython:ユーザー入力時に1つまたは複数のファイル(コピー)を出力

はコードです:ここでは

import os 

file_list = os.listdir("C:/Python27/Programs/PrintNgo/Files2print") 
print ("List of available documents to print" '\n') 

enum_list = ('\n'.join('{}: {}'.format(*k) for k in enumerate(file_list))) 
print(enum_list) 

user_choice = input('\n' "Documents # you want to print: ") 
copies = input("How many copies would you like from each: ") 
#not implemented 
current_choice = file_list[user_choice] 
current_file = os.startfile("C:/Python27/Programs/PrintNgo/Files2print/"+current_choice, "print") 

です出力:

List of available documents to print 

0: doc0.docx 
1: doc1.docx 
2: doc2.docx 
3: doc3.docx 
4: doc4.docx 
5: doc5.docx 

Documents # you want to print: 

私は0-5からの入力番号に管理し、所望の文書を印刷し、しかし、のような2つの値を入力:2,3は動作し、エラーをスローしないでください。一度に複数の印刷を行うにはどうすればよいですか?

各文書のコピーを作成する場合は、私がコピー数を望むように何度も何度も繰り返す必要がある場合は2,3を選んだとしましょう。

I wonder if my style is fine, however that kind of menu looks nice as well and I can try it eventually

+0

「KeyError:」ですか? –

+0

これは 'TypeError'でなければなりません。 –

答えて

1

あなたはそれが便利なことができPythonの2のinput機能を避ける必要がありますが、それはセキュリティ上のリスクです。代わりにraw_input関数を使用する必要があります。 Python 3では、inputという名前の関数はPython 2のraw_inputに相当し、古いPython 2 input関数の機能は削除されています。

以下のコードは、複数のドキュメント番号をコンマ区切りリストで指定する方法を示しています。コードは単一の文書番号も扱います。ユーザーが整数以外の値を指定すると、プログラムはValueErrorでクラッシュします。ただし、入力には空白スペースを使用できます。

from __future__ import print_function 

user_choice = raw_input("\nDocuments # you want to print: ") 
user_choice = [int(u) for u in user_choice.split(',')] 
copies = int(raw_input("How many copies would you like from each: ")) 

for i in range(copies): 
    print('Copy', i + 1) 
    for j in user_choice: 
     print('Printing document #', j) 

デモ

Documents # you want to print: 3, 2,7 
How many copies would you like from each: 2 
Copy 1 
Printing document # 3 
Printing document # 2 
Printing document # 7 
Copy 2 
Printing document # 3 
Printing document # 2 
Printing document # 7 

このコードの中心はstr.split方法です。

user_choice.split(',') 

user_choice内の文字列を取得し、それがコンマを破棄、コンマを見つけどこ分割、文字列のリストにそれを分割します。

[int(u) for u in user_choice.split(',')] 

は、結果の文字列をそれぞれ取得し、整数に変換して結果をリストに格納します。

+0

編集:Pythonバージョンの2番目のタグがデフォルトでどのように割り当てられたのか興味深いです。なぜなら、私は何も入れていないことを覚えているからです。とにかく私は3.5を使用しています。私が家に帰るときに試してみる。 –

+0

@ D.Dachkinov 'Python-2.7'タグはデフォルトでは割り当てられていません:コードに" C:/ Python27/Programs/PrintNgo/Files2print "があり、コードがPythonで動作しないため、あなたがただ一つの文書番号を入力したとしても。 [この回答](http://stackoverflow.com/a/17245543/4014959)には、Python 2とPython 3をWindowsで実行する方法についての情報があります。 –

+0

ああ、私はそれが今気づいた、それは私はそれが3.5で実行されたと思った面白いです、私は今、本当に愚かな感じ。 私に 'str.split'メソッドを説明してくれてありがとう。それは非常に思慮深く、今日何かを学んだ –

関連する問題