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))
Related
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
For this lab, I need to write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, adjust each integer in the list by subtracting the smallest value from all the integers. My code runs and I am getting the correct outputs, but the code is meant to output the new integers(after subtracting the smallest value) in the order they were inputted. However, because I sorted the list in the beginning of my program, the numbers are printing in order from smallest to biggest. How do I get them to print in my final statement in the same order that they were inputted? For example, if the numbers inputted were
30, 50, 10, 70, 65, they should output 20, 40, 0, 60, 55. But my program is outputting them as 0, 20, 40, 55,60.
This is the code I have so far:
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
list = []
for i in range(x):
x = int(input())
list.append(x)
list.sort()
smallest = list[0]
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in list:
print(num - smallest)
Instead of sorting the list, you can use a different Python built in function, min(), which takes the smallest number in a list. Using this , you won’t need to sort the list, keeping the original order, and just subtract each element in the list by the int you got from min().
Here it is:
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
lst = []
for i in range(x):
x = int(input())
lst.append(x)
smallest = min(lst)
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in list:
print(num - smallest)
Just making small changes in your code
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
# Using list comprehensive
input_list = [int(input()) for _ in range(x)]
# You can use below code if you want better readability
# for i in range(x):
# x = int(input())
# input_list.append(x)
# Min returns you minimum value from iterator
smallest = min(input_list)
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in input_list:
print(num - smallest)
Output showing order is not changed
Enter the number of integers in the data set: 3
Enter the 3 numbers:
3
2
1
The smallest value is: 1
The normalized data set is:
2
1
0
Process finished with exit code 0
I'm trying to make a while loop that displays all possible perfect squared numbers up to the value is provided by the user input
Below is the code that I have produced for this however this only display the next possible perfect squared number
num = input("Type in a positive whole number: ")
count = 0
square = 0
while square <= num:
count = count + 1
square = count*count
print square
Using Python 3 syntax:
Convert input to int and use a list comprehension like so:
num = int(input("Type in a positive whole number: "))
print([i*i for i in range(int(num**0.5) + 1)])
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.
I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.
def SumAverage(n):
sum=0
for idx in range(1,n+1):
average =sum/idx
return average
num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:
n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+...)
We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.
So the implementation of the average for your application is:
def sum_average(n):
return (n + 1) / 2
This has the added benefit of being O(1).
Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.
Use mean from the statistics module.
from statistics import mean
num = int(input("Enter a number"))
result = mean(list(range(1, num+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. #zr0gravity7 has posted a better method.
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
return round(sum / n, 2)
num = int(input("Enter a number"))
result = SumAverage(num)
print(f'The average of all numbers from 1 to {num} is {result}')
I'm not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.
from statistics import mean
result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.
def SumAverage(n):
sum=0
l = [] # initialize an empty list to fill
n = abs(n) # incase someone enters a negative
# lets fill that list
while n >= 1:
l.append(n)
print('added {} to the list'.format(n), 'list is now: ', l)
n = n - 1 # don't forget to subtract 1 or the loop will never end!
# because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
for idx, n in enumerate(l):
sum = sum + n
# printing it so you can see what is going on here
print('length of list: ', len(l))
print('sum: ', sum)
return sum/len(l)
num =int(input("Enter a number: "))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
Try this:
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
average = sum/n
return average
[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx
]1