This question already has answers here:
Taking multiple integers on the same line as input from the user in python
(19 answers)
Closed 1 year ago.
I want to take multiple integer inputs in the same line. I know I can take str input and then convert them into integer in the next line but is there any way I can do it in the same line.
I have tried this:
x,y = int(input("->")).split()
print(x,y)
I am getting this error :
ValueError: invalid literal for int() with base 10
You messed up with parenthesis (split works on string not int)
then you expect a tuple for x,y = ...
the solution is:
x, y = [int(i) for i in input("->").split()]
print(x, y)
You are taking int as input which cant be split
x,y = input("->").split()
print(x,y)
you can change to int if you like later
print(int(x),int(y))
Related
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 10 months ago.
the string will be the price of some product, so it will basically come like this '1,433.10', the problem is that I need to compare it with the value that the user enters in an input that is only possible to enter integers because of the isdigit() method , used to check if the input is a number, and this causes the comparison to fail.
I already tried converting to int, to float and nothing worked, it only generated exceptions
def convert_values():
price = results['price'][2:] # here is where the string with the value is, which in this case is '1,643.10'
print(int(float(price))) # if I try to cast just to int: ValueError: invalid literal for int() with base 10: '1,643.10'
Before converting, replace the commas in the string with '' as:
price = results['price'][2:].replace(',', '')
print(int(float(price)))
This question already has answers here:
Change a string of integers separated by spaces to a list of int
(8 answers)
Closed 1 year ago.
In textEdit there are numbers separated by line breaks and I want to use them, but these numbers are a string and I couldn't convert them to integers.
This error is shown
ValueError: invalid literal for int() with base 10:' 15\n300\n2000\n'.
How can I use this content of TextEdit as integers?
t = self.TextEdit_numbers.toPlainText()
numbers = int(t)
I see there is a new line (\n) symbol in your TextEdit_numbers value.
It is not possible to convert something as
15
300
2000
to single integer.
I believe you want pass array of integers to your pie method.
You should try something like that:
self.numbers_string = self.TextEdit_numbers.toPlainText()
self.t = [int(n) for n in self.numbers_string.split('\n')
pyplot.pie(self.t, normalize=True)
In second line I use list comprehensions, you can read more about it here (https://www.w3schools.com/python/python_lists_comprehension.asp), and standard python string .split() method, more info here: https://www.w3schools.com/python/ref_string_split.asp
If you have integers on each line, this would give you a list of all those integers:
with open('TextEdit_numbers.txt') as f:
numbers = [int(x) for x in f]
Assuming the txt file has inputs like:
15
200
3000
The output would be the array number as:
[15, 200, 3000]
This question already has answers here:
Negative form of isinstance() in Python
(3 answers)
Closed 2 years ago.
Here's the info:
I have a list like this
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
Looking to create three lists - integer, string and float
Integer list will have: 9,0,-5,1,-600,4
Float list will have: 0.7,5.9
String list will have: Europe,-9,English,0,-2,-3.7,Python
Wrote this program. Output was integers and integers marked as string. Not kind of what I want. Tweaked it to do the same with float. Did not work. Looking for a better way to get the desired output. Thanks!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
You can read about list comprehension here
int() tries to convert its argument to an int, raising a ValueError if this can’t be done. While it’s true that any integer argument to int() will not raise a ValueError, non-integer arguments like ‘9’ can be successfully converted to an integer (the integer 9 in this case), therefore not raising a ValueError.
Hence, trying to verify whether something is an integer by calling int() on it and catching ValueErrors just doesn’t work.
You should really be using the isinstance() function. Specifically, item is an int if and only if isinstance(item, int) returns True. Similarly, you can check for strings or floats by replacing int by str or float.
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 6 years ago.
I have a list in python and I want to get the average of all items. I tried different functions and even I wrote a small function for that but could not do that. even when I tried to convert the items to a int or float it gave these errors:
TypeError: float() argument must be a string or a number
TypeError: int() argument must be a string or a number, not 'list'
here is a small example of my list in python.
['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
do you guys know how to get the average of items in such list/
thanks
Assuming that '0,0459016' means '0.0459016':
In [6]: l = ['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
In [7]: reduce(lambda x, y: x + y, map(lambda z: float(z.replace(',', '.')), l)) / len(l)
Out[7]: 0.033906559999999995
Please refer to How can I convert a string with dot and comma into a float number in Python
sum([float(v.replace(",", ".")) for v in a]) / len(a)
where a is your original list.
Try this,
In [1]: sum(map(float,[i.replace(',','.') for i in lst]))/len(lst)
Out[1]: 0.033906559999999995
Actulluy there is 2 problem in your list. The elements are string and instead of . it having ,. So we have to convert to normal form. like this.
In [11]: map(float,[i.replace(',','.') for i in lst])
Out[11]: [0.0459016, 0.0426647, 0.0324087, 0.0222222, 0.0263356]
Then perform the average.
This question already has answers here:
How to print list item + integer/string using logging in Python
(2 answers)
Closed 7 years ago.
I am coding in Python, and have reached an error that I cannot seem to solve. Here's the part of the code that it affects.
import random
a = raw_input("Enter text")
b = random.randrange(1,101)
print (a+b)
When I try to run the code, I get the error "TypeError: cannot concatenate 'str' and 'int' objects"
I want to know how to print the result of a+b.
To answer to the question in the title, you can convert an integer into a string with str. But the print function already applies str to its argument, in order to be able to print it.
Here, your problem comes from the fact that a is a string while b is an integer. The + operator works on two strings, or two ints, but not a combination of this two types. If you have two strings, the + will mean concatenate. If you have two ints, the + will mean add. It then depends on the result you want to get.
You can convert a string to an integer by using int.
Try this code:
import random
a = int (raw_input ("Enter int "))
b = random.randrange (1, 101)
print a + b