0

I want to run python code from the shell instead of from a script.

I searched everywhere and found suggestions about using echo or Shift+Enter and using ^ at the end of the line, but ^ and shift+Enter didn't work in python shell, and I need to if there is a way to separate commands in the shell.

For example I need to run this from python shell instead of from a script:

If x > y
   print ("x is greater than y.")

but non of the options I tried worked.

2
  • Do you mean the REPL or your system shell? Commented Oct 27, 2019 at 15:35
  • I edited your question to make it more clear as you already received one downvote, so it should be ok now. Commented Oct 27, 2019 at 15:36

2 Answers 2

1

You need to use : to issue a line separator.

i.e.

if x > y:
   print ("x is greater than y.")
Sign up to request clarification or add additional context in comments.

1 Comment

oh! I am ashamed a lot for this childish mistake!!!! I code in pyCharm and I need to use command line, I was struggling for 2 hours! just for missing : ! Thanks man! again sorry for this low level question!
1

If you are asking how to enter Python code in your shell, then try something like

python -c 'if x > y:
    print(("x is greater than y")'

assuming you are using a Bourne-compatible shell (Linux etc). This has the major drawback that your Python code cannot easily contain a single quote (though if you know the quoting rules of the shell it's of course not impossible or even unobvious how to create an expression which evaluates to a single quote).

However, the common way to do this (and perhaps the only way on Windows?) is to type the Python code into a file and then run it with

python filename.py

where filename.py is the name of the file where you saved your Python code.

You can of course run simply

python

to enter the Python interpreter in interactive mode, where you can type in Python expressions and have them evaluated immediately. When you type an expression which ends with a colon, Python changes the prompt from >>> to ... to indicate that it expects one or more indented lines. (Type just a newline immediately at the ... prompt to exit this mode.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.