I have the following code which works both in py 27 and 36 :
all_config_msgs = ['Okta App URL. E.g https://acme.okta.com/home/amazon_aws/b07384d113edec49eaa6/123: ','Organization username. E.g jane.doe#acme.com: ']
config_details = []
for config_msg in all_config_msgs:
config_details.append(input(config_msg))
In py 36 and 27, I get input prompt :
Okta App URL. E.g https://acme.okta.com/home/amazon_aws/b07384d113edec49eaa6/123:
in py 36, I put :
any_reply
and it takes it successfully
in py 27, I put :
any_reply
which fails with
config_details.append(input(config_msg))
File "<string>", line 1
https://acme.okta.com/home/amazon_aws/b07384d113edec49eaa6/123
^
SyntaxError: invalid syntax
FYI - In py 27 it works if I put the response as "any_reply"
but I need to have a way of answering without the double quotes/quotes.
I understand in py 27, input is doing an eval but what is a good way to have the input prompt as a variable without getting the above error.
On Python 2.7 you should use raw_input instead.
If you want to support multiple version of Python you can make your own function that will work on both Python 2 and 3:
def my_input():
try:
return raw_input()
except NameError:
return input()
You can also take advantage of six library that can help you a lot with compatibility issues:
from six.move import input
That will use raw_input in Python 2 and input in Python 3.
Denis' answer is correct. You can conditionally use the function. This is an incredibly common pattern in Python, especially when you're concerned with cross-version compatibility.
try:
my_input = raw_input
except NameError:
my_input = input
all_config_msgs = ['Okta App URL. E.g https://acme.okta.com/home/amazon_aws/b07384d113edec49eaa6/123: ','Organization username. E.g jane.doe#acme.com: ']
config_details = []
for config_msg in all_config_msgs:
config_details.append(my_input(config_msg))
Tested and working in Python 2.7 and 3.5, but it will work as well for your versions.
Another option that is a bit contested, because some people get all weird about changing global names, is to just enforce that raw_input exists, or define it:
try:
_ = raw_input
except NameError:
raw_input = input
you can use
six library for resolving compatibility issues
Related
I was faced with a very strange problem.
With print() this code works.
def max_pairwise_product(numbers):
max_1 = max(numbers)
numbers.remove(max_1)
max_2 = max(numbers)
return max_1 * max_2
if __name__ == '__main__':
input_n = int(input())
print() # <- comment of this line breaks the code
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
If I comment or delete the 10-th line with print() I got an error:
Traceback (most recent call last):
File "C:\Users\...\maximum_pairwise_product_fast.py", line 12, in <module>
print(max_pairwise_product(input_numbers))
File "C:\Users\...\maximum_pairwise_product_fast.py", line 2, in max_pairwise_product
max_1 = max(numbers)
ValueError: max() arg is an empty sequence*
Process finished with exit code 1
I use Python 3.9. PyCharm.
I tried to launch with different virtual environments with Python 3.8 and 3.10 – the same error.
When I launch in Jupyter and Colab – it is fane – no error.
There are no issues with any other Python script. I used the installation for several months and there was nothing strange.
It is so strange that I have no idea. Could you please help me?
Try checking if your python interpreter is working correctly and is the latest python
It might fix it or there's probably a problem with your ide.
Thank you all for helping to refer me in the right direction.
The reason for the error was a bug in PyCharm. It sent not was typed. The issue disappeared after the PyCharm update from version 2022.1.1 to 2022.1.2.
Back in 2018 or so, I found a similar strange issue in a Python program I downloaded that solved Rubik's cubes. Basically, the program ran just fine under Linux, but under Windows it was erroring out at a certain line that looked fine.
I ran "pyflakes" on that program, but pyflakes reported that nothing was wrong. Odd.
The line that supposedly contained the error was a list comprehension, much like your line here:
input_numbers = [int(x) for x in input().split()]
I replaced the list comprehension with a normal for-loop, and then the code ran fine with no errors. Basically, if I were to rewrite your line, I would replace it with the following four lines:
input_numbers = []
for x in input().split():
input_numbers.append(int(x))
assert input_numbers, "input_numbers is empty!"
I have no idea why the error was happening in the first place, and only on Windows. (The version of Python3 I was using certainly supported list comprehensions; I checked.) But once I replaced the list comprehensions with a for-loop, the code worked.
So my advice is to replace your list-comprehension with a for-loop and see if that solves anything.
I don't know if that will work, but it's worth a shot, as it seems that your input_numbers list is not actually being populated before it's passed to max_pairwise_product().
You might even try putting the assert statement:
assert input_numbers, "input_numbers is empty!"
after the list comprehension to verify that input_numbers is truly being populated. If it's not, then you at least have narrowed down your problem, and will now have to figure out why it's not being populated.
P.S. I'm curious: Which operating system(s) does the error happen on?
P.P.S. I recommend adding input text to your input() calls (such as input("Type some space-separated numbers: "), even if just for posting here. Otherwise, when stackoverflow users run your code, it looks like your code is hanging.
Here is code
equation1 = input("Please Enter an equation")
a = float(input("For a = "))
c = eval(equation1)
When I am typing equation with cos, tan, sin and ln functions; i.e : a*cos(a)
I am getting this error:
c = eval(equation1)
File "<string>", line 1, in <module>
TypeError: cos() takes exactly one argument (0 given)
and inputs like a*cos(90), a**2+cos(90) are working fine, my application is build to be generic. user can give any value is there any way to fix it?
First it needs to have from math import cos.
When I run with PyCharm, I get the same exception as you.
Then I added print(equation1) and found that when I typed cos(a), printed cos().
At first I thought there was something wrong with the input function, but I couldn't find the reason.
Then I ran it directly from the terminal command line using python xx.py and it worked fine.
So it may be that the PyCharm window does not recognize the contents of the parentheses.
I'm currently working on my homework and the first line code is provided and cannot be changed. I am able to run in PyCharm but not able to run in Hackerrank to submit my homework.
I have tried to find what's wrong with my code but I think the problem is related to input. I think teacher wants us to use input as variable?
def check_character_type(input):
# Write your code
ch = input
if ch[0].isalpha():
print("alphabet")
elif ch[0].isdigit():
print("digit")
else:
print("special")
return ch
check_character_type(input)
When I run the code in Hackerrank, error message are
Traceback (most recent call last):
File "Solution.py", line 29, in <module>
check_character_type(input)
File "Solution.py", line 21, in check_character_type
if ch[0].isalpha():
TypeError: 'builtin_function_or_method' object is not subscriptable
your issue as mentioned in the last answer and comments it that you are using the function named input as the name of your variable...try it like this:
inp = 'test'
def check_character_type(inp):
# Write your code
ch = inp
if ch[0].isalpha():
print("alphabet")
elif ch[0].isdigit():
print("digit")
else:
print("special")
return ch
check_character_type(inp)
output:
alphabet
'test'
if by "I think teacher wants us to use input as variable" you mean that you're supposed to provide input before hand, then do this first:
inp = input('Enter the input')
The issue here is you have named the parameter to your function input, which is a reserved function provided by Python used to read input from the STDIN. You then alias this to ch and attempt to subscript it, effectively trying to access an index of a function (which you can't).
The solution would be to change your parameter name from input to something like in or s instead, something that isn't a reserved keyword.
I use a software library that has different function names in different versions of the library.
I try to use the following code:
some_variable = module.old_name_of_function()
But this code only works with the old version of the program library.
I plan to use the code on different computers, with different installed versions of the software library.
Some computers have a new version of the program library installed, and the following code should be used there:
some_variable = module.new_name_of_function()
And if I use old_name_of_function() in the new version of the library, I will get an error.
How to solve this issue?
I suppose you could do
try:
my_func = module.old_name_of_function
except AttributeError:
my_func = module.new_name_of_function
some_variable = my_func()
You can use pkg_resources module for it (example for numpy):
import pkg_resources
pkg_resources.get_distribution("numpy").version
will return:
'1.15.2'
Then you can use cases, ifs or something else to run a function you need.
For example:
import pkg_resources
version = pkg_resources.get_distribution("numpy").version
v = version.split('.')
if int(v[0]) == 1 and int(v[1]) < 17:
print('WAKA')
else:
print('NEW WAKA')
will print 'WAKA' for every 1.X version of numpy, where X < 17.
I what the user input to be repeated 10 times but I get an error.
no = input(' any thing typed there will x10')
for i in range(10):
print(no)
But if I change the code to int or something else it works .
no = int (input(' any thing typed there will x10'))
for i in range(10):
print(no)
I am probably missing something basic ,but thanks in advance.
I used an app called QPython on my android which might be the problem
What you have written is valid Python 3, but not valid Python 2. I suspect you are running Python 2, given the question. Python changed how the input function works between Python 3 and Python 2. But given your issue, this will fix the issue for Python 2 users (you):
no = raw_input(' any thing typed there will x10')
for i in range(10):
print(no)