For statement does not repeated strings? - python

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)

Related

Commenting print() breaks the Python code

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.

use a variable inside input for python27 fails with syntax issues

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

Issue with in string operator in a module in python

When I use the operator in to compare strings in my program it works great but if I call it in a module I created it doesn't seem to work. I know I am making some error but not certain what it is, can anyone help?
Here is my code:
Module:
def checkRoots(wordChecked, rootList):
numRoots = len(rootList);
numTypeRoots = createList(numRoots);
for z in range(0, numRoots):
root = rootList[z];
rootThere = root in word;
if rootThere == True:
numTypeRoots[z] = numTypeRoots[z] + 1;
return numTypeRoots;
code works though when not in module as shown here:
for y in range (0, numRoots):
root = roots[y];
rootThere = root in word;
if rootThere == True:
numTypeRoots[y] = numTypeRoots[y] + 1;
Basic program takes a list of words in from a file and then looks to see if a particular root is in the word.
Thanks
The function is doing root in word but I think what you actually want to do is root in wordChecked
Global variables are the devil. best to avoid them if you can help it.
Suggestion - if writing Python code that other people might look at ( hint: probably any/all code) it's a good idea to read through and follow PEP-8

Syntax Error ncurses + python3

I've been trying to make my first program in Python 3 with Ncurses and I'm stuck trying to figure out this syntax error. I'm trying to build the ncurses menu topbar menu and I'm getting the following error;
s.refresh() c = s.getch()
^
SyntaxError: invalid syntax
I've been trying learn off from here http://www.ibm.com/developerworks/library/l-python6/#h3 but I cannot figure out why I'm getting syntax error with this. It happens with both Python 3.4.0 and Python 2.7.6 when I test it out. Also the menu's aren't rendering when I do go to test it out. I get nothing displaying at all. I'm just trying to make a simple program with very basic functions, nothing too special.
The problem is this piece of ncurses code when I try to add it to my own python script
def file_func():
s = curses.newwin(5,10,2,1)
s.box()
s.addstr(1,2, "I", hotkey_attr)
s.addstr(1,3, "nput", menu_attr)
s.addstr(2,2, "O", hotkey_attr)
s.addstr(2,3, "utput", menu_attr)
s.addstr(3,2, "T", hotkey_attr)
s.addstr(3,3, "ype", menu_attr)
s.addstr(1,2, "", hotkey_attr)
s.refresh() c = s.getch()
if c in (ord('I'), ord('i'), curses.KEY_ENTER, 10):
curses.echo()
s.erase()
screen.addstr(5,33, " "*43, curses.A_UNDERLINE)
cfg_dict['source'] = screen.getstr(5,33)
curses.noecho()
else:
curses.beep()
s.erase()
return CONTINUE
Here's what the current output looks like before trying to add the menu, before I got syntax error on the above code example at s.refresh() c = s.getch() line.
The is first time trying something like this in Python3 and Ncurses, I wanted to give it a go to see what I can do to make a simple functional program. ALso I'm not too sure how to customize the output more with Ncurses, I did want to change the colors and put a background fill to the boxed window it created, but not too sure on that, the tutorials I've read don't make it too clear on how to implement this into Python. Not too sure if I can just bundle it all into one script which is the main idea approach to this.
The problem is with this line:
s.refresh() c = s.getch()
You cannot place an assignment statement on the same line as a function call like you are doing. You need to use a semicolon to separate the lines:
s.refresh(); c = s.getch()
# ^
Note however that many Python programmers find the use of semicolons inelegant. It would be better to just use two lines:
s.refresh()
c = s.getch()

Long Int literal - Invalid Syntax?

The Python tutorial book I'm using is slightly outdated, but I've decided to continue using it with the latest version of Python to practice debugging. Sometimes there are a few things in the book's code that I learn have changed in the updated Python, and I'm not sure if this is one of them.
While fixing a program so that it can print longer factorial values, it uses a long int to solve the problem. The original code is as follows:
#factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = input("Please enter a whole number: ")
fact = 1
for factor in range(int(n), 0, -1):
fact = fact * factor
print("The factorial of ", n, " is ", fact)
main()
The long int version is as follows:
#factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = input("Please enter a whole number: ")
fact = 1L
for factor in range(int(n), 0, -1):
fact = fact * factor
print("The factorial of ", n, " is ", fact)
main()
But running the long int version of the program in the Python shell generates the following error:
>>> import factorial2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
import factorial2
File "C:\Python34\factorial2.py", line 7
fact = 1L
^
SyntaxError: invalid syntax
Just drop the L; all integers in Python 3 are long. What was long in Python 2 is now the standard int type in Python 3.
The original code doesn't have to use a long integer either; Python 2 switches to the long type transparently as needed anyway.
Note that all Python 2 support is shortly ending (no more updates after 2020/01/01), so at this point in time you'd be much better of switching tutorials and invest your time in learning Python 3. For beginner programmers I recommend Think Python, 2nd edition as it is fully updated for Python 3 and freely available online. Or pick any of the other Stack Overflow Python chatroom recommended books and tutorials
If you must stick to your current tutorial, you could install a Python 2.7 interpreter instead, and work your way through the book without having to learn how to port Python 2 to Python 3 code first. However, you'd then also have to learn how transition from Python 2 to Python 3 in addition.
You just need remove L
fact = 1
Python 3.X integers support unlimited size in contrast to Python 2.X that has a separate type for long integers.

Categories