JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Learn to program in Python

Introduction

Python is a simple, easy-to-understand, and minimalistic language. It is one of the easiest programming languages to learn because it has a clean and readable syntax that makes it easy for beginners to read and use. Besides, Python is free and open-source.

Python is an interpreted high-level general-purpose programming. It is used for web development, AI, machine learning, operating systems, mobile application development, and video games.

Installation

First steps

In case you do not want to (or cannot) install Python on your computer, you can execute Python programs using online tools, such as Python.org, replit (Python online editor), and Pythontutor.

Learn Python

Learn Python

Otherwise, open the terminal in your operating system and then open the Python prompt by typing python:

user@pc:~$ python
Python 3.9.5 (default, May 11 2021, 08:20:37) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>> 3*5 # You can use Python as a powerful calculator. The operators +, -, * and / work just like in most other languages.
15
>>> 5**2 # 5 squared
25 # 5^2=25
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s) # The built-in function len() returns the length of a string.
34
>>> import this! # Python has a really good sense of humour
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
>>> quit() # Use quit() or Ctrl-D (i.e. EOF) to exit

Visual Studio Code

Install Visual Studio Code. It is a multiplatform source-code editor made by Microsoft. Visual Studio Code functionality can be extended using extensions.

Let’s install Python extension for Visual Studio Code, Sublime Text Keymap (it imports keybindings and settings from Sublime Text to Visual Studio Code), Python-autopep8 (it automatically formats Python code. Linux’s shortcut is Ctrl+Shift+I), Pylint (a Python code analysis tool which looks for programming errors, e.g., print myswap(5, 9) as you can see in the screenshot below), Code Runner, and One Dark Pro by opening the Command Palette (Ctrl+Shift+P) and typing Extensions: Install Extensions.

Visual Studio Code

Visual Studio Code

Visual Studio Code provides an easy keyboard shortcuts editing experience using its Keyboard Shortcuts editor. You can open it by going to the menu File/Code, Preferences, Keyboard Shortcuts or using the Command Palette (Ctrl+Shift+P), Preferences: Open Keyboard Shortcuts.

Create an empty folder (mkdir python), navigate into it (cd python) and open VS Code (code). Alternatively, you can launch VS Code, then go to the File menu and select Open Folder… to open the project folder.

Immediately after that, select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P) and typing the Python: Select Interpreter command to search, then select the Python’s version that you want to work with.

Create a Python source code file: File, New File. As you write Python code, Visual Studio Code may give you a warning: Linter pylint (a source code, bug, and quality checker for Python) is not installed. Click on Install.

Run your source code file. Click on the Run Python File in Terminal button in the top-right side of the editor.

Learn Python withVisual Studio Code

Learn Python withVisual Studio Code

To run or debug an app, select Run and Debug on the Debug start view, Run, Start Debugging on the main menu, or just press F5, and VS Code will run your currently active file.

VS Code keeps debugging configuration information in a launch.json file. Navigate through Run, Open Configuration and you will be able to edit it. You may want to pass some arguments into the program by defining them in the args setting of launch.json as defined below:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "args":["myarg1", "myarg2"],
            "console": "integratedTerminal"
        }
    ]
}

Let’s configure Visual Studio Code to your heart’s content.

{
    "workbench.colorTheme": "One Dark Pro", // Color theme: "One Dark Pro", "Predawn", "Default Dark+", etc.
    "files.autoSave": "afterDelay", // It saves your files after a configured delay (default 1s).
    "explorer.confirmDelete": false,
    "window.zoomLevel": 4, // It adjusts the zoom level of the window.
    "editor.insertSpaces": false,    
    "editor.fontFamily": "Consolas", // It controls the font family.
    "editor.fontSize": 13, // It controls the font size.
    "workbench.settings.openDefaultSettings": true, // It controls whether opening settings also opens an editor showing all default settings.
    "workbench.settings.editor":"json", // By default VS Code shows the Settings editor, we want to edit the underlying settings.json
    "workbench.settings.useSplitJSON": true, // It controls whether to use the split JSON editor when editing settings as JSON.
    "python.formatting.provider": "autopep8", // This is the provider for formatting your code.
    "editor.formatOnSave": true, // The code is automatically formatted every time you save a file.
    "code-runner.executorMap": {
        "python": "$pythonPath -u $fullFileName",
     }, # It tells Code Runner to use the pythonPath variable.
    "code-runner.showExecutionMessage": false, // Don't show any extra execution message like [Running] and [Done]
    "code-runner.clearPreviousOutput": true, // Clear previous output before each run.
    "workbench.iconTheme": "material-icon-theme", // Icon theme: "material-icon-theme", "ayu", "vs-seti", etc.
    "cSpell.userWords": [
        "bilingüe"
    ],
    "cSpell.language": "en, es" //Code Spell Checker
}
  1. The Source Control icon is in the Activity Bar on the left. Clic on Initialize Repository.
  2. Create a .gitignore: venv credentials.py pycache *.pkl *pycache *.pickle3. Stage all files (git add .): …, Changes, Stage All Changes.
  3. Commit the changes (git commit): ✓, Commit.
  4. Push or publish your changes. You need to have already installed Git, have a GitHub account, and allow access to VS Code. You can create a new repository or clone a repository. If you select Clone repository, you will be asked for the URL of the remote repository and the parent directory under which to put the local repository.
  5. GitHub ended support for password authentication on August 13, 2021, so a personal access token needs to be used. A. First, create your token. Go to GitHub and in the upper-right corner of any page, click your profile photo, then click Settings, Developer settings, Personal access tokens, Generate new token. Create a new token by giving it a descriptive name, an expiration time, and select the scopes or permissions, you’d like to grant it (repo, admin). B. You need to change the Git origin remote to a new URL (it is really the same):
    git remote set-url origin https://[email protected]/UserName/RepositoryName.git

Some resources: The Ultimate Python Resource Hub, w3Schools, The Algorithms, etc.

If you have this error: TabError: inconsistent use of tabs and spaces in indentation using VS Code. You may want to convert existing indentation from spaces to tabs by hitting Ctrl + Shift + P and type: Convert indentation to Tabs.

Command Palette (Ctrl+Shift+P), Preferences: Configure User Snippets, then click on New Glabal Snippets file… or select a specific language (markdown)

{
    "Insert Raw HTML": {
        "prefix": "raw",
        "body": [
            "{{< raw >}}",
            "${1: markdown_content}",
            "{{< /raw >}}"
            ],
        "description": "Insert Raw HTML"
    },
    "Insert Code": {
        "prefix": "code",
        "body": [
            "``` ${1|html,python,md,bash,javascript,json|} ",
            "${2: markdown_content}",
            "```"
        ],
        "description": "Insert Code"
    },
    "Markdown link": {
        "prefix": "link",
        "body": [
            "[${1: link_text}](${2: link_url})"
        ],
        "description": "Markdown link"
    }
}

prefix defines the trigger word that display the snippet. body is one or more lines of content, and description is an optional description of the snippet.

The body of the example above has placeholders, e.g., ${1: markdown_content}, so you can quickly jump to the next placeholder with Tab. Placeholders can have choices as values, e.g., ${1|html,python,md,bash,javascript,json|}. When the snippet is inserted and the current placeholder is selected, these choices will be prompted to the user to pick one of them.

You can use Snippet generator to create snippets for Visual Studio Code, Sublime Text, and Atom.

If your snippets don’t work, go to settings, Edit in settings.json, and add the line: “editor.quickSuggestions”: true.

  1. code dotfiles (dotfiles is where I save all my configuration files)

  2. Let’s add settings.json. First, we need to create the structure: Code, .config, Code - OSS, User, settings.json. Code; and inside the User folder, snippets, markdown.json 2.1 Get the list of all installed extensions: code ‐‐list-extensions > vs-code-extensions.txt

  3. stow ‐‐adopt -nvt ~ *

  4. stow -nv ~ *

  5. cd ~/dotfiles

  6. git add . && git commit -am “my Code configuration” && git push

Bitcoin donation

JustToThePoint Copyright © 2011 - 2022 PhD. Máximo Núñez Alarcón, Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.