I am getting input from users via raw_input (using a for loop).
What code can I use to ensure that if a user presses only Enter it keeps the default values (i.e. raw_input returns an empty string '' when no value has been entered)?
So for the default values are in the form of variables:
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
If i understand you correctly you need to iterate over values inserted by user and replace with an empty string if the user type only Enter key.
def values_input():
return raw_input("Please enter value or 'quit' to finish: ")
values = []
for code in iter(values_input, "quit"):
if len(code) == 0:
values +=['']
else:
values += [code]
print values
You can use an if to check if the user pressed only enter. As jonrsharpe
said, only Enter would set your input equal to empty string, that is, ''.
if user_answer_1 == '':
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
If user is supposed to either press enter, or give numerous inputs, then you can use break to skip the rest of the questions if his first answer was Enter.
while True:
user_age_answer = input('\nAge?')
if user_age_answer == '':
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
# Skips the rest of the questions.
break
# Here go the rest of the questions.
user_cash_answer = input('Cash?')
# And then you do what you want with the answers.
age_years = user_age_answer
# This break is used to exit loop.
break
Related
Have written below program, but how to avoid the system checking the two argument when enter is pressed, we are using the enter key to exit the while loop.
while True: # need to exit the while loop thru one <Enter>
itemcode, quantity = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if itemcode == " " : #got two argument, one enter will crash the system, how to amend it
return
if itemcode not in orderdict.keys():
print("Invalid item code! Try again.")
continue
if itemcode in orderdict.keys():
orderdict [itemcode] = orderdict
#print("{:4s} {:<3d} {:<3d} X {:<3d} ".format(itemcode, [0], [1], [3]))
else :
input ()
break
Your problem is that the first line is hardcoded in such a way that the program expects two, and exactly two, values separated by a space. If you give it less than two (and simply hitting "enter" means giving it zero values), or more than two, this causes a traceback because the expected number of values isn't there.
If you don'T trust your users to enter the correct number of values, then I think you can avoid a crash either with a try/exception block, or a simple loop that repeats promtping the user for input until the number of entered values is exactly two:
while True:
entry_list = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if len(entry_list) == 2:
itemcode = entry_list[0]
quantity = entry_list[1]
break
You can start to ask the user to enter only the value of the item and check this value if it is an enter key, then break the loop. Otherwise, check the value of the item if it is within the keys if so, then ask the user for the corresponding quantity. I think you need to replace orderdict
with the corresponding quantity for the item entered by the user.
orderdict = {"car":50,"plane":60,"bus":100} # example
while True:
itemcode = input("Enter item code and quantity (Press <Enter> key to end): ")
if itemcode == "" :
break
elif itemcode not in orderdict:
print("Invalid item code! Try again.")
else:
orderdict [itemcode] = input("Enter the quantity: ")
Note: you do not need to write orderdict.keys(), you can use only the name of a dictionary to iterate through the keys of orderdict.
I'm attempting to get not more than 10 user inputs. The user can choose to stop giving input by inputing an empty string
container_size = []
for i in range(10):
while True:
container_size.append(float(input('What is the size of your container?: ')))
if input('What is the size of your container?: ') == '':
break
if i <= 1:
refund = 0.10
else:
refund = 0.25
print(refund)
I keep getting an error when trying to break if no input is given. What can I do? I am also getting more than 10 inputs.
You call for input() twice: once for add to container, and second time in the if. So for every iteration, you are asking for 2 inputs. Therefore you have a total of 20 inputs instead of ten. Put it in a variable, and ask if the variable is empty/add variable to container.
your break statement currently refer to the if statement and not the while, because it interacts with closest statement which is the if. You can overcome this by using flag and check it at the end of the while statement.
container_size = []
refund = []
i = 0
for i in range(10):
try:
container_size.append(float(input('What is the size of your container?: ')))
except ValueError:
break
for x in container_size:
if x <= 1:
refund.append(0.10)
else:
refund.append(0.25)
print(sum(refund))
I corrected the code already. Thank you.
been at this all day and made absolutely no progress, it's surely supposed to be pretty simple too but I'm new to Python. Google hasn't brought up much so this is my last resort!
It's supposed to be some basic code for manually putting numeric values into a list. If I add a 'print' line to the script I can see the values are being successfully entered as I go along, but I can't seem to add the right script for breaking out of the loop by leaving the input blank. Currently if I set anything to make it break, the script seems to freeze while it's running and I have to reset the console completely.
Also I'm wondering is there a way of ensuring the input is always an integer? It would be good to make things a bit cleaner and bring up an error message or something if the user enters anything non-numeric.
Here's the code.
values = []
while True:
a = raw_input('Enter numeric values. Leave blank to stop: ')
if a == (??????) :
break
values.append(float(a))
Thanks!
You can restrict to only numbers with
if a.isdigit():
So your function could look like
def accept_inputs():
values = []
while True:
a = raw_input('Enter numeric values. Leave blank to stop: ')
if a.isdigit():
values.append(float(a))
if not a:
return values
Testing
>>> accept_inputs()
Enter numeric values. Leave blank to stop: 5
Enter numeric values. Leave blank to stop: 42
Enter numeric values. Leave blank to stop: 73
Enter numeric values. Leave blank to stop: ab
Enter numeric values. Leave blank to stop: abc
Enter numeric values. Leave blank to stop:
[5, 42, 73]
My approach is similar to #CoryKramer, with small changes
>>> values = []
>>> while True:
val = raw_input('Enter Number : ')
if not val:
print values
elif val.isdigit():
values.append(int(val))
else:
print 'you have entered non - digit value'
Enter Number : 2
Enter Number : a
you have entered non - digit value
Enter Number : 3
Enter Number : 5
Enter Number : 6
Enter Number : 22
Enter Number : 546
Enter Number : 31s
you have entered non - digit value
Enter Number : 345678
Enter Number :
>>> values
[2, 3, 5, 6, 22, 546, 345678]
Strings have a built in function isdigit() that returns true if all the characters are numbers.
To break out if nothing is entered, use the len() function to detect if the string is empty.
More info here
You're code would look like this:
if a.isdigit():
#keep going, and add it to the list
elif len(a) == 0:
break #stop the loop
I'm stumped, I have no idea why this is not working. It just ignores everything except for the else statement. No idea what could be causing this, help!
The program is just too simple to mess up, and yet, here it is, not working.
def main(): #the main function, where the program is held.
print("Opening Account List now...\n")#flavor tx to add user context for the list of numbers to be displayed.
infile = open('CHarge Accounts.txt', 'r')#opens the 'CHarge Accounts' text file in read-only mode,
#and saves it to the variable 'infile'.
numbers = infile.readlines()#The '.readlines()' command opens the text file stored in the 'infile'
#variable and and reads every single line of text in the file.
#It then saves the data that has been read to the variable 'numbers'.
infile.close()#This closes the text file being within the 'infile' variable, preventing data from being los,
#and causing errors in the program
index = 0#control value for the number of values to be inserted into the 'numbers' list.
#
while index < len(numbers): #while the index value is less than the number of values within numbers.
#This means that as long as index is less than however many account numbers
#that are within the 'numbers' list, the loop will continue.
numbers[index] = int(numbers[index])#While the loop runs, the values in the numbers index will be
#converted to integer values
index += 1 #controlling value increments for every number read
print (numbers, '\n')
x = 0 #control value for the while loop.
while x == 0: #Loop begins.
accnumber = int(input("Please type in the account number you'd like to change, or type in -1 to exit."))
if accnumber not in numbers and not -1:#Checks if account number is not in the saved txt file data, and
#if the user has inputted the 'kill' value.
print("The account number you have typed in is invalid.")#informs user data is invalid
elif accnumber in numbers and not -1:#Checks if the account number is within the saved text file data, and
#if the user has inputted the 'kill' value.
print("The account number you have selected is valid.")#text informs user that data is valid
elif accnumber == -1:#Checks if the account number value is -1
print("Goodbye!")#Flavor for the user
x = 1 #activates the control variable to break the loop
main()
if accnumber not in numbers and not -1:
# ^^^^^^
When evaluated as a truth-statement, 0 is False and any other integer is True. So -1 is True, not -1 is False, and (anything) and not -1 is always False.
Therefore your if and elif clauses always get skipped.
Try
if accnumber not in numbers and accnumber != -1:
instead.
Also:
your commenting is overdone to the point of obscuring your program. I presume this is some sort of class requirement, ie commenting every line?
your use of while loops and index variables is very non-idiomatic and could be replaced by a list comprehension as follows:
.
def main():
print("Opening Account List now...\n")
with open('Charge Accounts.txt') as inf:
numbers = [int(line) for line in inf]
print(numbers, '\n')
while True:
accnumber = int(input("Please enter an account number (or -1 to exit): "))
if accnumber == -1:
print("Goodbye!")
break
elif accnumber not in numbers:
print("The account number you have typed in is invalid.")
else:
print("The account number you have selected is valid.")
main()
Your code is a bit messy. When you are adding comments, please try to make it reader friendly. Also, spend more time on basic syntax!
def main():
print("Opening Account List now...\n")
infile = open('CHarge Accounts.txt', 'r')
numbers = infile.readlines()
infile.close()
index = 0
while index < len(numbers):
numbers[index] = int(numbers[index])
index += 1
print (numbers, '\n')
x = 0 #control value for the while loop.
while x == 0:
accnumber = int(input("Please type in the account number you'd like to change, or type in -1 to exit."))
if (accnumber not in numbers) and (accnumber !=-1):
print("The account number you have typed in is invalid.")
elif (accnumber in numbers) and (accnumber !=-1):
print("The account number you have selected is valid.")#text informs user that data is valid
elif accnumber == -1:#Checks if the account number value is -1
print("Goodbye!")#Flavor for the user
x = 1 #activates the control variable to break the loop
main()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new to Python, so forgive my newbish question. I have the following code:
[a while loop starts]
print 'Input the first data as 10 characters from a-f'
input1 = raw_input()
if not re.match("^[a-f]*$", input1):
print "The only valid inputs are 10-character strings containing letters a-f"
break
else:
[the rest of the script]
If I wanted to, instead of breaking the loop and quitting the program, send the user back to the original prompt until they input valid data, what would I write instead of break?
To go on with the next loop iteration, you can use the continue statement.
I'd usually factor out the input to a dedicated function:
def get_input(prompt):
while True:
s = raw_input(prompt)
if len(s) == 10 and set(s).issubset("abcdef"):
return s
print("The only valid inputs are 10-character "
"strings containing letters a-f.")
print "Input initial data. Must be 10 characters, each being a-f."
input = raw_input()
while len(input) != 10 or not set(input).issubset('abcdef'):
print("Must enter 10 characters, each being a-f."
input = raw_input()
Slight alternative:
input = ''
while len(input) != 10 or not set(input).issubset('abcdef'):
print("Input initial data. Must enter 10 characters, each being a-f."
input = raw_input()
Or, if you wanted to break it out in to a function (this function is overkill for this use, but an entire function for a special case is suboptimal imo):
def prompt_for_input(prompt, validate_input=None, reprompt_on_fail=False, max_reprompts=0):
passed = False
reprompt_count = 0
while not (passed):
print prompt
input = raw_input()
if reprompt_on_fail:
if max_reprompts == 0 or max_reprompts <= reprompt_count:
passed = validate_input(input)
else:
passed = True
else:
passed = True
reprompt_count += 1
return input
This method lets you define your validator. You would call it thusly:
def validator(input):
return len(input) == 10 and set(input).subset('abcdef')
input_data = prompt_for_input('Please input initial data. Must enter 10 characters, each being a-f.', validator, True)