def entree_liste():
liste_entier = []
liste_nombre = int(input("Enter list of number separate by space :"))
for chiffre in range(liste_nombre):
liste_entier.append(chiffre)
print(liste_entier)
and my error
liste_nombre = int(input("Enter list of number separate by space :"))
ValueError: invalid literal for int() with base 10: '22 33 44 55'
Basically, I am asking the user for a list of int. If I do liste_entier = list(liste_nombre) they count space as an integer and I don't want to have space in my list only the integer.
The function int() will convert a single value to integer. But you have one giant string with many integer values embedded in it. To solve this problem, first split the giant string into a collection (in this case, a list) of smaller strings, each containing only one integer and then convert each of those strings separately.
To perform the splitting operation, you can use the Python string method .split(). That will return a list of strings. Each of those strings can then be converted to integer:
# get list as string
list_nombre = input("Enter list of numbers separated by space:")
# create list of smaller strings, each with one integer-as-string
list_of_int_strings = list_nombre.split(' ')
# convert list of strings to list of integers
list_of_ints = []
for int_string in list_of_int_strings:
list_of_ints.append(int(int_string)
However, in Python we would more concisely write:
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = ([int(s) for s in list_nombre.split(' ')])
liste_entier = list(map(int, input("Enter list of number separate by space :").split()))
As #Larry suggests, this is a reasonable way to write this in Python
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [int(s) for s in list_nombre.split()]
The problem is that it's not possible to handle exceptions inside the list comprehension. To do this, you may want to write your own, more robust/helpful conversion function
def convert_int(s):
try:
return int(s)
except ValueError as e:
print e
return None
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [convert_int(s) for s in list_nombre.split()]
What you should do is read in the string, of ints separated by spaces then explode it, and case the entires to int.
input = raw_input("Enter list of number separate by space :")
input.split()
then cast he elements to int
its always safer to read in strings, then deal with the return.
The int() function will only take a string that contains only digits. Since a space is not a digit, it will cause an error. To fix this problem, first split the string into a list of smaller strings, and then convert each of the smaller strings into an integer if possible.
string = input('Enter list of space separated numbers: ')
numbers = [int(n) for n in string.split() if n.isdigit()]
Related
Using a for loop, how can a list generated by the input function display each string length in the order that they have been input?
example:
Please enter a list of numbers separated by a comma.
one,two,three,four,five
The length of the string one is 3.
The length of the string two is 3.
The length of the string three is 5.
The length of the string four is 4.
The length of the string five is 4.
Below is the code I have written so far. im sure it's laughable but i can't figure it out.
# stringList will contain a list of strings that have been entered.
stringList = input("Please enter a list of numbers seperated by a comma.\ne.g. Citreon,Ford,Audi,Mercedes\n")
i = 0
for i = 0:
print(f"The length of the string {i} is {(len_stringList[])}."
i += 1
I have tried to construct a for loop in order to display the strings in order, along with each strings length.
The string index number should be in text, with index[0] starting at 'one' up to the final user input (five in the example above)
Each string length should be displayed in a numerical value.
Use split to split the input string into a list, and then you can iterate over that list with a for loop and print the len of each element.
>>> for s in input("Please enter a comma-separated list: ").split(","):
... print(f"The length of {s} is {len(s)}")
...
Please enter a comma-separated list: one,two,three,four,five
The length of one is 3
The length of two is 3
The length of three is 5
The length of four is 4
The length of five is 4
This question already has answers here:
"pythonic" method to parse a string of comma-separated integers into a list of integers?
(3 answers)
Closed 2 years ago.
I'd like to accept a user input consisting of several comma-separated integers and put them in a list. The values are separated by commas. Let's say I'm giving 100,97,84 as input, the desired output would be [100, 97, 84]. I'm trying the following code:
int(input("Please enter the numbers: "))
but it gives me:
ValueError: invalid literal for int() with base 10: '100,97,84'
What should I do?
input will always return a string, even if it is a digit
If you want a number you write int(input"Enter number :))
I don't know what's the relation between your output and input, however you are looking to enter a list as an input. You can do that by
s = (input("Enter the numbers :"))
numbers = list(map(int, s.split()))
This will return a list in numbers. You enter the numbers with a space in between not a comma
E.g
Enter the numbers :100 97 84
Ouput>>>[100, 97, 84]
If you want them without the brackets and separated by a comma, you can use
print(*numbers, sep=',')
will give
Enter the numbers :100 97 84
Output>>>100,97,84
If you want to write number separated by a comma, first you have to split your input into a list of digit only strings and then map this list through int:
numbers = [int(s) for s in input("Please enter numbers separated by a comma:").split(',')]
Because your phrase contains a comma, put it in a quotation mark to convert it to an integer with the following phrase :
s = (input("Enter the numbers :"))
result = ''.join([i for i in s if i.isdigit()])
print(result)
example
Enter the numbers :12,34
output:
1234
The error problem will be solved
I want to take an input of a string of elements and make one list with the atoms and the amount of that atom.
["H3", "He4"]
That sections works, however I also need to make a list of only the elements. It would look something like
["H", "He"]
However when I try and split it into individual atoms it comes out like.
["H", "H", "He"]
Here is my current code for the function:
def molar_mass():
nums = "0123456789"
print("Please use the format H3 He4")
elements = input("Please leaves spaces between elements and their multipliers: ")
element_list = elements.split()
print(element_list)
elements_only_list = []
for element_pair in element_list:
for char in element_pair:
if char not in nums:
elements_only_list.append(char)
test = element_pair.split()
print(test)
print(elements_only_list)
I'm aware that there is a library for something similar, however I don't wish to use it.
Your problem here is that you are appending each non-numeric character to elements_only_list, as a new element of that list. You want instead to get the portion of element_pair that contains non-numeric characters, and append that string to the list. A simple way to do this is to use the rstrip method to remove the numeric characters from the end of the string.
for element_pair in element_list:
element_only = element_pair.rstrip(nums)
elements_only_list.append(element_only)
It could also be done using regular expressions, but that's more complicated than you need right now.
FYI, you don't really need your nums variable. The string module contains constants for various standard groups of characters. In this case you could import string.digits.
To my understanding, you will have user input such as H3 He4 and expect the output to be ['H','He'], accordingly i modified your function:
def molar_mass():
print("Please use the format H3 He4")
elements = input("Please leaves spaces between elements and their multipliers: ")
element_list = elements.split() # splits text to a list
print(element_list)
results = []
for elem in element_list: # loops over elements list
#seperate digits from characters in a list and replace digits with ''
el1 = list(map(lambda x: x if not x.isdigit() else '' , elem))
el2 = ''.join(el1)
results.append(el2)
return results
molar_mass()
using this function, with an input as below:
H3 He4
output will be:
['H','He']
I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement
I'm new to Python and am trying to make a simple program to calculate mean median and mode from numbers input by user. So far I have:
num=[]
UserNumbers=int(input("Enter number sequence separated by spaces: "))
num.append(UserNumbers)
print (num)
I want the user to be able to input multiple int's separated by spaces, however my code only accepts one number. The mean/median/mode part shouldn't be hard as I'm just going to use statistics package in 3.4; just need help with gathering input.
You have to parse the answer if you want it this way.
UserNumbers=input("Enter number sequence separated by spaces: ")
nums = [int(i) for i in UserNumbers.split()]
EDIT:
Duplicate of this question
You can use this one line:
user_numbers = [int(num) for num in raw_input
("Enter number sequence separated by spaces: ").split()]
Notes:
Read about PEP-8
Read about split
List comprehension