I'm new to programming and currently learning python with reference book Python Programming Fundamentals. Here is one of the question I am dealing with:
1: Request user to input a list of numbers.
2: Then output those numbers which is in between 0 and 100.
Following is my code:
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output = output.append(float(e))
else:
output = output
print("The number between 0 and 100 are ", output)
And the error is:
File "c:\Users\HKGGAIT001\Desktop\1.py", line 7, in <module>
output = output.append(float(e))
builtins.AttributeError: 'NoneType' object has no attribute 'append
Supposing you are using Python3 (because it's unlikely the .split() would be successful in Python2)
This part is ok
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
You can write the loop like this
for e in lst:
if 0 < float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
Notice that there are two comparisons. There is an implicit and. This is called a chained comparison
This pattern can be reduced down to a single line using a list comprehension
output = [float(e) for e in lst if 0 < float(e) < 100]
But now we need to use float(e) twice
We can use another list comprehension to make lst already a list of float
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = [float(e) for e in s.split()] # Now lst is a list of floats.
output = [e for e in lst if 0 < e < 100]
Since we only need to iterate lst once, a tiny change makes it a generator expression. So your final program could be
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = (float(e) for e in s.split()) # Now lst is a generator of floats.
output = [e for e in lst if 0 < e < 100]
print("The number between 0 and 100 are ", output)
Your current code has a couple of issues, assuming you're in Python 2.x.
Using input causes Python to try to evaluate the user input, which will cause problems because you want them to input a list of numbers. raw_input will just give you what the user input without trying to parse it.
list.append is in-place, which means that the side effect of the function call will simply perform the append on the object it is called on, instead of returning a new object.
Try this:
s = raw_input("Please enter a list of numbers: ")
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
print("The number between 0 and 100 are ", output)
s = str(input("Please enter a list of numbers:"))
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 :
output.append(float(e))
print("The number between 0 and 100 are ", output)
else:
print("The number less than 0 or greter than 100 ", e)
s = input("Please enter a list of numbers:")
output = [each for each in s if each > 0.0 and each < 100.0]
print("The number between 0 and 100 are ", output)
Related
I'm writing a program which should produce an output of something like this:
`Enter an integer (or Q to quit): 1
Enter an integer (or Q to quit): 2
Enter an integer (or Q to quit): 3
Enter an integer (or Q to quit): Q
(1 x 1) + (2 x 2) + (3 x 3) = 14`
So far, I've gotten the display of the equation right, but I can't seem to figure out how to actually get the total of the equation. Currently, the total displays 18 instead of the expected 14.
Here's my code so far:
`int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)`
Any help would be greatly appreciated :))
Your problem exists in the here:
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)
Let us walk through what the code does to get a better understanding of what is going wrong.
With a list of [1, 2, 3] The for loop will iterate three times
On the first iteration, x will be assigned the value 1 because 1 * 1 is 1.
On the second iteration, x will be assigned the value 4 because 2 * 2 is 4. Notice that rather than the two values being added x's value being overwritten
On the third iteration, x will be assigned the value 9 because 3 * 3 is 9. Again the value is being overwritten.
After the loop, the variable add is created with the value x + x, or in our case 9 + 9 which is 18
This is why with the list [1, 2, 3] the value displayed is 18
Now that we have walked through the problem. We can see that the problem is overriding the value in the for loop then doubling the value before displaying it.
To fix these problems we can first remove the doubling giving the following code
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
print(x)
But the program still has the overriding problem so the value of a list [1, 2, 3] would be 9.
To fix this rather than overriding the value of x, let's create a new variable total that will have the result of the loop added to it every iteration rather than being overwritten.
total = 0
for i in range(0, len(int_list)):
total = total + (int_list[i]*int_list[i])
print(total)
Now let's walk through what the code does now.
With a list of [1, 2, 3] the for loop will iterate three times
On the first iteration, total will be assigned the value 1 because 0 + 1 * 1 is 1.
On the second iteration, total will be assigned the value 5 because 1 + 2 * 2 is 5. Notice how the previous value of the loop iteration is being added to the loop
On the third iteration, total will be assigned the value 14 because 5 + 3 * 3 is 14. Notice again how the previous value of the loop iteration is being added to the loop.
This gives us the correct result of 14.
One nice feature of python is the addition assignment which condentes A = A + B to A += B so it is possible to simply the following code to:
total = 0
for i in range(0, len(int_list)):
total += (int_list[i]*int_list[i])
print(total)
A reason this problem may have been so difficult is that the for loop is more complicated than it needs to be. It is possible that rather than iterating through a list of indices generated by a list of numbers then assessing the numbers from the list by their index. It is possible to iterate through the numbers directly.
With the that simplification your loop would look like this:
total = 0
for number in int_list:
total += number * number
print(total)
These changes would make your whole programme look like this:
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
total = 0 # start the total at zero as no values have been calculated yet
for number in int_list: # iterate through all values in the list
total += number * number # add to the total the number squared
print(total)
You duplicate only the last product (2 x 3 x 3 = 18).
Because you reassign x in your loop (x = (int_list[i]*int_list[i])) and than duplicate x with add = (x+x).
But you have to build the sum.
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list) - 1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
x = 0
for i in range(0, len(int_list)):
x += (int_list[i] * int_list[i])
print(x)
You can try this
state= True
combi= []
while state:
user_input = input("Enter an integer (or Q to quit): ").lower()
if "q" in user_input:
state= False
else:
combi.append(int(user_input))
else:
final= sum([x+x for x in combi])
print(final)
Hello I am having trouble inputting two numbers from stdin using the following code as I am not quite yet familiar with this feature, when I input numbers manually the code seems to work properly but I can't get sys.stdin.readline to properly work.
import sys
def k(upto):
def collatz(n):
if n < upto and lst[n] > 0:
return lst[n]
if n % 2 == 0:
val = collatz(n/2) + 1
else:
val = collatz((3*n + 1)/2) + 2
if n < upto:
lst[n] = val
return val
lst = [0]*upto
lst[1] = 1
lst[0] = 1
for i in range(mini,upto):
collatz(i)
return max(lst)
line=int(sys.stdin.readline())
maxi = max(line)
mini = min(line)
print k(maxi)
The code produces the following error: TypeError: 'int' object is not iterable. Any assistance would be appreciated.
EDIT ::: Should have mentioned only two numbers will be input, one per line.
After reading your comment, it looks like you want something like this
line = list()
for x in range(2):
line.append(int(sys.stdin.readline()))
That will read 2 lines from STDIN, convert each line to an int, and append each value to line.
The "one per line" is an important information :)
If you're reading one per line you're code is quite close - except you're reading only one line: your variable line is only one number - hence min and max can't work.
You could do something like
i1 = int(raw_input("Enter first number: "))
i2 = int(raw_input("Enter second number: "))
maxi = max(i1, i2)
mini = min(i1, i2)
...
note: If you switch to Python 3 (recommended) it's input() instead of raw_input()
old version:
What is the input? A list of integers, e.g. 2 3 5? This will be interpreted as a string "2 3 5". To convert this into integers you to have to do something like
line = [int(i) for i in sys.stdin.readline().split()]
This
- will split() the input into an array of strings ["2", "3", "5"] and then
- apply the int() conversion to each element of the array.
So I'm writing some code for my class and have to have a list of floats that are input by a user and print them out with normal iteration and reverse iteration, and I have basically all of it done. But when it should ask multiple times for the user input, it only asks one time then prints everything out and finishes without asking multiple times.
Any help would be appreciated as to why it isnt asking multiple times for input even though I have a for loop?
Is there an easier way to get a list of floats from user input that I don't know about?
Thanks
emptyList = []
userInput = high = low = total = float(input("Input a float > "))
emptyList.append(userInput)
for y in range(len(emptyList)-1):
userInput = float(input("Input a float > "))
emptyList.append(userInput)
total += emptyList
if userInput > high:
high = userInput
if userInput < low:
low = userInput
avg = total / len(emptyList)
above_avg = below_avg = 0
for y in range(len(emptyList)):
if emptyList[y] > avg:
above_avg += 1
if emptyList[y] < avg:
below_avg += 1
I checked your logic and according to that you are running your first for loop to the length of emptyList-1 so, after adding one element your emptylist's length becomes 1 and 1-1=0 so, your for loop will work only to 0th index and after that it will break.
I tried this
a=[]
b = []
t=0
count = 0
total = 0
for i in range(0,5):
x= float(input())
count = count + 1
total = total+ x
a.append(x)
print(count)
for i in range(count-1,-1,-1):
print('Aya')
print (i)
b.append(a[i])
for i in range(0,count-1):
for j in range(i,count):
if(a[i]>a[j]):
t=a[i]
a[i]=a[j]
a[j]=t
print(a)
print(b)
print(total)
print(total/count)
print(a[0])
and found it working perfectly fine for me and my for loop is taking values on every iteration.
You may try like this:
n = int(input("Number of inputs: "))
emptyList = []
while n:
userInput = float(input("Enter a Float > "))
emptyList.append(userInput)
n-=1
print(emptyList)
I'm trying to count the number of occurrence of a number in a list. So basically, i have a list:
lst = [23,23,25,26,23]
and the program will first prompt the user to choose a number from the list.
"Enter target number: "
and for example, if the target is 23, then it will print out how many times 23 occur in the list.
output = 3 #since there are three 23s in the list
Here's what I've tried and it resulted in an infinite loop:
lst = [23,23,24,25,23]
count = 0
i = 0
prompt= int(input("Enter target: "))
while i< len(lst)-1:
if prompt == lst[i]:
count+=1
print(count)
else:
print("The target does not exist in the list")
I'm not supposed to use any library so i would really appreciate if anyone could help me out by pointing out the fault in the code i written. Also, i would prefer the usage of 'while loop' in this as I'm practicing using while loops which i understand the least.
i is 0 always, which results in an infinite loop. Consider increasingi by 1 at the end of your loop.
Moreover you need to go until the end of the list, so the while loop condition should be:
while i < len(lst):
Putting everything together should give this:
while i< len(lst)a:
if prompt == lst[i]:
count+=1
print(count)
else:
print("The target does not exist in the list")
i += 1
which outputs:
Enter target: 23
1
2
The target does not exist in the list
The target does not exist in the list
3
By the way here is what a more pythonic implementation would look like:
lst = [23,23,24,25,23]
count = 0
target = int(input("Enter target: "))
for number in lst:
if number == target:
count += 1
print(count)
Output:
Enter target: 23
3
Or if you want to use a build-in function, you could try:
print(lst.count(target))
as smarx pointed out.
you should print after loops over, not every single loop
lst = [23,23,24,25,23]
count = 0
i = 0
prompt= int(input("Enter target: "))
while i< len(lst):
if prompt == lst[i]:
count+=1
i+=1
if count>0:
print(count)
else:
print("The target does not exist in the list")
You can use count for this task :
lst = [23,23,24,25,23]
prompt= int(input("Enter target: "))
cnt = lst.count(prompt)
# print(cnt)
if cnt:
print(cnt)
else:
print("The target does not exist in the list")
Output :
Enter target: 23
3
Enter target: 3
The target does not exist in the list
You may use collections.Counter which aims at performing what you desire. For example:
>>> from collections import Counter
>>> lst = [23,23,25,26,23]
>>> my_counter = Counter(lst)
# v element for which you want to know the count
>>> my_counter[23]
3
As mentioned in the official document:
A Counter is a dict subclass for counting hashable objects. It is an
unordered collection where elements are stored as dictionary keys and
their counts are stored as dictionary values. Counts are allowed to be
any integer value including zero or negative counts. The Counter class
is similar to bags or multisets in other languages.
You may try using filter for this.
>>> lst = [23,23,24,25,23]
>>> prompt= int(input("Enter target: "))
Enter target: 23
>>> len(filter(lambda x: x==prompt, lst))
3
>>> prompt= int(input("Enter target: "))
Enter target: 24
>>> len(filter(lambda x: x==prompt, lst))
1
I am trying to add all of the negative integers in a user input list, but the function always returns 0 as the answer. It works if I include the list as part of the function, but not when its user input. The code I have is:
def sumNegativeInts(userList):
userList = []
sum = 0
for i in userList:
if i < 0:
sum = sum + i
return sum
userList = input("Enter a list of +/- integers: ")
print(sumNegativeInts(userList))
sum(i for i in alist if i < 0)
Done. It's Python, it has to be simple!
remove the second line of your code, it sets the input to an empty list no matter what your input is.
You assign an empty list to userList every time you enter the function, how can it not be 0?
Further more, the function input() seems not able to handle a list of inputs.
So I think you can do this:
def sumNegativeInts(userList):
sum = 0
for i in userList:
if i < 0:
sum += i
return sum
inputData = raw_input('some prompts')
userList = [int(i) for i in inputData.split(' ')]
print(sumNegativeInts(userList))
You could always just do if and elif statements to determine whether or not to add a number to a list and then take the sum of the list. My prompt is making a list of 100 number with random integers from -100 to 100. Then finding the sum of all the negative numbers.
import random
def SumNegative():
my_list = []
for i in range(100):
x = random.randint(-100, 100)
if x > 0:
pass
elif x < 0:
my_list.append(x)
print(sum(my_list))
SumNegative()