{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyP6ajx/tzXbVSGp19NXrPaj", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# **Syntax is a set of rules that define how code is written in a particular language. Some of the key elements of a language’s syntax include:**\n", "\n", "Keywords are reserved words in the programming language, such as “if,” “else,” and “for.”\n", "\n", "Variables are used to store data values and have names, types, and scopes.\n", "\n", "Control Flow Statements determine the sequence of execution in a program.\n", "\n", "Indentation determines code blocks.\n", "\n", "Comments make it possible to document your code inline.\n", "\n", "# **Basic Python Syntax**\n", "Let’s take a look at basic Python syntax, which is comprised of the same items above with the addition of:\n", "\n", "Functions\n", "\n", "Data types\n", "\n", "Classes and Objects\n", "\n", "Lists, Tuples, and Dictionaries" ], "metadata": { "id": "qtXgMAwAU01c" } }, { "cell_type": "markdown", "source": [ "# **Python Syntax Fundamentals**\n", "Indentation and Whitespace\n", "The key principles of Python indentation and whitespace include:\n", "\n", "**The Key Principles:**\n", "\n", "Indentation Defines Code Blocks: Python uses indentation to define blocks of code that should be executed together. Without proper indentation, your program will encounter syntax errors and won’t function correctly. Typically, indentation in Python is four spaces.\n", "Consistency: Indentation consistency matters. If you don’t use the same number of spaces or tabs consistently throughout all your code files, it could not only lead to confusion but your script not functioning.\n", "One-Level: Indent blocks that contain multiple lines of Python’s “language rules.” Such rules are made up of the following types:\n", "\n", "if, elif, else statements\n", "\n", "Loops (for, while)\n", "\n", "Function calls (like print(a) )\n", "\n", "Indentation is not merely a code formatting rule, but it’s also how Python “understands” the flow of your program.\n", "\n", "**Comments in Python**\n", "There are two types of comments in Python: single-line and multiple-line. A single-line comment might look like this:\n", "\n", "# This is my comment\n", "\n", "The best way to add a multiline comment in Python is with docstrings, which are encased in triple quotes like this:\n", "\n", "“””This is my comment.\n", "\n", "I love this comment.\n", "\n", "It is the best comment.”””\n", "\n", "Everything in between the triple quotes is ignored by Python.\n", "\n", "Variables and Data Types\n", "\n", "Operators and Expressions\n", "\n", "There are different types of operators and expressions for Python. You have:\n", "\n", "Arithmetic operators for basic math, such as addition, subtraction,\n", "multiplication, and division (result = 5 + 3)\n", "\n", "Comparison operators for comparing values and checking equality/\n", "\n", "inequality (is_equal = 5==5, if x > y, if x >= y)\n", "\n", "Logical operators for combining conditions and performing logical\n", " comparisons (is_true = x > 0 and y < 10)." ], "metadata": { "id": "5P8ETnSxVFgM" } }, { "cell_type": "markdown", "source": [ "# **Control Flow Statements**\n", "**If-Else Conditions**\n", "An if-else statement is used to execute a block of code when a certain condition is met. It checks for truth values and executes the corresponding code blocks based on these values." ], "metadata": { "id": "S7g_eUEDVUw1" } }, { "cell_type": "markdown", "source": [ "# **Loops**\n", "Python has two different types of control statements that are used for repetition:\n", "\n", "For Loops allow you to execute a block of code repeatedly based on the iterations over a sequence.\n", "While Loops continue executing as long as a certain condition is true, regardless of whether it’s related directly to each individual item or not (this also allows for conditional logic)." ], "metadata": { "id": "MqsssMZNVUzc" } }, { "cell_type": "markdown", "source": [ "# **Functions in Python**\n", "A function is a block of code that can be executed multiple times from different parts of a program. Functions make up the core structure of any well-written piece of software and are defined as such:\n", "\n", "Define the name of the function\n", "The def keyword is used to indicate to Python that what follows is a function.\n", "Parentheses are used to encapsulate the function." ], "metadata": { "id": "lUPdvOqPVU2M" } }, { "cell_type": "markdown", "source": [ "# **Importing and Using Modules**\n", "Python also allows you to import and use various modules. Modules are pre-written Python source files that serve different purposes. For example, you could use the built-in datetime module like this:\n", "\n", "print(“Current date:”,datetime.datetime.now())" ], "metadata": { "id": "uvDj6R1mVU4c" } }, { "cell_type": "markdown", "source": [ "# **Error Handling in Python (try-except Blocks)**\n", "Python provides several ways to handle errors, but the most important is the try-except block, which is used to catch and handle exceptions that may occur during the execution of your code.\n", "\n", "There are two parts to the try-except block:\n", "\n", "Try Block contains the code that might raise an exception.\n", "Except Block is used to handle exceptions raised in the try block." ], "metadata": { "id": "-Gr5aH5gVmWN" } }, { "cell_type": "markdown", "source": [ "# **Best Practices for Writing Clean Python Code (PEP 8 Guidelines)**\n", "PEP 8 provides a set of rules for writing clean and maintainable Python code, which are:\n", "\n", "Use import statements instead of from module import item.\n", "Use meaningful variable names.\n", "Keep functions concise.\n", "Keep class methods concise and meaningful.\n", "Use meaningful error messages.\n", "Use triple quotes for docstring formatting.\n", "Use consistent indentation (4 spaces).\n", "Keep blank lines between logical sections or control structures.\n", "Be cautious when formatting the code for documentation.\n", "Avoid repeated lines of code.\n", "Use loop constructs where possible to avoid recursion.\n", "Make your code testable." ], "metadata": { "id": "8bhEsuXmVmez" } }, { "cell_type": "markdown", "source": [ "# **What is Python Syntax?**\n", "Before we move on to understanding python syntax, let’s understand how to write and run a basic Python program.\n", "\n", "There are two ways to do so:\n", "\n", "1.**Interactive mode **– In this mode, you write and execute the program\n", "\n", "2.**Script mode** – In this mode, you first create a file (.py file), save it, and then execute it." ], "metadata": { "id": "a26wq4V3V9g7" } }, { "cell_type": "markdown", "source": [ "# **Indentation in Python**\n", "Whenever we write any piece of code in Python, say, functions or loops, we specify blocks of code for them. How will we identify which block is for what? It is done by “indenting” statements of that block according to the Python syntax." ], "metadata": { "id": "mfUHbWDXV9jk" } }, { "cell_type": "markdown", "source": [ "# **Python Syntax Identifiers**\n", "When we talk about variables, functions, classes, or modules, we use “identifiers” to identify them. What are identifiers? It is a name given to something to differentiate it from other code entities.\n", "\n", "Now just like for indentation, we have some naming rules here.\n", "\n", "The identifier will contain a combination of lowercase (a-z) or uppercase(A-Z) alphabets or numbers (0-9) or underscore (_)\n", "\n", "The Identifier cannot start with a digit\n", "\n", "Any reserved words or keywords cannot be used as identifier names\n", "(you’ll read more about keywords in the article soon)\n", "\n", "Symbols or Special characters cannot be used in the identifier\n", "\n", "Length of the identifier can be variable; there is no restriction\n", "\n", "Remember that Python is a case-sensitive language, so var and VAR are two different identifiers" ], "metadata": { "id": "61g1zpdoV9mF" } }, { "cell_type": "markdown", "source": [ "# **Quotation in Python**\n", "Three types are used when it comes to quotation marks accepted by Python according to the Python syntax.\n", "\n", "Single – ' ' Double – \" \" And Triple – \" \" \" … \" \" \"" ], "metadata": { "id": "nMvLQIJAV9o0" } }, { "cell_type": "markdown", "source": [], "metadata": { "id": "PV9v5K-bV9rc" } }, { "cell_type": "markdown", "source": [ "# **Blank Lines in Python**\n", "There are three ways to print blank lines in Python according to the Python syntax." ], "metadata": { "id": "YtPflS2MV9t7" } }, { "cell_type": "code", "source": [ "print(\"Line # 1\")\n", "print()\n", "print(\"Line # 3\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "hKFjh4rOWf7f", "outputId": "b3d527de-85b5-4af1-e165-5bb2e2f18855" }, "execution_count": 1, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Line # 1\n", "\n", "Line # 3\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Command Line Arguments**\n", "To keep our program’s nature generic, we use command-line arguments. For example, if we have written a program to parse a CSV file, inputting a CSV file from the command line would make our program work for any CSV file, making it generic.\n", "\n", "python code.py arg1 arg2 … arg N\n" ], "metadata": { "id": "4JvwSd3lV9w0" } }, { "cell_type": "markdown", "source": [ "# **Sys module**\n", "The sys module has a variable named argv. All the command line arguments are stored as a list of strings.\n", "\n", "If you want the first command-line argument entered, you can access it by argv[0].\n", "\n", "\n", "\n" ], "metadata": { "id": "EvmzljdFV9z7" } }, { "cell_type": "code", "source": [ "import sys\n", "\n", "if len(sys.argv) != 3:\n", " raise ValueError(\"Please provide your name and age\")\n", "\n", "print(f' Your name is {sys.argv[1]} and your age is {sys.argv[2]}')\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ck9MP44cWsoZ", "outputId": "d0151c68-cb36-46ba-a544-8e1261a6c634" }, "execution_count": 2, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " Your name is -f and your age is /root/.local/share/jupyter/runtime/kernel-3b7434b3-da39-412e-a347-db6cf4f32034.json\n" ] } ] }, { "cell_type": "markdown", "source": [ "There are 2 ways to write and run a Python program: interactive mode and script mode.\n", "\n", "Python Syntax for the print statement is – print(‘Syntax of print’)\n", "\n", "After every line of code that ends with ‘:’, python expects an indented code block. It is usually done with 4 whitespaces or 1 tab.\n", "\n", "Your code can throw an indentation error if there’s extra whitespace, an unexpected indent, or no indent.\n", "\n", "Identifiers in Python are used to identify variables, classes, functions, or objects. Some correct naming methods are – var, Robot, python_007, etc.\n", "\n", "Python has 36 keywords which are essentially reserved words that cannot be used as identifiers.\n", "\n", "Variables are containers that can be used to store any values. Variable names follow the same rules as identifiers.\n", "\n", "In python, you can use the ‘#’ symbol to write single-line comments like this :\n", "\n", "# this is a comment\n", "or write multiline comments like this:\n", "\n", "\"\"\"\n", "This is multiline.\n", "Written in 3 quotations.\n", "\"\"\"\n", "\n", "If a statement is too long, it can be broken down using the ‘\\’ character and written in multiple lines. Alternatively, you can write multiple short statements in one line by terminating each statement with the ‘;’ semicolon.\n", "\n", "In Python, three types of quotation marks are used. The single and double quotation marks are for strings, while the triple quotation marks are for multiline comments according to the Python syntax.\n", "\n", "The three ways to add a blank line in Python are:\n", "\n", "Use the empty print statement.\n", "\n", "Use print statements with empty single or double quotation marks\n", "\n", "Use the newline character (\\n)\n", "\n", "The input() function allows us to wait for user input. The program will not proceed further without user input according to the Python syntax.\n", "\n", "Using the sys module, we can take command-line arguments" ], "metadata": { "id": "OpKjivXHWuf5" } } ] }