# Basic Programming Constructs – Python 3

Lesson Progress
0% Complete

As part of this topics we will see all important details related to basic programming constructs using Python 3

• Python CLI
• Getting Help
• Data types in Python
• Operators in Python
• Conditional Statements
• Looping Constructs
• Errors and Exceptions

Python is a case sensitive programming language.

## Python CLI and Getting Help

Let us get started with Python CLI as well as how to get help using CLI. Also we will understand details with respect to indentation which is used for defining the scope.

#### Python vs Java

• Python is Dynamically Typed. No need to declare anything. An assignment statement binds a name to an object, and the object can be of any type.No type casting required when using container objects where as Java is Statically Typed. All variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception.Type casting is required when using container objects.
• Python uses indentation for structuring code where as Java uses  braces for structuring code.
• Python is more compactable when compared to Java.

To print Hello ,World! in java,

but in Python,

#### Indentation

Python uses indentation to represent block of code.The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

Indentation can be done by using space-bar or tab. 1 tab = 4 spaces.

#### Python Identifiers

• An identifier starting with a single leading underscore indicates that the identifier is private. Similarly an identifier starting with double leading underscores indicates a strong private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

A hash sign (#) that is not inside a string literal is the beginning of a comment.

#### Quotations in python

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals.The triple quotes are used to span the string across multiple lines.

Variables are used to store values in reserved memory locations. In python, based on data type of the variable, interpreter automatically allocates memory and decides what can be stored in the reserved memory.

### Assigning Values

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

### Multiple Assignment

Python allows to assign a single value to several variables simultaneously.

Python also allows to assign multiple values to multiple variables at a time.

Here p is treated as integer,q as float and r as string.

## Standard Data Types

Let us go through details with respect to Standard Data Types in Python.

Python has five data types –

• Numbers – int, float,complex
• String
• Collections
• List
• Set
• Dictionary
• Tuple
• Dictionary
• type(VARIABLE_NAME) returns data type of the variable.

#### Numbers

Number variables are created when we assign a value to them.

We can also delete a single variable or multiple variables by using the del statement.

Python supports three different numerical types-

• int (signed integers)
• float
• complex

By default, in python3, all integers are represented as long integers.

A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are real numbers and j is the imaginary unit.

#### Strings

• Strings are identified  as a contiguous set of characters represented in the quotation marks.
• Subsets of strings can be taken using the slice operator ( ( [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.
• Plus (+) sign is used for concatenation of two strings.
• Asterisk (*) is repetition operator.

#### Lists

A list contains elements separated by commas and enclosed within square brackets( [] ). Lists can contain elements of different type.

• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.
• Plus (+) sign is used for concatenation of two lists.
• Asterisk (*) is repetition operator.

#### Set

A set contains elements separated by commas and enclosed within curly braces ( {} ). While list contain elements group of elements with duplicates, set will remove duplicates.

• As set does not contain duplicates we cannot read elements using index
• It actually checks whether the element exists in the set if you use [] and pass value to it

#### Dictionary

A dict contains group of key value pairs and they are typically comma separated and enclosed in curly braces ( {} ). Each element’s key value pair are separated by colon ( : ).

• Python’s dictionaries are kind of hash-table type.
• A dictionary keys are usually numbers or strings.
• Dictionary values can be any arbitrary python object.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

#### Tuples

• Tuples look similar to list, but they are different
• Unlike lists, tuples are enclosed within parenthesis.
• Lists represent homogeneous elements, while tuple represents heterogeneous
• Tuple is similar to individual record and list is like a table
• Main difference between lists and tuples – lists are enclosed in brackets ( [ ] ) and their elements and size can be changed while tuples are enclosed in parenthesis ( ( ) ) and cannot be updated. So the can be reffered as read-only lists.
• Plus (+) sign is used for concatenation of two tuples.  Asterisk (*) is repetition operator.

#### Type conversions

• int(x [,base]) – Converts x to an integer. The base specifies the base if x is a string.
• float(x) – Converts x to a floating-point number.
• complex(real [,imag]) – Creates a complex number.
• str(x) – Converts object x to a string representation.
• list(s) – Converts s to a list.
• tuple(s) – Converts s to a tuple.
• dict(d) – Creates a dictionary. d must be a sequence of (key,value) tuples.

## Operators

We can perform all sorts of standard numeric and string operations in Python using standard operators.

• Operators are the constructs, which can manipulate the value of operands.
• Python language supports the following types of operators − Arithmetic Operators, Relational Operators, Assignment Operators, Logical Operators, Bitwise Operators, Membership Operators and Identity Operators.
• Arithmetic Operators : +, -, *, /, %, **(Exponent), //(Floor Division)
• Relational Operators : ==, != , < , >, >=, <=
• Assignment Operators : =, +=, -=, *=, /=, %=, **= ,//=
• Logical Operators : and, or, not
• Bitwise Operators : &, |, ^, ~,  << , >>
• Membership Operators : in, not in
• Identity Operators : is, is not

• There are three control flow statements in Python – if, for and while.
• Python programming language assumes any non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.

## Conditional Statements and Loops

Let us quickly review how we can Conditional Statements and Loops in Python.

#### Decision making statements

• if statements – An if statement consists of a boolean expression followed by one or more statements.
• if – else statements – An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
• Nested-if statements – You can use one if or else if statement inside another if or else if statement.

#### Loops

• While-loop – Repeats a statement or group of statements while a given condition is TRUE and tests the condition before executing.
• For-loop – Execute a sequence of statements multiple times and also abbreviates the code that manages the loop variable.
• Nested-loop – You can use a loop inside another loop.

#### Loop control statements

• break statement – break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.
• continue statement – continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition. It continues with the next cycle of the nearest enclosing loop.

## Error and Exception Handling

Let us explore error and exception handling in Python

• Errors
• Exceptions
• Handling Exceptions (try/catch)
• Raising Exceptions
• Cleanup actions (finally)

#### Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
eg: while True print('Hello world')

#### Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

#### Handling Exceptions (try/catch)

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

Flow of try/catch execution

• First, the try clause (the statement(s) between the try and except keywords) is executed.
• If no exception occurs, the except clause is skipped and execution of the try statement is finished.
• If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
• If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
• try statement may have more than one except clause, to specify handlers for different exceptions
• An except clause may name multiple exceptions as a parenthesized tuple as shown above

#### Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur. For example:

raise NameError('HiThere')

#### Cleanup Actions

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances