this is the task im busy with:
Write a program that starts by asking the user to input 10 floats (these can
be a combination of whole numbers and decimals). Store these numbers
in a list.
Find the total of all the numbers and print the result.
Find the index of the maximum and print the result.
Find the index of the minimum and print the result.
Calculate the average of the numbers and round off to 2 decimal places.
Print the result.
Find the median number and print the result.
Compulsory Task 2
Follow these steps:
Create
this is what i have but getting the following error:
ValueError: invalid literal for int() with base 10:
CODE:
user_numbers = []
#input request from user
numbers = int(input("Please enter a list of 10 numbers (numbers can be whole or decimal):"))
for i in range(0,numbers):
el = float(input())
user_numbers.append(el)
print("Your list of 10 numbers:" + str(user_numbers))
you can refer to the solution :
user_numbers = []
#input request from user
numbers = list(map(float, input().split()))
print("total of all the numbers : " + str(sum(numbers)))
print("index of the maximum : " + str(numbers.index(max(numbers)) + 1))
print("index of the minimum : " + str(numbers.index(min(numbers)) + 1))
print("average of the numbers and round off to 2 decimal places : " + str(round(sum(numbers)/len(numbers),2)))
numbers.sort()
mid = len(numbers)//2
result = (numbers[mid] + numbers[~mid]) / 2
print("median number :" + str(result))
let me know if you have any doubts.
Thanks
Related
I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.
So I'm writing a basic program, and part of the output is to state the lowest and highest number that the user has entered. For some reason, the min and max are correct some of the time, and not others. And I can't figure out any pattern of when it's right or wrong (not necessarily when lowest number is first, or last, etc). Everything else works perfectly, and the code runs fine every time. Here is the code:
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(x)
total = total + int(x)
count = count + 1
avg = total / count
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
Any ideas? Keep in mind I'm (obviously) pretty early on in my coding study. Thanks!
If, at the end of your program, you add:
print("Your input, sorted:", sorted(lst))
you should see the lst in the order that Python thinks is sorted.
You'll notice it won't always match what you think is sorted.
That's because you consider lst to be sorted when the elements are in numerical order. However, the elements are not numbers; when you add them to lst, they're strings, and Python treats them as such, even when you call min(), max(), and sorted() on them.
The way to fix your problem is to add ints to the lst list, by changing your line from:
lst.append(x)
to:
lst.append(int(x))
Make those changes, and see if that helps.
P.S.: Instead of calling str() on all those integer values in your print statements, like this:
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
you can take advantage of the fact that Python's print() function will print each argument individually (separated by a space by default). So use this instead, which is simpler and a bit easier to read:
print("The total of all the numbers your entered is:", total)
print("You entered", count, "numbers.")
print("The average of all your numbers is:", avg)
print("The smallest number was:", min(lst))
print("The largest number was:", max(lst))
(And if you want to, you can use f-strings. But you can look that up on your own.)
You convert your input to int when you are adding it to the total, but not when you are finding the min and max.
When given strings, min and max return values based on alphabetical order, which may sometimes happen to correspond to numerical size, but in general doesn't.
All you need to do is to append input as ints.
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(int(x)) # this should fix it.
total = total + int(x)
count = count + 1
avg = total / count
You might also want to use string formatting to print your answers:
print(f"The total of all the numbers your entered is: {total}")
print(f"You entered {count} numbers.")
print(f"The average of all your numbers is: {avg}")
print(f"The smallest number was: {min(lst)}")
print(f"The largest number was: {max(lst)}")
Dear stackoverflow community!
I just started learning python and want to figure out how to write following program:`
number = int(input('Enter ten numbers:'))
for i in range(1, 10):
while True:
try:
number = int(input("Enter another number: "))
break
except:
print("This is a string")
for i in range(1, 10):
res = 0
res += int(input())
print('The sum of these 10 numbers is:', res)
I want the user to input 10 numbers and during the process I want to check if the numbers are actually integers. So the number input works, it checks if its an integer, but then how can make this work at the same time? (To sum up the 10 integers that I got as input) :
for i in range(1, 10):
res = 0
res += int(input())
print('The sum of these 10 numbers is:', res)
So basically i want two conditions for those 10 numbers that I got as Input.
Thanks for your help.
You are simply checking the user input, not storing it somewhere. Use this instead:
numbers = []
while len(numbers) != 10:
try:
numbers.append(int(input("Enter another number: ")))
except ValueError:
print("This is not an integer!")
res = sum(numbers)
print('The sum of these 10 numbers is: {}'.format(res))
I want to create a program that asks for three numbers, then displays the range, sum of the numbers in that range, and average of the numbers in the range. Why is it that this program is not able to interpret the list as integers?
numbers = list()
for i in range(0, 3):
inputNr = int(input("Enter a number: "))
numbers.append(inputNr)
rangeofNums = range(numbers)
sumRange =
print("The range is: " + rangeofNums)
print("The total sum is: " + sumRange)
print("The avg is: " + avgRange)
The range function takes in one, two or three integer arguments, not a list. Python documentation about range. If you want to make a range using the minimun and maximum numbers provided by user, you should do:
range_of_nums = range(min(l), max(l) + 1)
This produces a range that includes both the minimum and maximum of inputs as well as all numbers between them. Also you should use format (docs) or f string literals (docs) when printing. All in all:
numbers = list()
for i in range(0, 3):
inputNr = int(input("Enter a number: "))
numbers.append(inputNr)
range_of_nums = range(min(numbers), max(numbers) + 1)
sum_range = sum(range_of_nums)
avg_range = sum_range / len(range_of_nums)
print("The range is: {}".format(range_of_nums))
print("The total sum is: {}".format(sum_range))
print("The avg is: {}".format(avg_range))
What is wrong with this? I need to get it to sum negative numbers too.
Result = int(input('Enter a number: ')) M = (result) For I in range(m): Result = result + i Print(result)
Probably an indentation error, but your for loop should read,
"for i in range(m):"
not "for I in range(m):"
The print function should be in lowercase letters as well.
Python is case sensitive so make sure all of your variables are matching up.
This code works for you.
n = int(input())
result=0
for i in range(n):
print "Enter number"
num = int(input())
result+=num
print"The sum is", result
This fixes it for negative input values; it still has a problem if input is 0.
upto = int(input("Enter a number: "))
sign = abs(upto) // upto # +1 or -1
upto = abs(upto)
total = sign * sum(range(upto + 1))
print("The result is {}".format(total))