🚀 Join our community of 100,000+ learners worldwide! 📚 2000+ free tutorials available 🎓 Get certified today! 💡 Learn at your own pace 🌟 New courses added weekly 🤝 Connect with expert instructors
Python - Syntax - Ngahtech Tutorials

Python - Syntax

0 min read Python – Application Areas / Python – Application Areas
Text

Python - Syntax

Python SyntaxThe Python syntax defines a set of rules that are used to create 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 program to print "Hello, World!" in two different modes of Python programming:

  1. Interactive Mode Programming
  2. Script Mode Programming

Python - Interactive Mode ProgrammingWe can invoke a Python interpreter from the command line by typing python at the command prompt as follows −

$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] 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 Enter −

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

If you are running an older version of Python, such as Python 2.4.x, then you would need to use the print statement without parentheses as in:

print "Hello, World!"

However, in Python version 3.x, this produces the following result −

Hello, World!

Python - Script Mode ProgrammingWe 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 a simple text file. Python files have the .py extension.

Type the following source code in a test.py file −

print ("Hello, World!")

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

$ python3 test.py

This produces the following result −

Hello, World!

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

#!/usr/bin/python3

print ("Hello, World!")

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

$ chmod +x test.py     # This is to make file executable
$ ./test.py

This produces the following result −

Hello, World!

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z, a to z, or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.

Python is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

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 a 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 names, variable names, or any other identifier names.

All Python keywords contain lowercase letters only.


and

The and keyword is a logical operator used to combine two or more conditions. It returns True only if all conditions being evaluated are true.

as

The as keyword is used to create an alias for a module, function, or imported object. It is also commonly used in exception handling and context managers.

assert

The assert keyword is used for debugging purposes. It tests whether a condition is true and raises an AssertionError if the condition evaluates to false.

break

The break keyword is used to terminate a loop immediately. When encountered, control exits the loop and continues with the next statement after the loop.

class

The class keyword is used to define a new class in Python. Classes are blueprints for creating objects and implementing object-oriented programming concepts.

continue

The continue keyword skips the remaining statements in the current iteration of a loop and moves execution to the next iteration.

def

The def keyword is used to define a function. Functions allow you to group reusable blocks of code that can be called whenever needed.

del

The del keyword is used to delete objects, variables, list items, dictionary entries, or other references from memory.

elif

The elif keyword stands for "else if" and is used in conditional statements to test multiple conditions after an initial if statement.

else

The else keyword specifies a block of code that executes when the conditions in an if or elif statement evaluate to false.

except

The except keyword is used in exception handling to catch and handle errors that occur within a try block.

False

The False keyword represents one of Python's two Boolean values. It indicates a negative or unsuccessful logical condition.

finally

The finally keyword defines a block of code that always executes after a try statement, regardless of whether an exception occurred.

for

The for keyword is used to create loops that iterate over sequences such as lists, tuples, strings, or other iterable objects.

from

The from keyword is used with the import statement to import specific objects, functions, classes, or modules from another module.

global

The global keyword allows a function to modify a variable that is defined in the global scope rather than creating a local variable.

if

The if keyword is used to perform conditional execution. A block of code is executed only when the specified condition evaluates to true.

import

The import keyword is used to include modules and libraries into a Python program, making their functionality available for use.

in

The in keyword is used to test membership in a sequence or collection and is also used in loops for iteration.

is

The is keyword is used to compare whether two variables refer to the same object in memory.

lambda

The lambda keyword is used to create small anonymous functions without using the standard def syntax.

None

The None keyword represents the absence of a value or a null value. It is commonly used as a default return value for functions.

nonlocal

The nonlocal keyword is used inside nested functions to refer to variables defined in the nearest enclosing scope that is not global.

not

The not keyword is a logical operator that reverses the truth value of a condition. If a condition is true, not makes it false, and vice versa.

or

The or keyword is a logical operator used to combine conditions. It returns True if at least one of the conditions is true.

pass

The pass keyword is a null statement that performs no action. It is often used as a placeholder where code will be added later.

raise

The raise keyword is used to manually trigger an exception in a program.

return

The return keyword is used inside a function to send a value back to the caller and terminate the function's execution.

True

The True keyword represents one of Python's Boolean values and indicates a positive or successful logical condition.

try

The try keyword defines a block of code that may raise an exception. It is typically followed by except, else, or finally blocks.

while

The while keyword creates a loop that continues executing as long as a specified condition remains true.

with

The with keyword is used for resource management and context handling. It ensures that resources such as files are properly opened and closed.

yield

The yield keyword is used inside a function to create a generator. Instead of returning a value and ending execution, it produces values one at a time and preserves the function's state between iterations.

Python Lines and Indentation

Python programming provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −

if True:
   print ("True")
else:
   print ("False")

However, the following block generates an error −

if True:
   print ("Answer")
   print ("True")
else:
   print ("Answer")
   print ("False")

Thus, in Python, all continuous lines indented with the same number of spaces form a block.

The following example contains various statement blocks −

import sys

try:
   # open file stream
   file = open(file_name, "w")
except IOError:
   print "There was an error writing to", file_name
   sys.exit()

print "Enter '", file_finish,
print "' When finished"

while file_text != file_finish:
   file_text = raw_input("Enter text: ")

   if file_text == file_finish:
      # close the file
      file.close
      break

   file.write(file_text)
   file.write("\n")

file.close()

file_name = raw_input("Enter filename: ")

if len(file_name) == 0:
   print "Next time please enter something"
   sys.exit()

try:
   file = open(file_name, "r")
except IOError:
   print "There was an error reading file"
   sys.exit()

file_text = file.read()
file.close()
print file_text

Do not try to understand the logic at this point. Just make sure you understand the various blocks even though they are written without braces.

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 indicate that the line should continue.

For example −

total = item_one + \
        item_two + \
        item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character.

For example, the following statement works well in 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.

Triple quotes are used to span strings across multiple lines.

For example, all the following are legal −

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 Python source code. Comments are added to make the source code easier for humans to understand and are ignored by the Python interpreter.

Like most modern languages, Python supports both single-line and multi-line comments. Python comments are very similar to comments 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 are ignored by the Python interpreter.

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

This produces the following result −

Hello, World!

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

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

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

The following triple-quoted string is also ignored by the Python interpreter and can be used as a multiline comment:

'''
This is a multiline
comment.
'''

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 "Press the enter key to exit" and waits for the user to take action −

#!/usr/bin/python

raw_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 useful 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 a single line, provided that neither statement starts a new code block.

Here is a sample snippet using the semicolon −

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

Multiple Statement Groups as Suites

A group of individual statements that make up a single code block is called a suite 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 a keyword and terminate with a colon (:). They are followed by one or more lines that make up the suite.

For example −

if expression :
   suite
elif expression :
   suite
else :
   suite

Command Line Arguments in Python

Many programs can be run to provide basic information about how they should be executed. Python enables this with the -h option −

$ python3 -h

usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...

Options and arguments (and corresponding environment variables):

-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser (also PYTHONDEBUG=x)
-E     : ignore environment variables (such as PYTHONPATH)
-h     : print this help message and exit

[ etc. ]

You can also program your script in such a way that it accepts various options.

Command-line arguments are an advanced topic and should be studied later after you have gone through the rest of the Python concepts.