Entering multiple lines / statements into the IDLE shell? - python

x=100
ENTER
if x == 10:
print("10!")
elif x == 20:
print("20!")
else:
print("I don't know!")
It prints I don't know! although it's more than one line?
What is the limit of the shell? What does "executed individually" mean - no matter how much code you write, it executes the first line / statement and ignores the rest?

A Python program is a sequence of statements. In IDLE's Shell, one enters and executes a single statement at a time. This is much more useful than entering a single physical line at a time, as with python.exe running in a Windows console or *nix Terminal. The text you quoted was talking about the latter, not IDLE.
To understand 'statement', we must start with 'line'. A physical line is "a sequence of characters terminated by an end-of-line sequence." A logical line can be two or more physical lines joined either explicitly using a \ character or implicitly using (), [], or {} pairs.
A simple statement comprises one logical line. A compound statement usually comprises multiple logical lines, each of which may be more than one physical line. Your if statement is an example of a compound statement.
In IDLE, one enters a complete statement on one or more physical lines. When a simple statement is complete (when one has entered a complete logical line), IDLE runs it. Since a compound statement can have an indefinite number of logical lines, one enters a blank line to indicate the end.

Related

Python: What Does This Syntax Error Mean? [duplicate]

I think this is perfectly valid.
if False:
print(1)
print(2)
However, it gives me an invalid syntax error in Python REPL.
Why is it?
On Python 3.6.5 (x64), Windows 10 RS4
As pointed out by user2357112, this behaviour is explained in https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming,
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The REPL can only read and evaluate one statement at a time.
You entered two statements at once.
This is possible because the REPL cannot decide if the third line is going to continue the if construction or start a whole new statement. It has to assume the former to allow indented blocks at all.
You have to make it clear to the REPL that your previous statement is finished before starting a new one.
Wrong version seems to be the most possible since, in the error it shows print. In the older python versions, print was used as print"ok", I see your operating system is windows so you can just directly download python3 from https://python.org/ have a nice day!

Reverse Tab in Python IDLE (3.7)

Is there a keyboard shortcut for reverse-tab in the Python IDLE?
I am trying to write an if-elif-else statement but cannot reverse-tab to properly indent the elif statement. I've tried shift+tab and shift+ctrl+tab.
For example, I can write this...
if x < 0:
print('Less than Zero')
but when I try to add the elif statement...
elif x == 0:
print('Zero')
I get the following error message:
SyntaxError: unindent does not match any outer indentation level
ctrl+[ de-indents highlighted code. ctrl+] indents.
You can see all the shortcuts if you look in the "Edit" menu at the top of the editor.
For reverse
ctrl+[
For Opposite
ctrl+]
Use the back space key to dedent. It is easiest if one does so before entering any code. If there is already code on the line, put the edit cursor between the end of the indent and the beginning of the code before hitting backspace. Note that in IDLE, one enters and edits, and submits complete statements for execution. Hence no secondary prompts. Example:
>>> a, x, y = 1, 2, 3 # Bind some names. This is one statement.
>>> if a: # When you hit return, IDLE see that you entered the header
# of a compound statement and indents the next line with a Tab.
# Note that I have to use 8 spaces here instead of a tab.
print(x) # When you hit return, IDLE keeps the same indent.
# Use Backspace [<--] to dedent back to the margin.
else: # Do not line up 'else' with 'if' by adding 4 spaces.
# Since this is another header, an indent is added on the next line.
print(y) # No header, indent kept the same.
# Hit Return to enter blank line
The final blank line signals that the compound statement is complete and should be executed. Until then, one can edit any part of the statement.
I am a bit stunned that 3 people would suggest the awkward and much harder workaround of selecting the line or at least the indent and using control-[. I am thinking about how to make the easy way more obvious.
I am aware that having 'if', 'elif', and 'else' not lined up is a nuisance. I intend to fix this.
What your doing is the shortcut on Spyder, but no, in idle, you have to do:
Ctrl+[
And the opposite would be:
Ctrl+]

Why am I getting an invalid syntax error in Python REPL right after IF statement?

I think this is perfectly valid.
if False:
print(1)
print(2)
However, it gives me an invalid syntax error in Python REPL.
Why is it?
On Python 3.6.5 (x64), Windows 10 RS4
As pointed out by user2357112, this behaviour is explained in https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming,
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The REPL can only read and evaluate one statement at a time.
You entered two statements at once.
This is possible because the REPL cannot decide if the third line is going to continue the if construction or start a whole new statement. It has to assume the former to allow indented blocks at all.
You have to make it clear to the REPL that your previous statement is finished before starting a new one.
Wrong version seems to be the most possible since, in the error it shows print. In the older python versions, print was used as print"ok", I see your operating system is windows so you can just directly download python3 from https://python.org/ have a nice day!

Dynamic single-line printing in Python (time?)

I'd like to make a simple clock (CLI) that prints the time into one line, and updates it every second. Is this even possible? Should I just print a new line every second?
This is what I have at the moment, which functions terribly:
import calendar, time
a = 1
while a == 1:
print (calendar.timegm(time.gmtime()))
If I understand, what you want to do is write the time, then, a second later, overwrite it with the new time, and so on.
On most terminals, printing a carriage return without a newline will take you back to the start of the same line. So, you can almost just do this:
print('\r{}'.format(calendar.timegm(time.gmtime())), end='')
In general, there's a problem with this: the carriage return doesn't erase the existing text, it just lets you overwrite it. So, what happens if the new value is shorter than the old one? Well, in your case, that isn't possible; you're printing a 10-digit number that can never turn into a 9-digit number. But if it were a problem, the easiest solution would be to change that {} to something like {<70}, which will pad a short line with spaces, up to 70 characters. (Of course if your lines could be longer than 70 character, or your terminal could be narrower than 70, don't use that number.)
Meanwhile, if you just do this over and over as fast as possible, you're wasting a lot of CPU and I/O, and possibly screwing up your terminal's scrollback buffer, and who knows what else. If you want to do this once per second, you should sleep for a second in between.
So:
while True:
print('\r{}'.format(calendar.timegm(time.gmtime())))
time.sleep(1)
If you want to get fancy, you can take over the whole terminal with curses on most non-Windows platforms, msvcrt console I/O on Windows, or even manually printing out terminal escape sequences. But you probably don't want to get fancy.
print function print newline (\n) after the string you passed. Specify carriage return (\r) explicitly does what you want.
To print every second, call time.sleep(1) after printing.
import calendar
import time
while 1:
print(calendar.timegm(time.gmtime()), end='\r')
time.sleep(1)
UPDATE
To make cursor remains at the end of the line, prepend \r:
print('\r', calendar.timegm(time.gmtime()), sep='', end='')

Indentation of an IF-ELSE block in Python

I am Python newbie and I am working on NLP using Python. I am having an error in writing an if-else block in Python. When I am writing only an if block at that time it is working fine:
if xyzzy.endswith('l'):
print xyzzy
After entering a colon (:) I am pressing Enter and it is automatically taking me to the correct indentation.
But when I am trying to add an else block to it after pressing the Enter key after the print statement, it is considering it to be statement of an IF block only, so it is giving me incorrect indentation as I want an else block after, while when I am trying to write else block my self it is giving me this error.
else:
^
IndentationError: unexpected indent
What should I do after writing print statement? Enter is clearly not working, because it is taking the cursor forward, while when I use space to come to the correct pointer it is giving me an error.
It's hard to see from your post what the problem is, but an if-else is formatted like so
if someCondition:
do_something # could be a single statement, or a series of statements
else:
do_something_else # could be a single statement, or a series of statements
I.e., the else needs to be at the same level as the corresponding if.
See this Python doc/tutorial on if, and this other tutorial too.
Sometimes when your editor does autoindent for you and you edit manually too things might get messed up, so you'll have to figure out how your editor handles indentations (e.g., is it always using tabs or spaces?, what happens if you hit return etc).
Also, be wary of mixing tabs and spaces, that will cause problems too (hard to spot since both are "invisible")
With your updated post:
if xyzzy.endswith('l'):
print xyzzy
else:
something_else
The else should be at the same level of indentation as the if with which it is coupled:
if x:
# Do something
else:
# Do something else
In your case,
if xyzzy.endswith('l'):
print xyzzy
else:
# Something else
Even if your editor is auto-indenting for you, you should still un-indent to make the code syntactically correct.
Getting the indentation correct isn't really a Python issue but rather an issue with the editor that you're using for your source code.
Most editors that understand Python will correctly add one level of indentation after a colon (as you're seeing). Because you can have as many statements as you want in that block of code, the editor has no way to know when to "outdent" the next line for the else.
You have to tell the editor to outdent that line by hitting backspace or Shift + Tab on the line before starting to type.
If you are inserting the else part after the rest of the code is written, make absolutely certain that the characters you use to indent are the same as for the if statement. If the if statement is indented with spaces, use the same number of spaces for else. If the if statement is indented with one or more tabs, use the same number of tabs for the else statement. Don't mix spaces and tabs for indentation.
Don't assume that just because the lines "look" as if they're indented the same that they are indented the same. One may use spaces and one may use tabs (or some combination).
when I use space to come to the correct pointer it is giving me a error
Of course. Using space never makes a "line break", typically this is \n in Unix systems. If you'd open your .py file in a different editor (say Notepad in Windows) you'd see that your else statement is in the same line as print.
Enter is clearly not working because it is taking the cursor forward
Press backspace the correct amount of times to reach the same level of indentation as your IF statement.
I don't agree entirely with the accepted answer. Yes, indention is very important in Python, but to state that the if-else has to always look like that with this formatting is a little bit overboard.
Python allows you a one-liners (even multiple) as long as you don't do anything fancy in there that requires indention in the body of the if, elif or else.
Here are some examples:
choice = 1
# if with one-liner
if choice == 1: print('This is choice 1')
# if-else with one-liners
if choice == 1: print('This is choice 1')
else: print('This is a choice other than 1')
# if-else if with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
# if-else if-else with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
else: print('This is a choice other than 1 and 2')
# Multiple simple statements on a single line have to be separated by a semicolumn (;) except for the last one on the line
if choice == 1: print('First statement'); print('Second statement'); print('Third statement')
Usually it is not recommended to pack too many statements on a single line because then you lose one of the big features of Python - readability of the code.
Notice also that the above examples can also easily be applied to for and while. You can go even further as to do some crazy nesting of one-liner if blocks if you use the ternary conditional operator.
Here is how the operator usually looks:
flag = True
print('Flag is set to %s' % ('AWESOME' if True else 'BORING'))
Basically, it creates a simple if-else statement. You can embed it with one of your one-liners if you need more branching (but not complex one).
I hope this clarifies the situation a bit and what is allowed and not allowed. ;)
I've been getting this error even when the indentation looked correct.
Viewing in Notepad++ there is an option to see white spaces and Tabs. The error was caused by mixing spaces and tabs to create indentation.
Replacing Tabs with spaces in every line helped to get rid of an error.
Actually, this is a Python IDLE UI issue: Once you hit Enter after the if block finishes, next the else statement is already in intent with the if statement. There isn't any need to provide any tabs or spaces to make indentation. Below is the image for reference.

Categories

Resources