Before move ahead and explore various advanced commands let us quickly see how we can run a .py file (python extension) in python shell. The Python Interpreter can take commands line by line and give you the results instantly but what if you need to execute it more than once and you would like to use it again and again?
You can actually save the entire code in a python file and just run the python file in the python shell.
Run a py File in Python Shell
Follow the below steps to execute a set of code by saving it to .py file
STEP-1: Open the IDLE editor, it should be available in your All Programs (this is for windows), under Python 3.x folder. You should see a Python Shell launched as shown below.
STEP-2: Click on the File menu option and select New File.
You can also use the shortcut CTRL + N which will open an Untitled python document editor as shown below,
STEP-3: Paste the below code in the Untitled code editor window,
#addTwoNumbers is a function that will add two numbers.
result = a+b
#Get the Number1 from the user.
Number1 = int(input("Please enter number 1: "))
#Get the Number2 from the user.
Number2 = int(input("Please enter number 2: "))
#Call the addTwoNumbers function which will add and display the result.
STEP-4: Now click on the File menu and select Save. Save the file as “AddTwoNumbers.py”in a location that you prefer. For example I have saved it in C:\PythonSnippets. You should see something as shown below,
STEP-5: Open a command window and navigate to the folder by entering the below command
You can use windows explorer and go to the folder C:\PythonSnippets, hold SHIFT key and right click which will display the “Open command window here” option and when clicked it will directly open the folder in command window.
STEP-6: In your command window just type the below command and press Enter key,
You will be asked to enter number 1 and number 2. Once entered the result will be displayed as shown below.
Alternatively, after you have completed STEP-3 i.e saving the file you can directly press F5 in the editor itself which will run the program