Python Language Basics
Introduction
Python programming language, developed by Guido Van Rossum in early 1990s, has become very popular programming language among begineers as well as developers. Let us revise all the zeast content of python in this chapter.
Tokens in Python
The smallest individual unit in a program is known as Token or Lexical unit.
Python has following tokens:
- Keywords
- Indentifiers
- Literals
- Operators
- Punctuators
Keywords
Keywords are predefined words with special meaning to the language compiler or interpreter. These are reserved for special purpose and must not be used as normal identifier names.
Some of the keywords are:
False assert del for in or while none break
elif from is pass with true class else global
lambda raise yield and continue except if nonlocal
return as def finally import not try
Identifiers
Identifiers are the names given to different parts of the program i.e. variables, objects, classes, functions, list, dictionaries etc.
Naming rules for variables are:
- Varibable name must only be a non-keyword word with no spaces between them.
- It should not start with a number, although they can contain numbers
- Varibale names must be made up of only letters, numbers, and underscore.
Remember Python is case sensitive which means it treats uppercase and lowercase characters differently.
Literals
Literals are the data items that have a fixed/constant value.
- String Literals: A string literal is a sequence of characters surrounded by quotes. String literals can either be single line strings or multi-line strings.
- Single Line Strings must terminate in one line i.e. closing quotes should be on the same line as that of the opening quotes.
- Multi Line Strings are strings spread across multiple lines. With single and double quotes, each line other than the conlcuding line has an end character as \( backslash ) but with triple quotes, no backslash is needed at the end of intermediate lines.
- Numeric Literals:
Numeric Literals are numeric values and these can be one of the following types:.
- int(signed integers) often called just integers or ints, are positive or negative whole numbers with no decimal point.
- Decimal Form- 1234,1490
- Octal Form- 0o37,0o77
- Hexadecimal Form- 0x73, 0xAF
- Floating Point Literals represent real numbers and are written with a decimal point dividing the integer and fractional parts are numbers having fractional parts.
- Complex Number literals are of the form "a+bJ", where a and b are floats and J or j represents √(−1), which is an imaginary number. a is the real part of the number and b is the imaginary part of the number.
- int(signed integers) often called just integers or ints, are positive or negative whole numbers with no decimal point.
- Boolean Literals:
A boolean literal in python is used to represent one of the two boolean values i.e., True(Boolean True) or False (Boolean False). A boolean literal can either have value as True or False
- Special Literal None:
Python has one special literal, which is None. The None Literal is used is used to indicate absence of value. Python can also literal collections, in the form of tuples and lists etc.
Operators
Operators are tokens that trigger some computation/action when appplied to variables and other objects in an expression.
The operators can be arithmetic operators(+, -, *, /, %, //), bitwise operators(&, ^, |), shift operators(<<, >>), identity operators(is, is not), relational operators(>, <, >=, <=, ==, !=), logical operators(and, or), assignment operator(=), membership operators(in, not in), and arithmetic-assignment operators(/=, +=, -=, */, %=, **=, //=)
Punctuators
Punctuators are sysmbols that are used in programming languages to organize sentence structures, and indicate the rhythm and emphasis of expressions, statements and program structure.
Most common punctuators of python programming language are: ' " # \ () [] {} @ , : . ` =
Barebones of a python program
A Python program may contain various elements such as comments, statements, expressions etc.
- Expressions, which are any legal combination of sysmbols that represents a value
- Statements, which are programming instructions.
- Comments, which are the additional readable information to clarify the source code.
- Functions, which are named code-sections and can be reused by specifying their names(function calls).
- Block(s) or suite(s), which is a group of statements which are part of another statement or a function. All statements inside a block or suite are indented at the same level.
Variables and Assigments
Variables represent labelled strorage locations, whose values can be manipulated during program run.
In Python, to create a variable, just assign to its name the value of appropriate type. For example, to create a variable namely Student to hold student's name and variable age to hold student's age.
-
Dynamic Typing:
In, python as we learnt, a variable is defined by assigning to it some value (of a particular type such as numeric, string etc).
X = 10 print(X) X = "Hello World" print(X)
The above code will yield output as:
10 Hello World
Dynamic typing is different from static typing. In static typing, a data type is attached with a varibale when it is defined first and it is fixed. That is, data type of a varibale cannot be changed in static typing whereas there is no such restriction in dynamic typing, which is supported by Python.
-
Multiple Assignments:
Python is very versatile with assignments.
- Assigning same value to multiple variables.
a=b=c=10
- Assigning multiple values to multiple varibales.
ax,y,z = 10, 20, 30
- Assigning same value to multiple variables.
Simple Input and Output
In python 3.x, to get inout from user interactively, we can use built-in function input(). The function input() is used in the following manner:
varibale_to_hold_the_value = input(<promtt to be displayed>)
The input() function always returns a value of String type. Python offers two functions int() and float() to be used with input() to convert the values received through input() into int and float types.
Output Through print() Statement: The print() function of Python 3.x is a way to send output to standard output device, which is normally a monitor.
The simplified syntax to use print() function is as follows:
pritn(*objects, [sep = '' or <separator-string> end = '\n' or <end-string>])
*objects means it can be one or multiple comma separated objects to be printed.
Note: A print() function without any value or name or expression prints a balnk line.
Data Types
Data types are means to identify type of data and set of valid operations for it. Python offers following built-in core data types: (i) Numbers (ii)String (iii)List (iv)Tuple (v)Dictionary
- Data Types for Numbers:
Python offers following data types to store and process different types of numeric data:
- Integers: There are two types of integers in python: integers and booleans
- Floating point numbers: In python, floating point numbers represent machine-level double precision floating point numbers(15 digit precision). The range of these numbers is limited by underlying machine architecture subject to available(virtual) memory.
- Complex number: Python represents complex numbers in the form A+Bj. Both the real and imaginary part are represented internally as float values.
- Data Type for Strings:
All strings in Python 3.x are sequences of pure Unicode characters. Unicode is a system designed to represent every character from every language. A string can hold any type of known characters of any known scripted language. Individual characters can be accessed using the index.
- Lists:
A list in pyhton represents a group of comma-separated values of any datatype between square brackets. In list too the values internally are numbered from 0(zero) onwards i.e. firs item of the list is internally numbered as 0, second item of the list as 1 and so on.
- Tuples:
Tuples are represented as group of comma-separated values of any data type within parentheses.
- Dictionaries:
The dictionary is an unordered set of comma-separated key:value pairs, within {}, with the requirement that within a dictionary no two keys can be the same(i.e., there are unique keys within a dictionary.)
Mutable and Immutable Types
The python data objects can be broadly categorized into two - mutable and immutable types, in simple words changeable or modifiable and non modifiable types.
- Immutable Types:
The immutable types are those that can never change their value in place. In python, the following types are immutable: integers, floating point numbers, booleans, strings, tuples.
In immutable types, the variable names are stored as references to a value-object. Each time you change the value, the variable's refenrence memory address changes. - Mutable Types:
Mutability means that in the same memory address, new value can be stored as and when you want. The types that do not support this property are immutable types. The mutable types are those whose values can be changes changes in place. Lists, dictionaries and sets are immutable types.
Expressions
An expression in Python is any valid combination of operators, literals and varibales. The expressions in python can be of any type: arithmetic, string, relational, logical, compound expressions.
Arithmetic expressions involve numbers and arithmetic operators, e.g. 2+5**3
An expression having literals and/or variables of any valid type and relational operators is a relational expression e.g. x>y, x<=y
An expression having literals and/or variables of any valid type and logical operators is a logical expression. e.g. a or b, a and b
Python also provides two sting operators + and *, when combined with string operands and integers, form string expressions. e.g. "and" + "then"
- Evaluating Arithmetic Operations:
To evaluate arithmetic expression, the first thing done by python is that it determines the order of evaluation in an expression considering the operator precedence.
- Evaluate each of its operands
- Performs any implicit conversions(e.g. promoting int to float or bool to int for arithmetic on mixed types.)
- Compute its result based on the operator.
- Replace the subexpression with the computed result and carry on the expression evaluation.
- Repeat till the final result is obtained.
Operator Description () Parentheses(grouping) ** Exponentiation ~x Bitwise nor +x,-x Positive, negative(unary +, -) *, /, //, % Multiplication, Division, floor division, remainder +, - Addition, Subtraction & Bitwise AND ^ Bitwise XOR | Bitwise OR <, >, <=, >=, ==, <>, !=, is, is not Comparisons(Relational, operators) not x Boolean NOT and Boolean AND or Boolean OR -
Evaluating Raltional Expressions:
All comparison operations in Python have the same priority, which is lower than that of any arithmetic operations. All relational expressions(comparisons) yield boolean values only i.e. True or False.
-
Evaluating Logical Expressions:
While evaluating logical expressions, python first finds if there is any arithmetic sub-expression, then it is evaluated first and then logical operators are applied.
- Type Casting:
An explicit type conversion is user defined conversion that forces an expression to be of specific type. The explicit type conversion is also known as type casting.
Type casting in python is performed by <type>() function of appropriate data type.
Statement Flow Control
In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iterations.
A conditional is a statement set which is executed, on the basis of result of a condition. A loop is a statement which is executed repeatedly, until the end condition is satisfied.
- Compound Statement:
A compound statement represents a group of statements executed as a uit. The compund statements of Python are written in a specific pattern as shown:
<compound statement head>: <indented body containing multiple simple compound statements>
- The contained statements are not written in the same colimn as the control statement, rather they are indented to the right and together they are called a block.
- The first line of compound statement, i.e. its header contains a colon(:) at the end of it.
-
Simple Statement
Compound statements are made of simple statements. Any single executable statement is a simple statement in Python
-
Empty Statement:
The simplest statement is the empty statement i.e., a statement which does nothing. In python an empty statement is the pass statement. Whenever Python encounters a pass statement, python does nothing and moves to the next statement in the flow of control
The if Conditionals
The if conditionals of python come in multiple forms : plain if conditional, if-else conditional, and if-elif conditionals.
- Plain if conditional statement:
An if statement tests a particular condition; if the condition evaluates to true, a course-of-action is followed i.e., a statement or set-of-statements is executed. If the condition is false, it does nothing:
The syntax (general form) of the if statement is as shown below:if <conditional expression>: statement
-
The if-else conditional statement
This form of if statement test a condition and if the condition evaluates to false, it carries out statements indented below else.
The syntax of the if-else statement is as shown below:if <conditional expression>: statement else: statement
-
The if-elif conditional statement:
Sometimes we want to check a condition when control reaches else i.e. condition test in the form of else if. To serve such conditions, Python provides if-elif and if-elif-else statements. The general form of these statements is :
if <conditional expression>: statement elif <conditional expression>: statement
- Nested if statements:
Sometimes you may need to test additional conditions. For such situations, python also supports nested-if form of if. A nested if is an if that has another if in its if's body or in elif's body or in its else body.
- Storing Condition:
Sometimes the conditions being used in code are complex and repetitive. In such cases to make your program more readable, you can use named conditions i.e. you can store conditions in a name and use that named conditional in the if statements.
Looping Statements
Python provides two kinds of loops: for loop and while loop to represent counting loop and conditional loop respectively.
- The for loop
The for Loop of Python is designed to process the items of any sequence, such as a list or a string, one by one.
General form of for loop is :for <variable> in <sequence>: statements-to-repeat
-
The range() based for loop
For number based lists, we can specify range() function to represent a list as:
The syntax of the if-else statement is as shown below:for <variable> in range(3,18): statements-to-repeat
-
The while loop:
A while loop is a conditional loop that will repeat the instructios within itself as long as a conditional remains true(boolean true or truth value true). The general form of while loop is :
while <logical expression>: loop-body
Jump Statements break and continue
Python offers two jump statements - break and continue - to be used within loops to jump out of loop-iterations
- The break statement:
A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.
The syntax for break statement is :if <conditional expression>: some-statements break
-
The continue statement
Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
The syntax for continue statement shown below:if <conditional expression>: statement continue these-are-skipped
More on Loops
Their are two more things we need to know about loops - the loop else clause and nested loops
- Loop Else Statement:
Python loops have an optional else clause. Complete syntax of python loops along with else clause is as given below.
The syntax (general form) of the if statement is as shown below:for <variable> in <sequence>: statement1 statement2 . . else: statement(s)
while <test-condition>: statement1 statement2 . . else: statement(s)
-
Nested Loops
A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop,
The syntax of the nested loop is as shown below:for i range(1,6): for j in range(1,i): print("A") print()