# Basic syntax of Python

The Python syntax defines a set of rules that are used to create Python statements while writing a Python Program. The Python Programming Language Syntax has many similarities to `Perl`, `C`, and `Java` Programming Languages. However, there are some definite differences between the languages.

## First Python Program

Let us execute a Python `Hello, World!` Programs in different modes of programming.

### Python - Interactive Mode Programming

We can invoke a Python interpreter from command line by typing python at the command prompt as following:

```
$ python
Python 3.6.8 (default, Sep 10 2021, 09:13:53)
[GCC 8.5.0 20210514 (Red Hat 8.5.0-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
```

Here `>>>` denotes a Python Command Prompt where you can type your commands. Let's type the following text at the Python prompt and press the `Enter`:

```
>>> print ("Hello, World!")
```

If you are running older version of Python, like Python `2.4.x`, then you would need to use print statement without parenthesis as in print `Hello, World!`. However in Python version `3.x`, this produces the following result:

```
Hello, World!
```

### Python - Script Mode Programming

We can invoke the Python interpreter with a script parameter which begins the execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

Let us write a simple Python program in a script which is simple text file. Python files have extension `.py`. Type the following source code in a `test.py` file:

```python
print ("Hello, World!")
```

We assume that you have Python interpreter path set in `PATH` variable. Now, let's try to run this program as follows:

```
$ python test.py
Hello, World!
```

Let us try another way to execute a Python script. Here is the modified `test.py` file:

```python
#!/usr/bin/python
print ("Hello, World!")
```

We assume that you have Python interpreter available in `/usr/bin` directory. Now, try to run this program as follows:

```
$ chmod +x test.py    # This is to make file executable
$ ./test.py
Hello, World!
```

## Expression & Statement in Python

In Python, an expression is a combination of values, variables, and operators that can be evaluated to produce a result. An expression can be as simple as a single value or as complex as a function call that returns a value.

For example, `2 + 3` is an expression that evaluates to `5`. Another example of an expression is `x * y`, where `x` and `y` are variables. Expressions can also include function calls, method calls, and conditional expressions.

A statement, on the other hand, is a unit of code that Python can execute. A statement can be an assignment, a function call, a loop, a conditional, or any other Python operation that produces a side effect.

For example, `x = 5` is a statement that assigns the value `5` to the variable `x`. Another example of a statement is a `print()` statement that prints a value to the console.

In summary, expressions are used to evaluate values, while statements are used to perform actions.

Here's an example that demonstrates a complex expression and statement in Python:

```python
# Define a function that takes a list of numbers and returns the sum of the even numbers
def sum_even_numbers(numbers):
    # Use a list comprehension to create a new list containing only the even numbers
    even_numbers = [num for num in numbers if num % 2 == 0]
    # Use the built-in sum() function to compute the sum of the even numbers
    total = sum(even_numbers)
    # Return the total
    return total

# Call the function with a list of numbers
numbers = [1, 2, 3, 4, 5, 6]
result = sum_even_numbers(numbers)
print(result)
```

In this example, the expression is the list comprehension `[num for num in numbers if num % 2 == 0]`, which creates a new list containing only the even numbers from the input list.

The statement is the entire function definition, which defines a new function `sum_even_numbers` that takes a list of numbers, processes the list using the expression, and returns the sum of the even numbers. The function is then called with a list of numbers and the result is printed to the console.

## Identifiers in Python

**Identifier** is a user-defined name given to a `variable`, `function`, `class`, `module`, etc. The identifier is a combination of character digits and an underscore.

> *It is a good programming practice to give meaningful names to identifiers to make the code understandable.*

We can also use the Python string `isidentifier()` method to check whether a string is a valid identifier or not.

```python
#!/usr/bin/env python
print("Name".isidentifier())
print("Age".isidentifier())
print("-Name".isidentifier())
print("1Name".isidentifier())
```

**Output:**

```
True
True
False
False
```

### Rules for Naming Python Identifiers

* It cannot be a reserved python `keyword`.
* It should not contain white space.
* It can be a combination of `A-Z`, `a-z`, `0-9`, or `underscore`.
* It should start with an alphabet character or an underscore (`_`).
* It should not contain any special character other than an underscore (`_`).

#### Some Valid and Invalid Identifiers in Python

| Valid Identifiers   | Invalid Identifiers |
| ------------------- | ------------------- |
| score               | @core               |
| return\_value       | return              |
| highest\_score      | highest score       |
| name1               | 1name               |
| convert\_to\_string | convert to\_string  |

> *Python is a case-sensitive language. This means, `Name` and `name` are not the same.*
>
> *Always give the identifiers a name that makes sense. While `c = 10` is a valid name, writing `count = 10` would make more sense, and it would be easier to figure out what it represents when you look at your code after a long gap.*
>
> *Multiple words can be separated using an underscore, like `this_is_a_long_variable`*

Here are naming conventions for Python identifiers:

* Python Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
* Starting an identifier with a single leading underscore indicates that the identifier is private identifier.
* Starting an identifier with two leading underscores indicates a strongly private identifier.
* If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

## Python Reserved Words

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

| break   | class    | continue |
| ------- | -------- | -------- |
| def     | del      | elif     |
| else    | except   | False    |
| finally | for      | from     |
| global  | if       | import   |
| in      | is       | lambda   |
| None    | nonlocal | not      |
| or      | pass     | raise    |
| return  | True     | try      |
| while   | with     | yield    |
| and     | as       | assert   |

### Print the list of all `keywords`

To print the list of all keywords, we must use `keyword.kwlist`, which can be used after importing the `keyword` module. Returns a list of all keywords in the current version of Python.

```python
#!/usr/bin/env python

# importing the module
import keyword

# printing the keywords
print("Python keywords are...")
print(keyword.kwlist)
```

**Output:**

{% code overflow="wrap" %}

```
Python keywords are...
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
```

{% endcode %}

We can also get a list of keywords in the current version of Python using the `help()` command.

```python
#!/usr/bin/env python
help("keywords")
```

**Output:**

```
Here is a list of the Python keywords.  Enter any keyword to get more help.
False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not
```

## Lines in Python

In Python, there are two types of lines: `logical` lines and `physical` lines.

1. **Physical lines:** These are the lines that you see in your `script`/`code` editor. They are the actual lines of code and end with a newline character.
2. **Logical lines:** These are the lines that Python recognizes as a single statement or instruction. Logical lines can span over multiple physical lines and are terminated by a newline character or a semicolon (`;`).

here's an example that demonstrates the difference between logical and physical lines:

```python
# Example of logical and physical lines

x = 5 + 2 \
+ 3 \
+ 7

if x > 10 \
and x % 2 == 0: print("x is greater than 10 and even")
```

In the above example, we have two logical lines of code that span over multiple physical lines.

In the first logical line, we are assigning the value of 5 plus 2 plus 3 plus 7 to the variable `x`. However, we have split this line into three physical lines for readability using the backslash (`\`) character at the end of the first two lines.

In the second logical line, we are using the backslash (`\`) character to split the line into two physical lines for readability. We are checking if the value of `x` is greater than 10 and if it is even. If both conditions are true, we are printing a message to the console.

> **Note:** that the backslash (`\`) character is used to escape the newline character and continue the statement on the next line.

## Indentation in Python

Indentation in Python is simply the spaces at the beginning of a code line. Indentation in other languages like `C`, `C++`, etc., is just for readability, but in Python, the indentation is an essential and mandatory concept that should be followed when writing a python code; otherwise, the python interpreter throws `IndentationError`.

### What is Indentation in Python <a href="#what-is-indentation-in-python" id="what-is-indentation-in-python"></a>

Indentation is the leading whitespace (`spaces` or/and `tabs`) before any statement in Python. The reason why indentation is important in python is that the indentation serves another purpose other than code readability. Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block. So whereas in languages like `C`, `C++`, etc. a block of code is represented by curly braces `{ }`, in python a block is a group of statements that have the same Indentation level i.e. same number of leading whitespaces.

<figure><img src="https://847702634-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6i4tTDVzxDUhKzBX7GT3%2Fuploads%2FriKPauznmx10zcywQ5Kx%2Fpython-indentation-1024x495.png?alt=media&#x26;token=19ce5cb2-b133-4617-9e76-38c7a03cc11b" alt=""><figcaption><p>Indentation in Python</p></figcaption></figure>

Below is an example code snippet with the correct indentation in python.

```python
name = 'Ali Nasiri'
  
if name == 'Ali Nasiri':
   print('Welcome Ali Nasiri..')
   print('How are you?')
else:
   print('Dude! whoever you are ')
   print('Why you here?')
 
print('Have a great day!')
```

**Output:**

```
Welcome Ali Nasiri..
How are you?
Have a great day!
```

### Python Indentation Rules <a href="#python-indentation-rules" id="python-indentation-rules"></a>

* Python uses **four spaces as default** indentation spaces. However, the number of spaces can be anything; it is up to the user. But a **minimum of one space** is needed to indent a statement.
* The first line of python code cannot have an indentation.
* Indentation is mandatory in python to define the blocks of statements.
* The number of spaces must be uniform in a block of code.
* It is **preferred to use whitespaces** instead of tabs to indent in python. Also, either use whitespace or tabs to indent; intermixing of tabs and whitespaces in indentation can cause wrong indentation errors.

### Benefits of Indentation in Python <a href="#benefits-of-indentation-in-python" id="benefits-of-indentation-in-python"></a>

* Indentation of code leads to better readability, although the primary reason for indentation in python is to identify block structures.
* Missing `{` and `}` errors that sometimes popup in `C`, `C++` languages can be avoided in python; also the number of lines of code is reduced.

## Python Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (`\`) to denote that the line should continue. For example:

```python
total = 1 + \
        2 + \
        3
```

Statements contained within the `[]`, `{}`, or `()` brackets do not need to use the line continuation character. For example following statement works well in Python:

```python
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']
```

## Quotations in Python

Python accepts single (`'`), double (`"`) and triple (`'''` or `"""`) quotes to denote `string` literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal:

```python
word = 'word'
print (word)

sentence = "This is a sentence."
print (sentence)

paragraph = """This is a paragraph. It is
 made up of multiple lines and sentences."""
print (paragraph)
```

## Comments in Python

A comment is a programmer-readable explanation or annotation in the Python source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Python interpreter

Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. Python comments are very much similar to the comments available in `PHP`, `BASH` and `Perl` Programming languages.

A hash sign (`#`) that is not inside a string literal begins a comment. All characters after the `#` and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

```python
# First comment
print ("Hello, World!") # Second comment
```

**Output:**

```
Hello, World!
```

You can type a comment on the same line after a statement or expression:

```python
name = "Ali Abdullah Nasiri" # This is again comment
```

You can comment multiple lines as follows:

```python
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
```

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

```python
'''
This is a multiline
comment.
'''
```

## **Docstrings in Python**

Python `docstrings` are the string literals that appear right after the definition of a `function`, `method`, `class`, or `module`. Let's take an example.

* **Declaring Docstrings**: The doc-strings are declared using `'''` triple single quotes `'''` or `"""` triple double quotes `"""` just below the `class`, `method`, or `function` declaration. All functions should have a docstring.
* **Accessing Docstrings**: The doc-strings can be accessed using the `__doc__` method of the object or using the `help` function.&#x20;

The below examples demonstrate how to declare and access a docstring.

```python
def sum(a, b):
    """
    Calculate the sum of two numbers.

    Parameters:
    a (int): First number.
    b (int): Second number.

    Returns:
    int: Sum of the two numbers.
    """
    return a + b

# Accessing the docstring
print(sum.__doc__)
```

When you run this code, it will print out the docstrings of the `sum` function:

```
Calculate the sum of two numbers.

Parameters:
a (int): First number.
b (int): Second number.

Returns:
int: Sum of the two numbers.
```

> ***Note:** comments are meant for developers to add explanatory notes within the code, while docstrings are used to provide documentation for `functions`, `classes`, `modules`, or `methods`. Docstrings have a defined structure and can be accessed at runtime, whereas comments are purely for human understanding and are ignored by the Python interpreter.*

## Using Blank Lines in Python Programs

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

## Waiting for the User

The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action:

```python
#!/usr/bin/env python

input("\n\nPress the enter key to exit.")
```

Here, `\n\n` is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.

## Multiple Statements on a Single Line

The semicolon ( `;` ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon:

```python
import sys; x = 'foo'; sys.stdout.write(x + '\n')
```

**Output:**

```
foo
```

## Multiple Statement Groups as Suites

A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as `if`, `while`, `def`, and `class` require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( `:` ) and are followed by one or more lines which make up the suite. For example:

```python
if expression :
   suite
elif expression :
   suite
else :
   suite
```

### Command Line Arguments in Python

Command line arguments are the parameters that are passed to a Python script when it is executed from the command line interface (`CLI`). They provide a way to pass information or data to the script without hardcoding them in the code.

In Python, command line arguments are stored in the `sys.argv` list, which is automatically created by the interpreter when the script is executed. The `sys.argv` list contains the name of the script as its first element (`sys.argv[0]`) and any additional arguments as subsequent elements.

For example, if we have a Python script named `my_script.py` and we execute it with the following command:

```python
import sys

# Get the name of the script
script_name = sys.argv[0]

# Get the first argument
arg1 = sys.argv[1]

# Get the second argument
arg2 = sys.argv[2]

# Print the arguments
print("Script name:", script_name)
print("Argument 1:", arg1)
print("Argument 2:", arg2)
```

**Output:**

```
$ python my_script.py arg1 arg2 arg3
Script: my_script.py
Argument 1: arg1
Argument 2: arg2
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ali-abdullah-nasiri.gitbook.io/python/chapter-two-basics-and-syntax/basic-syntax-of-python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
