First Syntax#
Overview#
Let’s create a Python file and write code to print a message in the interpreter terminal:
Open a text editor (integrated development environment - IDE) of your choice, and create a new file, called “first_code.py”. The .py extension is required for a Python file.
In the new file, write the following code:
print("My first code!")
Save the file.
Open the anaconda terminal (or command prompt) and type:
> python first_code.py
and press Enter.
> "My first code!"
Congratulations, you have run a Python code!
Warning
If you got an error message, you will need to specify the python.exe location (e.g., “C:\Program Files\Anaconda\python.exe” in Windows OS). You should also check the “environmental variables” in Windows OS and add the python folder.
Conventions#
In these lectures we use the following conventions.
Commands in Anaconda command prompt are represented with >
:
> cd change-to-my-folder
> python first_code.py
Codes in Python interpreter are represented with >>>
:
>>> 2+2
>>> 10*213421
Code blocks written in IDE are:
123456
def my_function(input_message):
""" printing message"""
print(input_message)
Coding Style and PEP8#
PEP8 (Python Enhancement Proposal 8) is a set of guidelines and recommendations for writing Python code that promotes code readability, consistency, and maintainability. PEP 8 is widely accepted by the Python community. Here are three recommendations outlined in PEP 8:
Code Layout: PEP 8 suggests using 4 spaces for indentation and limiting line length to 79 characters. It also provides guidelines for using blank lines, spaces around operators, and consistent line breaks.
Naming Conventions: PEP 8 recommends using lowercase letters for variable and function names, separating words with underscores (snake_case). Class names should follow the CapWords convention. Constant variables should be written in uppercase letters with underscores.
Imports: PEP 8 recommends standard library imports first, followed by third-party library imports, and then local application or module imports. It also suggests avoiding wildcard imports (from module import *)