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)
Related
I'm creating two lists in a while loop, which will stop when the user enters 0. My question is, how do I include 0 in the list?
exit = False
a = []
b = []
while not exit:
x = int(input("Enter number A:"))
y = int(input("Enter number B:"))
if x == 0 and y == 0:
exit = True
else:
a.append(x)
b.append(y)
print(a)
print(b)
You can't. The problem is, you shouldn't use permitted values as conditions to get out of the for loop.
Do you have to insert the x and y values recursively? You could just give the whole lists as input.
If the answer to my previous question is no:
One way to overcome you're problem could be giving the length of the array first, so the program knows when it has to stop:
a = []
b = []
length = int(input("Enter arrays length:"))
for i in range(length):
a.append(int(input("Enter number A:")))
b.append(int(input("Enter number B:")))
We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)
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
import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
for j in range (0, count):
a.append(i)
if (count==3):
break
Output:
[1, 2, 2, 3, 3, 3]
This appears when I prompt the program to print 'a' variable where I want 'a' to store values like
[1, 2, 3]
Can someone point out what's wrong with my code
you can use append but in a different way:
a = []
count = 0
while True:
a.append(input("A number "))
count += 1
if count == 3:
break
in your code you're appending the user's number 'count' times to a[], the way i did it, it will append one time for loop.
You can also use
for x in range(0,3)
a.append(input('A number'))
it work's as well.
The problem with your code, is that you add input number to the a one more time in each while iteration. It's the fault of for loop there.
Also, you don't have to import array.
Also, the if/break combo is redundant, just set iterations in the while loop.
Try this code:
a = []
count = 0
while count < 3:
i = int(input("A number: "))
a.append(i)
count += 1
print(a)
Variable A prints:
[1, 2, 3]
Lose the for loop:
a=[]
count = 0
while count < 3:
count += 1
a.append(int(input("A number ")))
The reason for duplicate values in your list, a, is the inner for loop. To illustrate with an example, consider what happens when you have already entered 1 as the input and now enter 2 as the input. At this moment, before your code begins executing the for loop, count has the value 2. The inner for loop will thus insert your input value, stored in variable i (in this case, 2), twice. Similarly, when you input 3, count has the value 3 and hence the inner for loop will execute three times.
The correct code should be as follows :
import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
if (count==3):
break
Remove the for-loop or simply do
a=[]
count=3
for i in range(count):
a.append(int(input("new number: ")))
Importing array isn't needed here.
And a little hint (if you don't allready know): i+=1 is the same as i=i+1
By playing the answer from deshu, you might also consider to use try and except so that the user could continue to type a number and prompt him if ever he enter non-numeric character.
a = []
count = 0
while count < 3:
try:
i = int(input("A number: "))
a.append(i)
count += 1
except:
print('Enter only a whole number.')
print(a)
def silly(n):
"""requires: n is an int > 0
Gets n inputs from user
Prints 'Yes' if the inputs are a palindrome; 'No' otherwise"""
assert type(n) == int and n > 0
for i in range(n):
result= []
elem = input('Enter something: ')
result.append(elem)
print(result)
if isPal(result):
print('Is a palindrome')
else:
print('Is not a palindrome')
If you try running this function, with for example, as n = 3, why doesn't the elem append to the result properly? It keeps printing as new list of results. This messages up my isPal function.
The first line of your for loop replaces your result variable with a new list.
result= []
You should do this before the for loop instead.
Swap these lines:
result = []
for i in range(n):
# ...
Or you will be reassigning result in every iteration.
The issue is that you are redefining result each time.
def silly(n):
"""requires: n is an int > 0
Gets n inputs from user
Prints 'Yes' if the inputs are a palindrome; 'No' otherwise"""
assert type(n) == int and n > 0
result= []
for i in range(n):
elem = input('Enter something: ')
result.append(elem)
print(result)