To run a Python program, you need to have Python installed on your computer. You can write your code in a text editor or use an Integrated Development Environment (IDE) like PyCharm, Jupyter Notebook, or Visual Studio Code.
Once you've written your code, save it with a .py
extension, such as my_program.py
. To run the program, open a terminal or command prompt, navigate to the directory containing your Python file, and use the following command:
python my_program.py
You can also run Python in interactive mode by simply typing python
in your terminal or command prompt, which allows you to write and execute code line-by-line without saving it in a file first.
Let's create a simple Python program that prints "Hello, World!" to the console:
# my_program.py
print("Hello, World!")
To run this program, save it as my_program.py
, navigate to its directory in your terminal or command prompt, and execute the following command:
python my_program.py
You should see "Hello, World!" printed on the screen.
What causes it: This error occurs when you try to use a variable that hasn't been defined yet in your code.
# bad_code.py
print(my_variable)
Error message:
Traceback (most recent call last):
File "bad_code.py", line 1, in <module>
print(my_variable)
NameError: name 'my_variable' is not defined
Solution: Define the variable before using it in your code.
# corrected_code.py
my_variable = "Hello"
print(my_variable)
Why it happens: Python doesn't automatically declare variables, so you must define them before using them.
How to prevent it: Always make sure to declare your variables before using them in your code.
What causes it: This error occurs when you try to perform an operation on objects of incompatible types.
# bad_code.py
print(1 + "2")
Error message:
Traceback (most recent call last):
File "bad_code.py", line 1, in <module>
print(1 + "2")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Solution: Make sure to use the appropriate operators for your data types.
# corrected_code.py
print(str(1) + "2")
Why it happens: Python doesn't support adding an integer and a string directly. You need to convert one of them into a string before performing the addition operation.
How to prevent it: Always check the data types of your variables before performing operations on them, and use appropriate conversion functions if necessary.
.py
file and use the command python filename.py
.