AirPods

Python 3 Basic Syntax

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

Python Identifiers

Python Identifier is the name we give to identify a variable, function, class, module or other object. That means whenever we want to give an entity a name, that’s called identifier.

There are some rules for writing Identifiers. But first you must know Python is case sensitive. That means Name and name are two different identifiers in Python. Here are some rules for writing Identifiers in python.

  1. Identifiers can be combination of uppercase and lowercase letters, digits or an underscore(_). So myVariablevariable_1variable_for_print all are valid python identifiers.
  2. An Identifier can not start with digit. So while variable1 is valid, 1variable is not valid.
  3. We can’t use special symbols like !,#,@,%,$ etc in our Identifier.
  4. Identifier can be of any length.

Though these are hard rules for writing identifiers, also there are some naming conventions which are not mandatory but rather good practices to follow.

  1. Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  2. Starting an identifier with a single leading underscore indicates the identifier is private.
  3. If the identifier starts and ends with two underscores, than means the identifier is language-defined special name.
  4. While c = 10 is valid, writing count = 10 would make more sense and it would be easier to figure out what it does even when you look at your code after a long time.
  5. Multiple words can be separated using an underscore, for example this_is_a_variable.

Here’s a sample program for python variables.

firstString="hello python"
print(firstString)

int1=1
print(int1)

int2=2
print(int2)

Python Keywords

Keywords are the reserved words in Python.

We cannot use a keyword as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.

In Python, keywords are case sensitive.

The following program will output all keywords of the current version of python:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', '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']

Comments in Python

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

#!/usr/bin/python3

# First comment
print ("Hello, Python!") # second comment

This produces the following result.

Hello, Python!

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

name = "Madisetti" # This is again comment

Python does not have multiple-line commenting feature. You have to comment each line individually as follows.

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

Note: As part of the Python course it is taught that in order to do a multiline comment one should use """triple quotes""". This is wrong. Python only has one way of doing comments and that is using #.

Triple quotes are treated as regular strings with the exception that they can span multiple lines. By regular strings I mean that if they are not assigned to a variable they will be immediately garbage collected as soon as that code executes. hence are not ignored by the interpreter in the same way that #a comment is.

Print Function in Python 3

The print function in Python is used to display the output of variables: string, lists, tuples, range etc.

Before version 3.x of Python, the print was taken as a statement. However, from Python 3.x, the print acts as a function. For example:

print("A String")
 
print(a_variable)
 
print(list)

Following is the syntax of using the print function:

print(*objects, sep='', end='\n', file=sys.stdout, flush=False)

Where:

  • The object can be strings, lists, tuple etc.
  • The sep = '' parameter specifies a space between multiple objects. You may use other than space by using this parameter.
  • The end='\n\' means in each call, the print function will end at a newline. A demo is shown later in this tutorial, how you can change that.
  • The file=sys.stdout specifies where the print function should send the output. The default value is stdout that you may change, for example to an external file.
  • In Python 3.3 the flush keyword argument is added that specifies whether to flush or not the output stream. The default value is false.

Lines and Indentation

Python does not use 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")    # indenting with the different number of spaces will cause an error

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

Multi-Line Statements

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

total = item_one + \
        item_two + \
        item_three

The statements contained within the []{}, or () brackets do not need to use the line continuation character. For example:

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

Quotation 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.

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Using Blank Lines

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 Input

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

#!/usr/bin/python3

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 a single line given that no statement starts a new code block. Here is a sample snip using the semicolon:

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

Multiple Statement Groups as Suites

Groups 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:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

import and from…import

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

import module_name

When import is used, it searches for the module initially in the local scope by calling __import__() function. The value returned by the function are then reflected in the output of the initial code.

import math 
print(math.pi)

Output:

3.141592653589793

import module_name.member_name

In the above code module math is imported, and its variables can be accessed by considering it to be a class and pi as its object. The value of pi is returned by __import__()pi as whole can be imported into our intial code, rather than importing the whole module.

from math import pi 
  
# Note that in the above example,  
# we used math.pi. Here we have used 
# pi directly. 
print(pi)

Output:

3.141592653589793

from module_name import *

In the above code module math is not imported, rather just pi has been imported as a variable. All the functions and constants can be imported using *.

from math import *
print(pi) 
print(factorial(6))

Output:

3.141592653589793
720

The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module

  • Pros: Less maintenance of your import statements. Don’t need to add any additional imports to start using another item from the module
  • Cons: Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo

  • Pros:
    • Less typing to use foo
    • More control over which items of a module can be accessed
  • Cons:
    • To use a new item from the module you have to update your import statement
    • You lose context about foo. For example, it’s less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don’t use from module import *.

For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from ‘module’, making it easy to get to the point where you think you don’t use the import any more but it’s extremely difficult to be sure.

Command Line Arguments

Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h

$ python -h
usage: python [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. ]

So far, we have learned the basic syntax of Python 3. Compared to other programming languages, Python’s syntax is simpler and more flexible.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button