values = []
while True:
values.append(int(input('Enter a value:')))
if values.append(int(input('Enter a value:'))) == 0:
break
I'm trying to exit the code when an input of 0 is entered. What am I doing wrong?
Each time you call input a new input is being entered, and list.append will add the input to the list and return None, which is not equal to 0.
You can use a variable val to store the input, and use it to test, if you want to store the value 0 in the list, append it before checking:
values = []
while True:
val = int(input('Enter a value:'))
values.append(val) # this will add `0` to the list when it's entered
if val == 0:
break
If you don't want to store it, append it after the if:
values = []
while True:
val = int(input('Enter a value:'))
if val == 0:
break
values.append(val) # this won't add `0` to the list when it's entered
The return of values.append(...) is None. It only updates the variable.
This means your code is always checking None == 0 and will never exit.
a = values.append(int(input('Enter a value:')))
>> Enter a value:0
print(a)
>> None
print(values)
>> [0]
A fix to you code would be:
values = []
while True:
values.append(int(input('Enter a value:')))
if values[-1] == 0:
break
for values[-1], using index -1 is how you get the last value in the list. It's the same as len(values) - 1
Related
Declare an empty array
Let the user add integers to this array, over and over
Stop when the user enters -1
Do not add -1 to the array
Print the array
So far my code below:
A=[]
while True:
B = int(input("Input a continuous amount of integers"))
A = [B]
print(A)
if B == -1:
break
else:
continue
In Python, we call the this [] datatype as list. To append item into a list, you can do A.append(B)
A = []
while True:
B = int(input("Input a continuous amount of integers"))
if B == -1:
break
else:
A.append(B) # modify this line
print(A)
You need to check if user input is -1 before appending it to the array and print it in the if block, append it in the else block.
A=[]
while True:
B = int(input("Input a continuous amount of integers"))
if B == -1:
print(A)
break
else:
A.append(B)
Im trying to make a function that takes in 3 different inputs from the user and validates them to make sure they are all positive integers. Here's my current code
def get_positive_number(prompt):
condition = False
while condition == False:
time = (input("Number of time units:"))
if not time.isnumeric() or int(time) == 0:
print("{} is not a valid number".format(time))
condition = False
elif int(time) > 0
timeInt = int(time)
condition = True
while condition == False:
atoms = (input("Number of atoms to simulate:"))
if not atoms.isnumeric() or int(atoms) == 0:
print("{} is not a valid number".format(atoms))
condition = False
elif int(atoms) > 0
atomInt = int(atoms)
condition = True
while condition == False:
radius = (input("Radius of beaker:"))
if not radius.isnumeric() or int(radius) == 0:
print("{} is not a valid number".format(radius))
condition = False
elif int(radius) > 0
RadInt = int(time)
condition = True
pass
In the future, I would encourage you to search your code for a lot of repetition. There are a lot of statements in your code that are almost exact copies of each other. In responding to the question as posted, the following code can be used to retrieve three positive integers, returned from the function as a list:
def get_positive_integers():
positiveNums = []
for i in range(0, 3):
num=-1
while num < 0:
num = int(input("Enter a positive number {}".format(i)))
positiveNums.append(num)
return positiveNums
That being said, if you would like to have specific prompts (as in your example code), you could pass them to the function as a list, and use the .format() function to insert them.
I'm trying to make a program which adds the player's input to a list that's sorted alphabetically. When I try the program I've come up with it just arranges the words haphazardly, and I don't know whatäs wrong. What am I missing? I am fully aware there's a function which sorts for you, I'm simply doing this for practice.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
array = []
while True:
pl_inp = input('Add something to the list:\n')
location = 0
list_has_content = False
for x in reversed(array):
indx = 0
if alphabet.find(pl_inp[indx]) == alphabet.find(x[indx]):
indx += 1
elif alphabet.find(pl_inp[indx]) > alphabet.find(x[indx]):
list_has_content = True
location = array.index(x)
elif alphabet.find(pl_inp[indx]) < alphabet.find(x[indx]):
location = array.index(x) + 1
break
if location == 0 and list_has_content == True:
array.insert(location, pl_inp)
elif location > 0:
array.insert(location, pl_inp)
else:
array.append(pl_inp)
print(array)
So, I'm making a program that asks for user input to define a variable. What I want it to do is keep prompting them to define variables until they terminate the program. I.E. it prompts A1: and they input 2, and then it Prompts A2: and they input 6, and so on, until they press enter without inputting anything. The problem I am having is that I need unique variables for each time it loops. I also want these variables to be able to access the variables defined outside of the function, without using global.
Here is what I've got:
def userinput():
n = 0
while n >= 0:
c = str(n)
v = 'A'+c+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
As you can see, what it does know is set the user's input equal to v each iteration. I want it to set the first input to A0, then the next iteration, I want it the input to be set to A1, and so on and so forth. Then, after the user has run this, I want to be able to call the variable A1 and get a result. Any ideas?
EDIT:
So, here is my program. It takes input, adds the input to a list, then converts the list items to global variables. I didn't want to use global, but I had to.
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()
Use a list?
def getUserInput():
values = []
while True:
val = input("Enter a value (press enter to finish):")
if not val:
break
values.append(val)
return values
data = getUserInput()
Instead of a while loop, make a for loop wrapped in a while loop, like this:
def userinput():
n = 0
while n >= 0:
for x in range(100):
v = 'A'+x+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
Once again, here is the answer:
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()
Write a program that asks the user to enter some numbers (positives,
negatives and zeros). Your program should NOT ask the user to enter a
fixed number of numbers. Also it should NOT ask for the number of
numbers the user wants to enter. But rather it should ask the user to
enter a few numbers and end with -9999 (a sentinel value). The user
can enter the numbers in any order. Your program should NOT ask the
user to enter the positive and the negative numbers separately.
Your program then should create a list with the numbers entered (make
sure NOT to include the sentinel value (-9999) in this list) and
output the list and a dictionary with the following Key-Value pairs
(using the input list and the above functions):
I know this is a question that has been on the board 3 times, and I've tried copying other examples, but I still get an error stating I'm missing 1 required positional argument. I've tried changing several things with no resolution. I thought my average functions were working, but at this point I'm not even sure of that. This is also my first time posting anything here, so I'm sorry for poor formatting. Below is my code:
def numList():
values = []
while True:
x = int(input("Enter any amount of numbers or -9999 to quit: "))
if x == -9999: break
values.append(x)
return values
def allNumAvg(values):
whole = []
average = 0
for i in values:
whole.append(i)
average = sum(whole)/len(whole)
return average
def posNumAvg(values):
pos = []
average = 0
for i in values:
if i > 0:
pos.append(i)
average = sum(pos)/len(pos)
return average
def nonPosAvg(values):
non = []
average = 0
for i in values:
if i < 1:
non.append(i)
average = sum(non)/len(non)
return average
print(numList())
def store():
return {'all': allNumAvg(), 'pos': posNumAvg(), 'def': nonPosAvg()}()
print(store())
your functions allNumAvg posNumAvg and nonPosAvg all take 1 argument, values. You're calling them without any arguments. allNumAvg()
try changing to this
values = numList()
def store():
return {'all': allNumAvg(values), 'pos': posNumAvg(values), 'def': nonPosAvg(values)}
Apart for not passing the values and trying to call a dict you are calculating the average before the lists have been filled completely, in your code calculate the average outside the loop when you are finished appending:
def posNumAvg(values):
pos = []
# average = 0 don't need to declare variable
for i in values:
if i > 0:
pos.append(i)
average = sum(pos)/len(pos) # only calculate once when done
return average
In allNumAvg you already have a list of values and you then make another list of the exact same values, just use values itself:
def allNumAvg(values):
average = sum(values )/ len(values)
return average
You can use also use list comprehensions:
def num_list():
# "-9999" is the sentinel value which will break the loop if entered
values = [int(i) for i in iter(lambda:input("Enter any amount of numbers or -9999 to quit: "),"-9999")]
return values
def all_num_avg(values):
average = sum(values) / len(values)
return average
def pos_num_avg(values):
pos = [x for x in values if x > 0]
return sum(pos) / len(pos)
def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non)
values = num_list()
def store():
return {'all': all_num_avg(values), 'pos': pos_num_avg(values), 'def': non_pos_avg(values)}
I also changed your function names using underscores which is in line with the pep-8 style guide
Ideally when taking user input it is best to use a try/except to catch bad input from the user:
def num_list():
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
return values
values.append(int(inp)) # any input that cannot be cast will raise a ValueError which we catch and then inform the user
except ValueError:
print("Invalid input")
return values
If a user enters no positive or negative numbers then you will also get a zeroDivisionError so you would also need to handle that case by either using try/except again or returning a default values if the list is empty, we can use a default value as we will have already validated the input to make sure is a number:
def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non) if non else 0
Which can all be done in a single function updating the dict at the end and returning it:
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
# catch cases where user does not enter a mixture of pos and negative nums of break on the first iteration
# if values etc.. will all evaluate to False for an empty list
store_dict["all"] = sum(values) / len(values) if values else 0
store_dict["pos"] = sum(pos) / len(pos) if pos else 0
store_dict["def"] = sum(non) / len(non) if non else 0
return store_dict
print(store())
Because you are using python3.4 we can also let the statistics module handle the averaging:
from statistics import mean
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict
As per your comment if you want a the dict and the list returned you can return both and unpack:
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict,values
d, vals = store() # unpack
print(d, vals)