In IDLE, say i want to write the following in TWO lines:
x = 3
print x**5
but when i type x = 3 and press enter, it executes the assignment. How to let it execute AFTER two lines are all typed in?
having read first pages of Python tutorial but no answer to this "funny" question...
Use the Ctrl-J key sequence instead of the Enter key to get a plain newline plus indentation without having IDLE start interpreting your code.
You can find other key sequences that make IDLE easier to use for this type of learning under the Options->Configure IDLE menu.
End lines with ;\:
>>> x=3;\
... print x**5
243
>>>
after every line put \ mark and press enter
To code group of statements, ;\ will work
list1=[1,2,3]
list2=[4,5,6]
print list1;\
print list2
Will print both the lists
Where as, for Indentation statement, you need :\
for i in list1:\
print i
//double enter
Will show all the elements in the list
x = 3; print x ** 5
should help, but it doesnt matter that its executed the way it is in IDLE.
Just open a new file: File > New window. You can run it by clicking run > run module.
the "\" line at the end of the line works for me. in windows 10 cmd.
Edit: I've also noticed that you have to be consistent with its use, other wise you still get syntax error
Ctrl + Enter enters a new line in Spyder IDE
Related
I'm trying to familiarize myself with IDLE by executing the following code from Automate the Boring Stuff with Python by Al Sweigart:
name = ""
while name != "Mark":
print("What is your name?")
name = input();
print("Thank you")
Syntax Error
For some reason though, I get a syntax error when trying to type the last print statement. I dont know how to get around the indentation / how to be able to type again OUTSIDE of the loop. I understand that only one block of code is executed at a time but I can't seem to be able to incorporate the final print statement. Does anybody know how I can get around this? Thank you very much
In IDLE, put an empty, unindented line after entering this line:
name = input();
Press enter again to make the extra blank line to exit that indented block and your loop should execute after that.
Actually, your solution might be very simple.
name = input();
You don't need the ending semi-colon in Python, remove it so the line is just:
name = input()
I've just learnt that to clear a line that you printed in Python, do this:
sys.stdout.write('\x1b[2K')
Why is it so complicated? what does that weird code mean? and is there any alternative in print command?
Print does offer "end" option that allows to go back and forth in lines, but no way to clear what you printed. Overwriting via \r doesn't always work especially if the new line is shorter than the old one. You will get traces from the old line, so I need clearing first.
Thanks.
\x1b[2K is what's known as an ANSI terminal control sequence. They are a legacy of the 1970s and still used today (but vastly extended) to control terminal emulators.
\x1b is the ASCII for ESCAPE (literally the ESC key on your keyboard). [2K is the command "erase the current line".
There are many libraries in Python for working with the terminal, such as Urwid. These libraries will hide the inner workings of the terminal from you and give you higher-level constructs to create TUIs.
However, there is a much more efficient way of doing this:
You can use the print() command as usual, and delete the screen using
os.system("cls") # For Windows
or
os.system("clear") # For Linux
Alternative to print on a single line
I have a script that prints the x, y coordinates of the mouse as such:
import pyautogui
import time
while True:
x, y = pyautogui.position()
position_string = "X: {} Y: {}".format(str(x).rjust(4), str(y).rjust(4))
print(position_string, end='')
print('\b' * len(position_string), end='', flush=True)
time.sleep(1)
Where I will point out that you can print the backspace character ('\b') the amount of times that there are characters on the screen (len(position_string)), and when used with the end='' and flush=True options this will constantly print on a single line within your console. I should also note that this does not work in IDLE, but only on an actual command line! In IDLE the backspace characters are actually printed as some weird square shape...
This is called ANSI escape code . 2K is the name for Erase in Line. Quote from the link:
Erases part of the line. If n is 0 (or missing), clear from cursor to the end of the line. If n is 1, clear from cursor to beginning of the line. If n is 2, clear entire line. Cursor position does not change.
You can also try echo -e '\x1b[2k' in the terminal for better understanding.
I have a simple question today. Basically, I want to print 2 or more lines of output in the CMD shell with python. Here is an example:
Regular CMD Shell:
Output
What I want:
Output
Output1
Ect.
I'm using Python 3.x fyi. I don't even know if this is possible with typical Python libraries, thanks for your answers!
Edit: Due to confusion, I've dedcided to write more in detail. I'd like to have 2 or more live outputs while a loop or something of the matter is running. So, for example, if I was running a clock in a while True loop, I could use the carriage return function and have 2 outputs running.
Edit #2: So I'm going to give you guys a situation in which I would need an answer to this question. Basically, I made a loop that displays the current time and the time until 7:30 pm to the CMD shell using a return so it all stays neatly on one line. However, I need it so instead of me printing all the information I need on 1 line, it does it on 2. Here is the output:
Time: 12:44:38 Time Left Until 7:30: 6:45:22
What I want it to be:
Time: 12:44:38
Time Left Until 7:30: 6:45:22
Here is my code:
import datetime
import time
import sys
while True:
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
end_time = ('19:30:00')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print ('Time: ', start_time, 'Time Left Until 7:30: ', total_time, end='\r')
time.sleep(0.1)
When I try to print anything below the carriage return, it doesn't print and when I put the carriage return in the second print, the original loop prints down and not in one line. Thanks again!
If cls command blinks, you can use ANSI commands to control. First you have to enable ANSI in the windows cmd. You can use a 3rd party library such as colorama to do that.
Once you've enabled ANSI, you can use it to move up a line and delete a line (and also add nice colors 😉).
colorama.init() # don't forget to call
Up a line: sys.stout.write('\033[1A')
Delete current line: sys.stout.write(' \r\033[K')
You can refresh the cmd window by calling os.system('cls'). This will clear the screen and allow you to print your updated output.
name = input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
It says multiple statements found while compiling a single statement
I'm using a book and tried many different things. Also, I'm a noob at this as you can tell. If you have any suggestions that'll be great
Your code is fine, assuming you are using python 3, but you need to type (or paste) each line, one at a time. Based on what you are seeing, I suspect you are putting it all in at once, without a new line after each line.
If you are using python 2, you'll need to use raw_input rather than input, like this:
name = raw_input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
So couple of things:
print("name") will not print the name you captured from the last variable but a string that says name
print("Hi,", name) prints ('Hi,', 'Dmitry') which is probably not what you want, instead do this: ', '.join(["Hi", name]) There are probably other Python 3 conventions but I work in Python 2 so I don't know them all off the top of my head.
input("\n\nPress the enter key to exit.") not sure of the purpose of this line. Seems like a stray line from a block of code and it's not being assigned to any variable. Furthermore it throws an error SyntaxError. What book are you using if I may ask?
You can check the Python version in the HELP>about IDLE tab of IDLE editor or Shell - you seem to be using python 2 as others have stated
If you are able to enter and run one line of code at a time, followed by the next line then you are using the Shell, not the IDLE editor
You should be able to paste the code you have in question into IDLE editor and run (F5) - you should be prompted to save before it is run in the Shell.
This question already has answers here:
Python, writing multi line code in IDLE
(7 answers)
Closed 6 years ago.
I just picked up a basic book today on programming. The coding language is Python and I have only been trying this out for a few hours but I'm already stuck, because I can't figure out how to write multiple lines of code. For example, when I write print("one") and then hit enter, it just runs it and prints the word, one. How can I have it print the word, one, and then the word, two, on the line below it? Also, when I hit tab it just moves over 4 spaces, or so. I can't figure out how to have it not run the first command, and just give me '>>>' on the next line. So I guess what I'm asking is: What keystrokes do I need to use to get something like:
>>> print("one")
>>> print("two")
Thanks so much!
(Sorry for such a basic question, but I'm totally confused on this one.)
The Python REPL automatically executes each command as soon as it is completely typed in. This is why it is called a "read-eval-print loop". It accepts one input, evaluates it, and then prints the result.
If you want to execute two complete commands at once, you can put a semicolon between them, like this:
print("one"); print("two")
I said "completely typed in" above, because some commands inherently require multiple lines, so Python must accept several lines of input before the command is "completely typed in". Three types of command work like this: flow-control commands (def, while, if, for, etc., which apply to several indented lines below them), multiline expressions (calculations inside parentheses or brackets), or statements that use a backslash (\) at the end of the line to indicate that it is continued on the next line. So if you type in any of the blocks below, Python will wait until the block is completely finished before evaluating it.
if 1 + 1 == 2:
print "True"
else:
print "False"
print(
1 + 1
)
print \
1 + 1
You could also combine these two strategies and type something like this:
print("one"); \
print("two")
Python will wait for both commands to be typed and then run them both at once. But I've never seen anyone write code that way.
Alternatively, you could type several commands together in a different text editor, and then paste them into the Python REPL, e.g., copy and paste the following into your REPL (but you will get results printed between the commands):
print("one")
print("two")
Alternatively, you can probably get almost exactly the behavior you were originally expecting by using a different interface to Python. The IPython Notebook is a good choice, or you could try the Spyder or PyCharm editors, which let you select a few lines of code and run them.
Or, if you have a longer script that you want to run all at once, the best option is to type it up in a text file (e.g., script.py), and then tell python to run it, e.g., type python script.py from a system command prompt (not the Python interpreter), or press F5 in the IDLE editor.
One thing you may want to try is writing your code in a file, say learning.py, and then running that file on the command line with python learning.py.
The best way to get better support for multi line commands in python with a "console" feel is to use ipython qtconsole, or Jupyter qtconsole as its now called: http://jupyter.org/qtconsole/stable/. When using qtconsole, hitting Ctrl-Enter will delay the command from running even if it's not a complex block. You can keep hitting Ctrl-Enter as many times as you want, and then hit Enter to run them all. Hitting up arrow will then bring up the whole block again to edit, cleanly indented unlike the regular ipython console.
Note: this is not ipython notebook, nor the regular ipython console, but a separate thing from either using the same kernel. The qtconsole has some other nice things like better syntax highlighting and inline plotting compared to the terminal.