Reputation: 13
I'm new to Python. I'm trying to create a program that prints set of docs I usually print by hand every week, however I'm running into several problems:
Here is the code:
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")
Here is the output:
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:
I managed to input numbers from 0-5 and print the document desired, however entering 2 values like: 2,3 Do not work and throws an error. How can I print more than one at a time?
If I want to make copies of each doc. Let's say I choosed 2,3 should I do loop to repeat each action as many times as I want the number of copies?
Upvotes: 1
Views: 1452
Reputation: 55469
You should avoid the input
function in Python 2. It can be convenient, but it is a security risk. Instead you should use the raw_input
function. In Python 3, the function named input
is equivalent to Python 2's raw_input
and the functionality of the old Python 2 input
function has been dropped.
The code below shows how to handle multiple document numbers given in a comma-separated list. The code also handles a single document number. If the user supplies any non-integer values the program will crash with a ValueError
. However, blanks spaces are permitted in the input.
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)
Demo
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
The heart of this code is the str.split
method.
user_choice.split(',')
gets the string in user_choice
and splits it into a list of strings, splitting wherever it finds a comma, discarding the commas.
[int(u) for u in user_choice.split(',')]
gets each of those resulting strings and converts them to integers, storing the results in a list.
Upvotes: 1