invalid literal for int() with base 10: '1.0' [duplicate] - python-3.x

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed last month.
I wrote a program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 I get the error:
ValueError: invalid literal for int () with base 10.
Any suggestions?
Here's the traceback:
Traceback (most recent call last):
File "C:\Users\kasutaja\Desktop\EksponentfunktsioonTEST - koopia.py", line 13, in <module>
if int(a) < 0:
ValueError: invalid literal for int() with base 10: '0.3'
The problem arises every time I put a number that is smaller than one, but larger than 0. For this example it was 0.3 .
This is my code:
# y = a^x
import time
import math
import sys
import os
import subprocess
import matplotlib.pyplot as plt
print ("y = a^x")
print ("")
a = input ("Enter 'a' ")
print ("")
if int(a) < 0:
print ("'a' is negative, no solution")
elif int(a) == 1:
print ("'a' is equal with 1, no solution")
else:
fig = plt.figure ()
x = [-2,-1.75,-1.5,-1.25,-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
ax = fig.add_subplot(1,1,1)
ax.set_title('y = a**x')
ax.plot(x,y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.savefig("graph.png")
subprocess.Popen('explorer "C:\\Users\\kasutaja\\desktop\\graph.png"')
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Restart program? ")
if answer.strip() in "YES yes Yes y Y".split():
restart_program()
else:
os.remove("C:\\Users\\kasutaja\\desktop\\graph.png")

Answer:
Your traceback is telling you that int() takes integers, you are trying to give a decimal, so you need to use float():
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (ℤ), and floating point numbers, which store real numbers (ℝ). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Previous guess at answer before we had the traceback:
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the - and 1 will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
Advice on code style:
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a) a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x, you don't need to do anything to y, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.

As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:
With Python2, int(str(5/2)) gives you 2.
With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'
If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:
int(float(myStr))
As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.

It might be better to validate a right when it is input.
try:
a = int(input("Enter 'a' "))
except ValueError:
print('PLease input a valid integer')
This either casts a to an int so you can be assured that it is an integer for all later uses or it handles the exception and alerts the user

int() casting can't handle string numbers that have decimal points
- example --> int('13.5') will give you error , but int('13') will convert the
string to integer
Why : This considered as explicit casting required by the user as it prevents you from losing information like 0.5 if you read dataset and don't know it's had floating-point numbers
Work Around >
int(Float("13.5"))
A real-world example I faced: where I wanted the numbers as int while int(I["mpg"]) directly didn't work so I used float() then int()
sum([int(float(i["mpg"])) for i in file])//len(file)

Related

Unable to resolve Can't convert 'int' object to str implicitly

I am trying to solve this problem where certain numbers are taken and appended into the list.
After that I want to see that the first element is smaller than the next element if yes then remove it from the list.
But during comparison it is throwing this error.
I am new to python and don't know how to resolve this
I've tried to take the input in a different way but still can't solve it.
n=int(input())
l = []
m=input().split()
l.append(m)
print(m)
for i in m:
j=i+1
if i<j:
m.remove(i)
print(m)
It is showing the given error:
Traceback (most recent call last):
File "main.py", line 7, in <module>
j=i+1
TypeError: Can't convert 'int' object to str implicitly
Without knowing your input, I can tell you that the elements of m are strings. The return type of input() is a string and you've created a list of strings in m. You can do j = int(i) + 1 to make that line of code work, but you'll have a lot more work to do to solve your overall problem. i<j will always evaluate to True given the above line.
m = input().split() returns an iterable of strings, split by whitespace. If these are supposed to be integers, you've got to cast it to an integer. Do:
n=int(input())
l = []
m=input().split()
l.append(m)
print(m)
for i in m:
j=int(i)+1 # i is cast to an integer
if i<j:
m.remove(i)
print(m)

Python Middle String Print

I am relatively new to python and I have to create a program that prints the middle character of a user-inputted string. Here is what I have:
#accept string from user then print middle character
x = input("Enter a string: ")
print(x[len(x)/2-1])
However I keep getting this error when I try to run the program:
"TypeError: string indices must be integers".
Im not sure how to fix this or how to get this program to work. Please help!
From your error I infer that you are using python 3.
In python 3 division between two integers returns a float:
>>> 3/2
1.5
>>> 4/2
2.0
But a indeces must be integers, so you get the error. To force an integer division you must use the // operator:
>>> 3//2
1
>>> 4//2
2
Alternatively you can use math.ceil or math.floor if you want more control on the rounding of the floats.
This is a way:
x = raw_input("Enter a string: " )
print (x[:len(x)//2])

Simultaneous assignment in python 3.3

I am a newbie at python programming.I am referring to a book "Python Programming: An Introduction to Computer Science." Which is oriented to python 2.Since I cannot lay my hands upon a basic book oriented to python 3, I am facing a syntax problem depicted below
>>> def f():
x,y=input("enter two numbers seperated by a comma: ")
s=x+y
d=x-y
print (s,d)
f()
The result i got was
>>> f()
enter two numbers seperated by a comma: 2,3
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
f()
File "<pyshell#9>", line 2, in f
x,y=input("enter two numbers seperated by a comma: ")
ValueError: too many values to unpack (expected 2)
I tried to find the solution in some books like dive into python 3 and core python programming, but i think that they are way too high level for me right now.Please help.
"input" returns only one value at the time, so you can't really assign it for two variables. If you expect two values you may want to split string by space or any other convenient separator.
>>> x,y = map(int, input("Enter x and y separated by comma: ").split(',', 1))
Enter x and y separated by comma: 1, 2
>>> x
1
>>> y
2
split(var, 1) - make sure you split string only once into two pieces.
map(int...) - convert each string piece value into integer.
The input function returns one str (in Python 3), which won't be automatically split into two variables. You need to do something like:
x, y = input('enter two numbers separated by a comma:').split(',')

When to use ast.literal_eval

I came across this code and it works, but I am not entirely sure about when to use ast and whether there are performance issues when this is used instead of getting the string value from input() and converting it to int.
import ast
cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
# this get the user input as an int to the variable cyper_key
I read the docs I understand what it does.
This can be used for safely evaluating strings containing Python
values from untrusted sources without the need to parse the values
oneself. It is not capable of evaluating arbitrarily complex
expressions, for example involving operators or indexing.
I am looking for an explanation on above bold points.
When to use it.
ast.literal_eval(input()) would be useful if you expected a list (or something similar) by the user. For example '[1,2]' would be converted to [1,2].
If the user is supposed to provide a number ast.literal_eval(input()) can be replaced with float(input()), or int(input()) if an integer is expected.
Performance
Note that premature [micro-]optimization is the root of all evil. But since you asked:
To test the speed of ast.literal_eval(input()) and float(input() you can use timeit.
Timing will vary based on the input given by the user.
Ints and floats are valid input, while anything else would be invalid. Giving 50% ints, 40% floats and 10% random as input, float(input()) is x12 faster.
With 10%, 10%, 80% and float(input()) is x6 faster.
import timeit as tt
lst_size = 10**5
# Set the percentages of input tried by user.
percentages = {'ints': .10,
'floats': .10,
'strings': .80}
assert 1 - sum(percentages.values()) < 0.00000001
ints_floats_strings = {k: int(v*lst_size) for k, v in percentages.items()}
setup = """
import ast
def f(x):
try:
float(x)
except:
pass
def g(x):
try:
ast.literal_eval(x)
except:
pass
l = [str(i) for i in range({ints})]
l += [str(float(i)) for i in range({floats})]
l += [']9' for _ in range({strings}//2)] + ['a' for _ in range({strings}//2)]
""".format(**ints_floats_strings)
stmt1 = """
for i in l:
f(i)
"""
stmt2 = """
for i in l:
g(i)
"""
reps = 10**1
t1 = tt.timeit(stmt1, setup, number=reps)
t2 = tt.timeit(stmt2, setup, number=reps)
print(t1)
print(t2)
print(t2/t1)
ast -> Abstract Syntax Trees
ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
This link AST is useful for you to understand ast.
If it's going to be used as an int, then just use:
cypher_key = int(input("Enter the key (a value between 0 and 25) : "))
Only use that if you expect the user to be entering 10e7 or something. If you want to handle different bases, you can use int(input(...), 0) to automatically divine the base. If it really is an integer value between 0 and 25, there's no reason to use ast.
Running this in a python-3.x shell, I get no differences when I give correct input:
>>> cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
Enter the key (a value between 0 and 25) : 5
>>> cyper_key
5
However, when you give a string or something that cannot be converted, the error can be confusing and/or misleading:
>>> cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
Enter the key (a value between 0 and 25) : foo
Traceback (most recent call last):
File "python", line 3, in <module>
ValueError: malformed node or string: <_ast.Name object at 0x136c968>
However, this can be useful if you don't want to cast either float or int to your input, which may lead to ValueErrors for your int or floating points for your float.
Thus, I see no necessary use in using ast to parse your input, but it can work as an alternate.

Python: How do I get this function to print?

#integers to be input
n = input('Enter \"n\" trials')
x = input('Enter \"x\" number of succeses')
p = input('Enter the probability \"p\" of success on a single trial')
#Probability Distribution function
def probDist(n, x, p):
q = (1-p)**(n-x)
numerator = math.factorial(n);
denominator = math.factorial(x)* math.factorial(n-x);
C = numerator / denominator;
answer = C*p**x*q;
return answer
# Does this have to come after I define the function? Or does this matter in Python
# Also this part just doesn't work.
dist = probDist(n, x, p);
print(dist);
Here's the error that I get after I run and I input all the values.
Traceback (most recent call last):
line 17, in <module>
dist = probDist(n, x, p);
line 9, in probDist
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
In Python 3.x, input always returns a string, without applying eval the the user input. Python 2.x input does eval, but that's rarely what you want. If you want an integer, use int(input(...)) and if you want a float (not quite the same as a real number, as it has only limited range!), use float(input). (You should propably catch ValueError to handle the cases where the input is not appropiate; if this is for exercise/education, it's propably okay to leave error handling out for now.)
Does this have to come after I define the function?
Yes.
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
You have two - operations. One of those two is a mixture of int and str data.
Let's go through each operand.
1 - int
p - result of input(), and therefore a string
n - result of input(), and therefore a string
x - result of input(), and therefore a string
You probably want to do something to convert the results of input() to a proper floating-point value. float() works well for this.

Resources