Writing multi-line code in Python's IDLE application
Asked Answered
B

7

13

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 is in IDLE. As soon as I hit Enter after writting first line, it executes the first line and I am not able to write the full code.

Barnabe answered 2/5, 2012 at 12:21 Comment(1)
You don't have to execute it all in one go, if you do, then use a file for multiple runs or declare a function for a single run. Even if it executes earlier than you expected, you'll still have the entered value in the x variable.Kauslick
F
15

Try menu FileNew File in the top menu. Then write your code in this window and run it by the F5 key (or Run in the top menu).

Formalize answered 2/5, 2012 at 12:23 Comment(0)
P
9

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

Percolate answered 6/12, 2016 at 5:4 Comment(1)
This does not work.Wilow
M
8
  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'
    
Metrical answered 2/5, 2012 at 12:26 Comment(0)
H
3

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')"""
Hsu answered 2/5, 2012 at 12:21 Comment(0)
M
2

You can't write multi-line code in the Python console. You need a third-party application.

Marleenmarlen answered 31/10, 2015 at 17:3 Comment(1)
Leaving my prior misconception because nobody corrected me and it has been 8 years. Maybe it is correct and the new info I have is not correct? To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and continuation character slash “\”. - geeksforgeeks.org/python-multi-line-statementsMancuso
C
2

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.

Chip answered 26/5, 2020 at 8:32 Comment(0)
C
0

Creating a new file enables you to write your code in multiline in IDLE and before writing the code you need to save the file as *.py format. That's all.

Cataplasia answered 12/5, 2022 at 9:53 Comment(1)
But it isn't very interactive.Invercargill

© 2022 - 2024 — McMap. All rights reserved.