I encountered a problem while programming in Python, and here's a bite of my program:
import random
p = raw_input('Percent Probability Program\nWhat percent?\n ')
r1 = random.randint(p, 100)
It gave me an error that the first value in the random command wasn't an integer. Please help!
Python 2
raw_input returns a str object, which is basically a string - no math operations can be performed on strings, and it's not the correct type for randint.
You can either convert your input to int using int(raw_input()) or just use the method input(), which returns an evaluated value (in your case, it should return an int)
Python 3
In python 3, the input function returns an str object, so converting it to int will be int(input())
Related
For example, I have a
String = "TGR1UK"
I only need the number 1 in the string to do some math operation so I make a number variable as
number = String[3]
but the type of this "number" is actually Char
and I cant use
number = (int)String[3]
to cast it into an integer
what should I do?
number = int(String[3])
This will cast it to an int. Read more here:
https://careerkarma.com/blog/python-string-to-int/
Edit:
I have assumed when you said:
but the type of this "number" is actually Char and I cant use
number = (int)String[3]
That you meant that wasnt working, because that is not how you cast to an int in python. Did you mean you aren't allowed to use a straight cast for some reason?
You're using int wrong. int is used as follows:
int(string)
So, try number = int(String[3]).
Small question: Why doesn't this piece of code work when I use int but does when I use eval?
int can only take one input? Is there a way to make it take multiple inputs as concise as using eval? Int is a stronger condition so that's why I am curious about how it would work.
a,b,c = int(input("enter numbers: "))
print(no_teen_sum(a,b,c))
This gives ValueError: invalid literal for int() with base 10, but the following code does work.
a,b,c = eval(input("enter numbers: "))
print(no_teen_sum(a,b,c))
int takes one input and possibly a base:
>>> int('46',7) # 46 is 34 in base 7
34
But you can use int along with map:
>>> map(int,['1','2','3'])
[1, 2, 3]
Use list comprehension:
def main():
numbers = input("enter numbers: ").split()
print(no_teen_sum(*[int(n) for n in numbers)])
main()
Python is trying to parse the whole string as one integer rather than three.
What you could do is:
a, b, c = map(int, input("enter numbers: ").split())
This way you are splitting the list into three strings, and then converting (mapping) each string to an int.
int can only take one input?
Yes, and that is technically true for eval, too. It's just that eval might return something other than an int. In your case, I'm assuming you enter something like 1, 2, 3 on the input prompt. eval simply parses that as a tuple, which it returns, and unpacks into your three variables.
You can, however, easily achieve something similar to what you want using list comprehension:
a, b, c = [int(x.strip()) for x in input("Enter numbers: ").split(",")]
This has the added benefit that you don't risk having some completely unexpected type returned from eval.
One caveat with using eval that should perhaps be worth noting is that it accepts any valid Python syntax and executes the parsed result, which may include arbitrary function calls, including code to erase your hard drive. Not much of a problem when you're just writing a program for yourself to use, but just so that you know.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:
I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is 3, the code would be:
print(*range(1, 3+1), sep="")
which obviously works, however when using an n = input() , no matter where I put the str(), I get the same error:
"Can't convert 'int' object to str implicitly"
I feel sorry to waste your collective time on such an annoyingly trivial task..
My code:
n= input()
print(*range(1, n+1), sep="")
I've also tried list comprehensions (my ultimate goal is to have this all on one line):
[print(*range(1,n+1),sep="") | n = input() ]
I know this is not proper syntax, how on earth am I supposed to word this properly?
This didn't help, ditto this, ditto this, I give up --> ask S.O.
I see no reason why you would use str here, you should use int; the value returned from input is of type str and you need to transform it.
A one-liner could look like this:
print(*range(1, int(input()) + 1), sep=' ')
Where input is wrapped in int to transform the str returned to an int and supply it as an argument to range.
As an addendum, your error here is caused by n + 1 in your range call where n is still an str; Python won't implicitly transform the value held by n to an int and perform the operation; it'll complain:
n = '1'
n + 1
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1
TypeError: Can't convert 'int' object to str implicitly
That's why you need to be explicit and wrap it in int(). Additionally, take note that the one liner will fail with input that can't be transformed to an int, you need to wrap it in a try-except statement to handle that if needed.
In your code, you should just be able to do:
n = int(input())
print(*range(1,n+1),sep="")
But you would also want to have some error checking to ensure that a number is actually entered into the prompt.
A one-liner that works:
print(*range(1, int(input()) + 1), sep="")
So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get...
ValueError: could not convert string to float
I don't know what the problem is, I've tried using raw_input but it doesn't work ether. Please keep in mind I'm green and am not aware of most methods for getting around a problem like this
num1 = float(input ()) #take a float and store it
chars = input () #take a string and store it
num2 = float(input ())
your code only convert string that are integers like in below statement
num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0
if you provide 13 as a input it will give the output as 13.0
but if you provide SOMEONEE as input it will give ValueError
And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function
I think this is happening because in some cases 'input' contains non-numerical characters. Python is smart and when a string only contains numbers, it can be converted from string to float. When the string contains non-numerical characters, it is not possible for Python to convert it to a float.
You could fix this a few ways:
Find out why and when there are non-numerical characters in your input and then fix it.
Check if input contains numbers only with: isdecimal()
Use a try/except
isdecimal() example:
my_input = raw_input()
if my_input.isdecimal():
print("Ok, go ahead its all numbers")
UPDATE:
Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer.
I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.
Code:
import sys
a = sys.argv[1]
b = sys.argv[2]
print a, b
print a+b
Input:
python mySum.py 100 200
Output:
100 200
100200
When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.
How can I interpret them as numerics?
You can convert the arguments to integers using int()
import sys
a = int(sys.argv[1]) b = int(sys.argv[2])
print a, b
print a+b
input: python mySum.py 100 200
output:
100 200
300
You also should validate the user input:
import sys
def is_intstring(s):
try:
int(s)
return True
except ValueError:
return False
for arg in sys.argv[1:]:
if not is_intstring(arg):
sys.exit("All arguments must be integers. Exit.")
numbers = [int(arg) for arg in sys.argv[1:]]
sum = sum(numbers)
print "The sum of arguments is %s" % sum
Indeed, you have found the problem yourself, sys.argv is an array of strings.
You can transform a string to an integer with int(). In this case for example: a = int(sys.argv[1])
sys.argv items are always strings. you should cast them to int with int(a).
You can also use third party libraries for handling CLI arguments such as OptParse.
In Python, strings are not implicitly converted to integers.
Try
num1 = int(sys.argv[1])
This would represent the numerical value of the number, not its string representation.
Beware of performing comparisons involving command-line arguments, which can lead to really unexpected behavior owing to Python 2's policy for comparing objects of different types ('int' < 'list' < 'string' < 'tuple') as noted here. In Python 3, comparing objects of different types will lead to a TypeError.
For an example of object comparison mayhem, try removing the int() call in section 6.1.1. of the Python tutorial Fibonacci code and you'll get an infinite loop, since the while loop condition becomes: 'int' < 'string'. (This would not happen in Perl, btw).
Great advice from #Jan-Philip above to validate command-line arguments, even for Python 3.