I'm new to lists in python and trying to write a code where one inputs 10 numbers using a list and the following is performed:
Copy the number which is even to a new list named "EvenList" and
output that new list.
Output the average of the numbers stored in the new list.
Here is my code:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
while List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Whenever I run this module, after inputting my values my outputs (both the EvenList and average) aren't printed. Here's the output I get:
Example 1:
Enter a number: 1
Enter a number: 2
Example 2:
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 2
By further analysis, I realized whenever an even number was inputted, that's when the code gave an empty output. So I'm speculating my error lies in line 8 - 11 (there may be even more).
I so far changed my inital code:
List[i]=int(input("Enter a number: ")) and EvenList[index]=(List[i])
to
List.append(int(input("Enter a number: "))) and EvenList.append(List[i]) respectively - which I'm still confused as to why the intial code isn't considered to be correct since I thought they did the exact same thing [if someone could explain, it'd be very appreciated] - but that didn't fix this error.
It's because in while loop condition, if the number is even it gets stuck in infinite loop, instead of while add if:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
if List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Here's alternative using list comprehension, sum(), and len() as substitutes of creating EvenList, totalnum, count, and average :
List = [int(input("Enter a number: ")) for i in range(10)]
EvenList = [i for i in List if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)
Or list comprehension in list comprehension:
EvenList = [i for i in [int(input("Enter a number: ")) for i in range(10)] if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)
Related
how can i print the sum of all the numbers between any two given numbers in python.
i am not allowed to use functions like sum(). i can only use while or for loop.
i have a code which does the job but the problem is it also prints result every time after adding two numbers but i only want it to print final sum of all the numbers.
Here's the code:
...
a = int(input("Please enter a number"))
b = int(input("Please enter a number"))
n = 0
for x in range(a+1,b):
n+=x
print(n)
...
thanks
There is an Indentation Error just check the line below the for loop and give the proper indentation. You can refer to my code
a = int(input("Please enter a number: "))
b = int(input("Please enter a number: "))
n = 0
for x in range(a+1,b):
n+=x
print(n)
I'm supposed to write a code that asks users for 10 numbers, create a list with that and then sum them all up. I'm currently able to do that. However, I don't know how to check that the numbers do not overlap each other. If they do, the number is not supposed to be added onto the list.
So I am able to get the program to run such that it asks for a number for 10 times. However, after that, it appears to have a syntax error when producing the sum.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
numberList.append(number)
total = sum(numberList)
total = sum(numberList)
TypeError: 'int' object is not callable
You can use if condition with "not in", it will only add the new numbers in the list. I am not getting any error doing sum operation. May be there is sum indentation issue please check that.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
if number not in numberList:
numberList.append(number)
print "List formed: %s" %numberList
total = sum(numberList)
print "Sum of all elements in list: %d" %total
Console:
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
List formed: [1, 2, 3, 4, 5]
Sum of all elements in list: 15
Removing duplicates from a python list can be done in a few different ways. The most common for lists that need to keep their order is to convert into an OrderedDict because dictionary keys must be unique it will not create additional keys for duplicate elements.
Because we are finding the sum of numbers, order does not matter so we can use a built-in method set() which converts any iterable in to a set (By nature, must have unique elements).
If you need it to be a list you can convert back to list afterwards:
numberList = list(set(numberList))
reduce, map and filter are some of the most important functions to learn in any programming language. For this use case the reduce() is perfect, it performs a rolling computation.
from functools import reduce
final_sum = reduce((lambda x, y: x + y), numberList)
I find my prog's if-else does not loop, why does this happen and how can I fix it for checking?
my prog supposed that store user's inputs which must between 10 and 100, then delete duplicated inputs.
examples: num=[11,11,22,33,44,55,66,77,88,99]
result: `[22,33,44,55,66,77,88,99]
inList=[]
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
if num >= 10 and num <= 100:
inList.append(num)
else:
num = int(input("Please enter a valid number: "))
print(inList)
I found that the if-else only did once, so when I enter invalid num for the 2nd time, the prog still brings me to the next input procedure. What happen occurs?
Please enter number 1 [10 - 100]: 1
Please enter a valid number: 1
Please enter number 2 [10 - 100]:
Additionally, may I ask how can I check the inList for duplicated num, and then remove both of the num in the list?
I'd also suggest a while loop. However the while loop should only be entered if the first prompt is erraneous:
Consider this example:
inList = []
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
while not (num >= 10 and num <= 100):
num = int(input("Please enter a valid number [10 - 100]: "))
inList.append(num)
print(inList)
However, may I suggest something else:
This code creates a list of valid inputs ["10","11"...."100"] and if the input which by default is a string is not inside that list we ask for new input. Lastly we return the int of that string. This way we make sure typing "ashashah" doesn't throw an error. Try it out:
inList = []
valid = list(map(str,range(10,101)))
for x in range(1,11):
num = input("Please enter number {} [10 - 100]: ".format(x))
while num not in valid:
num = input("Please enter a valid number [10 - 100]: ")
inList.append(int(num))
print(inList)
I'm no python expert, and I don't have an environment setup to test this, but I can see where your problem comes from.
Basically, inside your for loop you are saying
if num is valid then
add to array
else
prompt user for num
end loop
There's nothing happening with that second prompt, it's just prompt > end loop. You need to use another loop inside your for loop to get num and make sure it's valid. The following code is a stab at what should work, but as said above, not an expert and no test environment so it may have syntax errors.
for x in range(1,11):
i = int(0)
num = int(0)
while num < 10 or num > 100:
if i == 0:
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
else:
num = int(input("Please enter a valid number: "))
i += 1
inList.append(num)
print(inList)
Is it possible to write a clean code in python to print something like:
Introduce the number of lists you want to have: 3
Introduce how many numbers you want it to have: 3
Number: 1
Number: 2
Number: 3
[1,2,3]
Introduce how many numbers you want it to have: 4
Number: 1
Number: 2
Number: 5
Number: 9
[1,2,5,9]
Introduce how many numbers you want it to have: 5
Number: 1
Number: 7
Number: 2
Number: 8
Number: 3
[1,7,2,8,3]
This is my try at it, but it only works for a list, as I don't know how to add multiple lists:
v1=[]
n=input ("Introduce how many numbers you want it to have: ")
def introdTast():
print("Introduce the numbers: ")
for i in range(0,n):
v1.append(input())
introdTast()
print "v1 =",v1
print "\n"
Your answer is here: The Python Tutorial
However, here you go:
lists = int(raw_input('Introduce the number of lists you want to have: '))
for i in xrange(lists):
numbers = int(raw_input('Introduce how many numbers you want it to have: '))
l = []
for j in xrange(numbers):
l.append(int(input('Number: ')))
print l
I am just starting my first computer science class and have a question! Here are the exact questions from my class:
"Write a complete python program that allows the user to input 3 integers and outputs yes if all three of the integers are positive and otherwise outputs no. For example inputs of 1,-1,5. Would output no."
"Write a complete python program that allows the user to input 3 integers and outputs yes if any of three of the integers is positive and otherwise outputs no. For example inputs of 1,-1,5. Would output yes."
I started using the if-else statement(hopefully I am on the right track with that), but I am having issues with my output.
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
I have this, but I am not sure where to go with this to get the desired answers. I do not know if I need to add an elif or if I need to tweak something else.
You probably want to create three separate variables like this:
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
In your code you only keep the value of the last number, as you are always writing to the same variable name :)
From here using an if else statement is the correct idea! You should give it a try :) If you get stuck try looking up and and or keywords in python.
On the first 3 lines, you collect a number, but always into the same variable (num). Since you don't look at the value of num in between, the first two collected values are discarded.
You should look into using a loop, e.g. for n in range(3):
for n in range(3):
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
Use the properties of the numbers...
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
Try Something like this
if num1< 0 or num2 <0 or num3 < 0:
print ('no')
elif num1 > 0 or num2 > 0 or num3 > 0:
print ('yes')