I am writing a python program in which I want to allow the user to enter only 10 numbers from the terminal. If they try to enter more than 10 it should prompt that they can't enter more than 10 numbers. How can I achieve this in python?
My code looks like as follows:
def get_list():
'''takes data from the user to create a list'''
error =True
while error == True:
error =False
user_data = raw_input("Please enter integers separated by space:" )
listofdata =user_data.split()
for item in listofdata:
try:
item = int(item)
except:
print("Please enter only numbers separated by spaces")
error =True
break
return listofdata
After the line:
listofdata =user_data.split()
you can add a check, something like:
if len(listofdata) > 10:
print "You should enter 10 integers only, please try again!"
error = True
continue
Related
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
I have a problem in which users can input spaces or nothing and still pass through the program, how do I go about preventing this? I am still a beginner at python.
def orderFunction(): # The function which allows the customer to choose delivery or pickup
global deliveryPickup
deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
if deliveryPickup == "d":
global customerName
while True:
try:
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
else:
break
global customerAddress
while True:
try:
customerAddress = (input("Please input your name"))
if customerAddress == (""):
print("Please input a valid Address")
else:
break
global customerPhnum
while True:
try:
customerPhnum = int(input("Please input your phone number"))
except ValueError:
print("Please input a valid phone number")
else:
break
print("There will also be a $3 delivery surcharge")
elif deliveryPickup == "p":
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
orderFunction()
else:
print("Please ensure that you have chosen d for Delivery or p for Pickup")
orderFunction()
orderFunction()
Here is my attempt at doing this but I get all kinds of unindent and indent errors at the moment and I think my while loops are probably wrong.
Essentially if I input a space or hit enter into one of the customer inputs (customerName for instance) it gets stored. This needs to prevented and I have tried to fix it by using while loops which obviously haven't worked.
Hopefully someone has a solution to this problem
Many Thanks.
.strip() removes all tabs or spaces before and after a string.
Meaning all spaces == empty string. All tabs == empty string. So all you have to check if the length of that string != 0 or the string is not empty. Just use an infinite loop to keep on forcing the right input.
Also as a tip, you don't have to limit yourself into one function.
Here's a working code below.
def getNonBlankInput(message, error_message):
x = input(message)
while len(x.strip()) == 0:
x = input(error_message)
return x
def getValidIntegerInput(message, error_message):
msg = message
while(True):
try:
x = int(input(msg))
break
except ValueError:
msg = error_message
return x
def orderFunction(): # The function which allows the customer to choose delivery or pickup
global deliveryPickup
global customerName
global customerAddress
global customerPhnum
deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
if deliveryPickup == "d":
customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
customerAddress = getNonBlankInput("Please input your address: ", "Please input a valid address: ")
customerPhnum = getValidIntegerInput("Please input your phone number: ", "Please input a valid phone number: ")
print("There will also be a $3 delivery surcharge")
elif deliveryPickup == "p":
customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
else:
print("Please ensure that you have chosen d for Delivery or p for Pickup")
orderFunction()
orderFunction()
Try using a regular expression that checks if any character between "A-Z" has been inserted, if not, give an error
The while loops are a decent solution, you just need to add more checks to your if statements.
First, you don't need a try statement on the top two loops. Don't use a try statement unless you're expecting an error, which you need to handle with an except statement, like you do in the bottom while loop.
Then you just need to add more conditions to your top two loops, I don't know exactly what you want to prevent, but you could try checking the length of the input, also see this answer for an interesting method:
https://stackoverflow.com/a/2405300/8201979
Instead of using input right away you can make a function similar to this one that will only allow valid inputs.
You can use this valid_input function instead of input.
def valid_input(text):
not_valid = True
res = ''
while not_valid:
res = input(text)
if res.split(): # if text is empty or only spaces, this creates an empty list evaluated at False
not_valid = False
return res
here the check is pretty simple: every text made out of nothing or spaces won't be allowed and we will keep asking for the same input until a valid information is given.
I made this code simple just so you get a general idea. But you can change the validation test to your liking and maybe also output a warning saying why the input wasn't allowed so the person knows what to do. You can do more advanced validation with regex, and maybe you need a minimum text length etc...
You have indent error because you have a try statement without the corresponding except.
You need both to make it work (as you did in the Phone number section).
Here is a link to the try/except: docs
Also, you can check if a string is empty as detailed in this answer.
So for example you want to write:
try:
customerName = input("Please input your name")
if not customerName:
print("Please input a valid name")
else:
break
except ValueError:
print("Please input a valid name")
Although the above seems a bit redundant, so you might want to raise an exception if the customer name is empty, catch the exception in the except block, print the warning and return error (or something else).
try:
customerName = input("Please input your name")
if not customerName:
raise ValueError
except ValueError:
print("Please input a valid name")
else:
break
Try adding another while true for pick and delivery option so that it can prevent taking other inputs
you don't need any of those try/excepts (which are broken anyway).
Its difficult to figure out what you're trying to do, are you trying to raise an exception if an empty string is passed, or request another input from the user? You seem to be half implementing both at the moment.
If its the latter, something like this would work.
def func(fieldname):
while True:
val = input("Please input your {}".format(fieldname))
if val.strip() != "":
break
else:
print("Please input a valid {}".format(fieldname))
return val
delivery_pickup = input("Please input delivery or pickup: d for delivery p for pickup")
if delivery_pickup == "d":
customer_name = func("name")
address = func("address")
phone_number = func("phone number")
What you are looking for is the str.strip method that remove trailing whitespace in strings.
Also I think try is not particularly suited for your needs here.
customerName = input("Please input your name")
while not customerName.strip():
customerName = input("Please input a valid name")
for the phone number I would not convert to integer because if the phone number starts with zeros, they will not be stored.
I have been trying to add some validation for users entering a new word to a text file.
The input must consists of letters only and I have got this working using if statements with .isalpha(), however I wanted to try and see if I could get it working using try, except and so far I have not got it working.
The try statement is allowing all input in no matter if it contains digits or spaces. I cant seem to spot where i've gone wrong.
def AddNewWords():
List = []
Exit = False
while not Exit:
choice = input("Please enter a word to be added to the text file: ")
try:
choice.isalpha()
except:
print("Not a valid word")
continue
else:
List.append(choice)
Exit = True
Return List
AddNewWords()
isalpha() returns True/False, it doesn't raise any exception.
Try this instead:
choice = input("Please enter a word to be added to the text file: ")
if not choice.isalpha():
print("Not a valid word")
continue
List.append(choice)
Exit = True
FWIW, you can also rewrite your loop in a more compact way without using the exit variable, but rather while True + break:
while True:
choice = input("Please enter a word to be added to the text file: ")
if choice.isalpha():
List.append(choice)
break
print("Not a valid word")
There are many way to achieve your result without a try / except clause. However, raising a manual exception is a perfectly valid approach and can be applied with only a couple of changes to your code.
First, you need to ensure a False result for str.isalpha raises an error:
if not choice.isalpha():
raise ValueError
Second, you should define explicitly the exception you are catching:
except ValueError:
print("Not a valid word")
continue
Complete solution:
def AddNewWords():
L = []
Exit = False
while not Exit:
choice = input("Please enter a word to be added to the text file: ")
try:
if not choice.isalpha():
raise ValueError
except ValueError:
print("Not a valid word")
continue
else:
L.append(choice)
Exit = True
return L
AddNewWords()
you need to check if true/false not try the except since you wont get any exception. the code should be.
def AddNewWords():
List = []
Exit = False
while not Exit:
choice = input("Please enter a word to be added to the text file: ")
if not choice.isalpha():
print("Not a valid word")
continue
else:
List.append(choice)
Exit = True
return List
AddNewWords()
I have seen many answers to this question but am looking for something very specific. What I need to accomplish (in pseudo code) is this:
> FOR every ITEM in DICTIONARY, DO:
> PROMPT user for input
> IF input is integer
> SET unique-variable to user input
I'm very new to Python so the code may not be proper, but here is what I have:
def enter_quantity():
for q in menu:
quantities[q] = int(input("How many orders of " + str(q) + "?: "))
So this does everything but evaluate the user input. The problem I'm having is if the input is incorrect, I need to re-prompt them for the same item in the top-level for loop. So if it's asking "How many slices of pizza?" and the user inputs "ten", I want it to say "Sorry that's not a number" and return to the prompt again of "How many slices of pizza?".
Any/all ideas are appreciated. Thanks!
My final solution:
def enter_quantity():
for q in menu:
booltest = False
while booltest == False:
inp = input("How many orders of " + str(q) + "?: ")
try:
int(inp)
booltest = True
except ValueError:
print (inp + " is not a number. Please enter a nermic quantity.")
quantities[q] = int(inp)
You need a while loop with a try/except to verify the input:
def enter_quantity():
for q in menu:
while True:
inp = input("How many orders of {} ?: ".format(q))
try:
inp = int(inp) # try cast to int
break
except ValueError:
# if we get here user entered invalid input so print message and ask again
print("{} is not a number".format(inp))
continue
# out of while so inp is good, update dict
quantities[q] = inp
This bit of code is a little more useful if a menu is added otherwise it crashes at the first hurdle. I also added a dictionary to store the input values.
menu = 'pizza', 'pasta', 'vino'
quantities = {}
def enter_quantity():
for q in menu:
while True:
if q == 'pizza':
inp = input(f"How many slices of {q} ?: ")
elif q == 'pasta':
inp = input(f"How many plates of {q} ?: ")
elif q == 'vino':
inp = input(f"How many glasses of {q} ?: ")
try:
inp = int(inp) # try cast to int
break
except ValueError:
# exception is triggered if invalid input is entered. Print message and ask again
print("{} is not a number".format(inp))
continue
# while loop is OK, update the dictionary
quantities[q] = inp
print(quantities)
Then run the code from this command:
enter_quantity()