Posts: 201
Threads: 37
Joined: Dec 2021
Hello,
Trying to sum string numbers to int, but there is a ; between them.
tab = input("Éntrez les nombres entiers séparés par des (;) : ")
list_nb= [tab]
list_nb = [item.replace(";"," ") for item in list_nb]
nbs = list(map(int, list_nb))
somme = 0
for nb in nbs:
print((somme + nb)/len(nbs))
Error: Éntrez les nombres entiers séparés par des (;) : 4;5;7;
Traceback (most recent call last):
File "<string>", line 10, in <module>
ValueError: invalid literal for int() with base 10: '4 5 7 '
>
Why i get this error. Numbers need to be input with ";"
Thank you
Posts: 1,139
Threads: 114
Joined: Sep 2019
Feb-13-2022, 04:01 PM
(This post was last modified: Feb-13-2022, 04:01 PM by menator01.)
tab = input('Enter numbers seperated with (;) : ') .split(';')
print(tab)
tab = list(map(int, tab))
print(tab)
somme = 0
for number in tab:
print((somme + number)/len(tab)) Output: Enter numbers seperated with (;) : 5;9;6;7
['5', '9', '6', '7']
[5, 9, 6, 7]
1.25
2.25
1.5
1.75
Posts: 201
Threads: 37
Joined: Dec 2021
only thing 5+6+9+7 = 6.75 not 1.75
Posts: 1,139
Threads: 114
Joined: Sep 2019
Feb-13-2022, 04:13 PM
(This post was last modified: Feb-13-2022, 04:13 PM by menator01.)
use sum(tab) instead of len(tab)
Output: Enter numbers seperated with (;) : 5;6;9;7
['5', '6', '9', '7']
[5, 6, 9, 7]
0.18518518518518517
0.2222222222222222
0.3333333333333333
0.25925925925925924
6.75
Posts: 2,168
Threads: 35
Joined: Sep 2016
user_input = input("Éntrez les nombres entiers séparés par des (;) : ")
numbers = [int(item) for item in user_input.split(";")]
print(sum(numbers) / len(numbers))
Posts: 201
Threads: 37
Joined: Dec 2021
Feb-13-2022, 04:33 PM
(This post was last modified: Feb-13-2022, 04:41 PM by Yoriz.
Edit Reason: Added code tags
)
Cant use sum in this assignment and its returning error anyway:
Error: Éntrez les nombres entiers séparés par des (;) : 4;5;5;
Traceback (most recent call last):
File "<string>", line 6, in <module>
File "<string>", line 6, in <listcomp>
ValueError: invalid literal for int() with base 10: ''
>
Posts: 2,168
Threads: 35
Joined: Sep 2016
Feb-13-2022, 04:42 PM
(This post was last modified: Feb-13-2022, 04:50 PM by Yoriz.)
The above error is nothing to do with sum you are trying to turn an empty string into an int
You have a ; at the end of the input string so when the split happens you end up with an empty string as the last list item.
Posts: 201
Threads: 37
Joined: Dec 2021
I got it now. Stupid misunderstanding
Thanks guys
Posts: 1,139
Threads: 114
Joined: Sep 2019
tab = '5;6;9;7'.split(';')
tab = list(map(int, tab))
somme = 0
total = 0
for number in tab:
total += number
print(f'Sum of tab list is: {total}')
for number in tab:
print((somme + number)/total) Output: Sum of tab list is: 27
0.18518518518518517
0.2222222222222222
0.3333333333333333
0.25925925925925924
|