Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, writing multi line code in IDLE

How do i write

   >>> x = int(raw_input("Please enter an integer: "))
    >>> if x < 0:
    ...      x = 0
    ...      print 'Negative changed to zero'
    ... elif x == 0:
    ...      print 'Zero'
    ... elif x == 1:
    ...      print 'Single'
    ... else:
    ...      print 'More'
    ...

this in IDLE. As soon as I hit enter after writting first line, it executes the first line and i am not able to write full code. I am very new to python, just started it today. Any help will be appreciated.

like image 748
Himanshu.MarJAVA Avatar asked May 02 '12 12:05

Himanshu.MarJAVA


People also ask

How do you write multiple lines in IDLE Python?

Add a trailing backslash ( \ ) If you write a \ , Python will prompt you with ... (continuation lines) to enter code in the next line, so to say.

How do I type multiple lines in IDLE?

Shift + Enter takes you to next line without executing the current line. Save this answer.

How do you write multiple lines of code in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

How do you go to the next line in IDLE Python?

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.


4 Answers

Using the exec function along with multi-line strings (""") worked well for my particular use case:

exec("""for foo in bar:
  try:
    something()
  except:
    print('Failed')"""
like image 107
joe Avatar answered Oct 24 '22 11:10

joe


Shift + Enter takes you to next line without executing the current line.

like image 38
Jayanth Reddy Avatar answered Oct 24 '22 11:10

Jayanth Reddy


1: Use semicolons between lines
2: Try iPython
3: Write it as a function, e.g.

def myfunc():
    x = int(raw_input("Please enter an integer: "))
    if x < 0:
        x = 0
        print 'Negative changed to zero'
    elif x == 0:print 'Zero'
    elif x == 1:print 'Single'
    else:print 'More' 
like image 41
Jason M Avatar answered Oct 24 '22 11:10

Jason M


If you do File --> New File, it should open a new savable window that you can write multiple lines and save as a .py file.

like image 28
StacknormalFlow Avatar answered Oct 24 '22 11:10

StacknormalFlow