I have an activity for some practice for a Python class. The aim is to have unlimited amount of input from the user and assuming user is inputting correct data. The input needs to end when a blank line is detected. (this is what seems to have me stumped, trying to avoid a Value Error when doing this.)
After input ends I need to sort numbers and find the total of numbers and average of numbers.
numbers = []
num_input = []
tot_numbers = []
while num_input != "":
try:
num_input = int((input("Input a number: ")))
numbers.append(num_input)
numbers.sort()
print(numbers)
except:
pass
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
break
This code above is what I have come to and it works but I am not too happy with it because of using 'except'. I know there is a better way and that it probably uses an if statement within the while loop, I have been playing around with something like:
if num_input.isnumeric():
but I get an AttributeError because I can't check if a list is numeric, any help would be greatly appreciated, thankyou!
Check that the input is digit then only cast it to int and store it into the list and perform operation as below:
numbers = []
num_input = []
tot_numbers = []
while num_input != "":
num_input = input("Input a number: ")
# Check if it input is digit then only append it to the list after casting it to int
if num_input.isdigit():
numbers.append(int(num_input))
numbers.sort()
print(numbers)
else:
# if user at first attemp entres blank line then there will not be any elements in the list
# so only if list has some elements then only these operations should be doen
if len(numbers)>0:
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
break
Check this out:
numbers = []
num_input = []
tot_numbers = []
num_input = input("Input a number: ")
while num_input != "":
numbers.append(int(num_input))
numbers.sort()
print(numbers)
num_input = input("Input a number: ")
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
We can achieve your desired solution without the try except, as you said. I have revised some of your code and added an explanation to the changes in the comments.
numbers = []
# first user input prompt
num_input = input("Input a number: ")
# isnumeric() checks if strings contain only numbers, and will return True if so, False if not
while num_input.isnumeric():
# append to the 'numbers' list, converting it into an int (since we're sure that it's an int now)
numbers.append(int(num_input))
# prompt the user again
num_input = input("Input a number: ")
# we can sort the list after all the elements are added, so it's called just once
numbers.sort()
tot_numbers = sum(numbers)
print("Sorted numbers: ", numbers)
print("Total of numbers: ", tot_numbers)
print("Average of numbers: ", (tot_numbers / len(numbers)))
I'll throw my hat in the ring. ;^) The key, I think, is accepting that the user input will either be a valid number or nothing at all. If nothing, then you are done looping. If a valid number then convert it to an int and add it to a list until looping is done. Once done, if any numbers at all perform your operations and print your results.
Edit: Fixed the bug Hetal caught.
Example:
numbers = []
while True:
num_text = input("Input a number: ")
if not num_text:
break
numbers.append(int(num_text))
if numbers:
print(f"Sorted numbers: {sorted(numbers)}")
tot_numbers = sum(numbers)
print(f"Sum of numbers: {tot_numbers}")
avg_numbers = tot_numbers / len(numbers)
print(f"Avg of numbers: {avg_numbers:.2f}")
print("Finished.")
Output:
Input a number: 2
Input a number: 3
Input a number: 1
Input a number:
Sorted numbers: [1, 2, 3]
Sum of numbers: 6
Avg of numbers: 2.00
Finished.
There is a few things wrong with your code, first num_input is not an array, you put a singular value into it with the input() line. Next, you don't need a pass after except if there are lines of code after it.
Here is what you want to accomplish with the type() function:
num_input = input("Here: ")
if type(num_input) == int:
num_input = int(num_input)
#code
else:
#Its not an integer
The reason why you get the error is because that method doesn't exist, type() is the one you are looking for
Related
The program allow the user to enter any number of numbers to a list but when it get to the part to sum it an error.
number_list = []
while True:
number = input('Please enter a number (RETURN/ENTER when done): ')
if number == '':
break
number_list.append(number)
for date in range(0,1):
print("The numbers entered were: ")
print(number_list)
print()
print()
print('The sum is: ', sum(number_list))
You are missing the int conversion after checking the string wasn't empty. Also for date in range(0,1): seems pretty useless, as it iterates once, and you don't use the iteration value, just use the code
number_list = []
while True:
number = input('Please enter a number (RETURN/ENTER when done): ')
if number == '':
break
number_list.append(int(number))
print("The numbers entered were: ", number_list, ', their sum is', sum(number_list))
Do Explicit Type conversion to int while inserting into the list.
number_list = []
while True:
number = input('Please enter a number (RETURN/ENTER when done): ')
if number == '':
break
number_list.append(int(number))
for date in range(0, 1):
print("The numbers entered were: ")
print(number_list)
print()
print()
print('The sum is: ', sum(number_list))
You forgot to convert string to integer. sum requires integers. int() will help you convert the string to an integer
while True:
number = input('Please enter a number (RETURN/ENTER when done): ')
if number == '':
break
number_list.append(int(number))
print('The sum is: ', sum(number_list))
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 trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))
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))
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))