Python – Fundamentals
Topics are discussed :
- Python Character Set,
- Python Tokens
- Keyword
- Identifier
- Rules for writing Identifier
- Do’s and Don’ts with Identifier
- Literal
- Operator
- Punctuator
- Variables – creation and assignment
- Concept of L-value and R-value
- Comments and Its uses
- Input – Output in Python
- input – Accepting data as input from the console and
- print – Displaying Output,
- Data Types
- Number : Integer, Floating-point, Complex, & Boolean
- Sequence: String, List, Tuple
- None
- Mapping data type – Dictionary
- Mutable and Immutable data types
Basic Elements of Python Program
Every Python program contains some basic elements like character set, tokens, expressions, statements, input & output.
Character Set
A valid set of characters that a language can recognize. Python support Unicode encoding standard and it has following character sets –
Letters – A to Z , a – z
Digits – 0 to 9
Special Symbol – All symbols available on the keyboard.
Whitespaces – Blank space, Tabs, Newline, Carriage return
Other Characters – All ASCII and UNICODE characters
Tokens
Lexical units or Lexical elements of a program, that is used for the building of statement and instructions in the program called Tokens.
Python has following tokens –
(i) Keyword (ii) Identifier (iii) Literals (iv) Operators (v) Punctuators
1. Keywords –
Keywords are the words that convey a special meanings to the python interpreter. These are reserved for special purpose and must not be used as identifier.
Python programming language has following keywords :
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 |
For checking / displaying the list of keywords available in Python, you have to write the following two statements:-
>>>import keyword
>>> print(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’]
“All these keywords are in small alphabets except for False, None, and True, which start with capital alphabets.
2. Identifier –
Name given to different parts of a program like variables, objects, class, method, module, list, dictionaries, is called identifier.
Identifier rules of Python –
i) Identifier is the long sequence of letters and digits. Eg. rateofinterest, listofstudents,
ii) First character must be letter; the underscore (_). E.g. _sum, sum, _1sum
iii) It is case-sensitive. E.g. Sum and sum both are different, due to case sensitivity.
iv) Must not be a keyword. if, else, break … not allowed.
v) Can’t be special character except underscore (_) e.g. ^sum, sum#.. not allowed due special character.
vi) White space not allowed. E.g. rate of interest, simple interest , not allowed due to space
Do’s :
- This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore _ .
- The name should begin with an uppercase or a lowercase alphabet or an underscore sign
- It can be of any length. However, it is preferred to keep it short and meaningful.
Don’ts :
- An identifier cannot start with a digit.
- An identifier cannot contain space.
- It should not be a keyword or reserved word.
- We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Example of Valid Identifiers –
Unit_per_day, dayofweek, stud_name, father_name, TotolaMarks, age, amount, a24, invoice_no
Example of Invalid Identifiers-
3rdGraph – Name can’t start with a digit
Roll#No – Special symbol # is not allowed
First Name – Spaces are not allowed.
D.O.B. – Special symbol . (dots) are not allowed.
while – Keyword not allowed.
3. Literals / Values –
The fixed value or data items used in the program, called Literals. Eg. “Anjeev Singh”, 38, 58690.36, True, False, None, etc.
Python allows five kinds of literals –
String Literals,
Numeric Literals,
Boolean Literals,
Special Character None,
Literal Collection
a) String Literals – The text written inside the quotes are called String literals. In python, string literals can form by enclosing text in both forms of quotes – single quotes or double quotes or triple quotes.
For example – ‘a’, “a”, ‘anjeev kumar singh’, “anjeev singh academy”.
“”” hello how are
You, I am fine,
Thank you
“””
String types in Python – Python allows two types of strings –
i) Single-line String
ii) Multi-line String
Single Line String – String written inside the single quote (‘ ‘) or double quote (“ “) are called single line string.
Multi-line String – String containing multiple lines called Multi-line string. It can be written in two ways – By adding backslash (\) and By typing text in triple quotes
For Example–
Str1 = “Hello\ # \ (backslash) not counted as character
How are you?\
I am fine.”
Str2 = “””Hello # EOL counted as character
How are You?
I am fine.”””
>>> len(str1)
27
>>> len(str2)
29
b) Numeric Literals – Literals written in the form of number, positive or negative, whole or fractional, called Numeric Literals. Python offers three types of numeric literals –
1. Integer Literals (int) – integers or ints, are positive or negative whole numbers with no decimal point. Commas cannot appear in integer constant.
- i. Decimal Integer: An integer contain digits. E.g. – 1254, +589, -987
- ii. Octal Integer : Digit starting with 0o (Zero followed letter o) e.g.0o27, 0o35
- iii. Hexadecimal Integer: Digit preceded by 0x or OX. E.g. 0x19A, 0xFA
2. Floating Point Literals (float) – real numbers, written with a decimal point with integer and fractional part.
- i. Fractional Form – A real number at least must have one digit with the decimal point, either before or after.
Example – 89.6589, 0.56898, 1.265, 25.0 - ii. Exponent Form – A real number containing two parts – mantissa and an exponent. The mantissa is followed by a letter E or e and the exponent. Mantissa may be either integer or real number while exponent must be a +ve or –ve integer.
Example – 0.125E25, -14.26e21 - iii. Complex Literals (complex) – are of the form of a + b j, where a is the real part of the number and b is the imaginary part. j represents , which is an imaginary number.
c) Boolean Literals – True (Boolean true) or False (Boolean false) is the two types of Boolean literals in python. Boolean Literals are – True and False.
d) Special Literals None – None is the special literal in Python. It is used to indicate nothing or no value or absence of value. In case of List, it is used to indicate the end of list.
- In Python, None means, “There is no useful information”, or “There is nothing here”.
- It display nothing when you write variable name, which containing None, at prompt.
Note :
(1) True , False and None are keywords, but these are start with capital letter, rest all keywords are written in small letters.
(2) Boolean literals True, False and Special literal None are built-in constants/literals of Python.
e) Literals Collections –
List – is a list of comma-separated values of any data type between square brackets. It can be changed. E.g.
p = [1, 2, 3, 4] m = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
q = [“Anjeev”, “kumar”, “singh”]
r = [“Mohit”, 102, 85.2, True]
Tuple – is a list of comma-separated values of any data type between parentheses. It cannot be changed. Eg.
p = (1, 2, 3, 4) m = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)
q = (“Anjeev”, “kumar”, “singh”)
r = (“Mohit”, 102, 85.2, ‘M’, True)
Dictionary – is an unordered set of comma-separated key : value pairs within curly braces.
rec = {‘name’:“Mohit”, ‘roll’: 102, ‘marks’ : 85.2, ‘sex’: ‘M’, ‘ip’: True}
4. Operators–
Operators are tokens that perform some operation/calculation / computation, in an expression.
- Variables and objects to which the computation or operation is applied, are called operands.
- Operators require some operands to work upon
5. Punctuators / Delimiters –
Punctuators are symbols that are used in programming languages to organize programming sentence structures.
Most common punctuators of Python programming language are:
( ) [ ] { } ’ : . ; @
Variables
The variable is an identifier whose value can change.
For example, variable age can have different values for different people.
Variable Name:
The variable name is named memory location, use to refer to the memory for processing of values. It should be unique in a program.
The value of a variable can be any data type like integer, float, string, Boolean, tuple, list, dictionary, None.
Variable Creation and Assignments
In Python, we can use an assignment statement (with = assignment operator) to create new variables and assign specific values to them.
Syntax : variableName = value
gender = ‘M’
message = “Keep Smiling”
price = 987.9
Variables must always be assigned values before they are used in the program, otherwise it will lead to an error-
NameError: name ‘variableName’ is not defined.
Wherever a variable name occurs in the program, the interpreter replaces it with the value of that particular variable.
Multiple Assignments
Python allows multiple assignment, i.e. assign either same value to multiple variables or assign different values to multiple variables.
All variables and values are separated with commas, evaluated from left to right, and assigned in the same order.
Example-
a = b = c = 20 # Assigning same value to multiple variable
a, b, c = 20, 40, 50 # Assigning different values to different variable
a, c = a+b, b+c # First expression will be evaluated then values assigned to the variable
b = 50
b, b = b+2, b+5 # b, b = 50+2, 50+5 => b,b = 52, 55
print(b) # 55
Note: Suppose you have written multiple values separated by a comma in RHS of assignment operator, but you did not write the multiple variable names in LHS, then Python creates a tuple internally,
u = 4, 5 # will not raise an error, it will create a tuple
type(u) # class ‘tuple’
print(u) # shows the result (4,5)
Lvalue and Rvalue
L-values are the objects to which we can assign a value. It can come on the LHS (left-hand side) of an assignment operator.
Rvalues are the objects/literals/expression that are assigned to Lvalues. It can come on the RHS (right hand) of an assignment operator.
Example : L-value = R-value
X = 25 #Here R-value is a literal
Y = X #Here R-value is a variable or object
Z = X + Y #Here R-value is an expression.
Dynamic Typing:
As we know, In Python, the type of variable depends upon the value assigned. Python allows a variable to point to a value of a certain type, which can be made to point to a value of a different type. This is called Dynamic Typing.
Example :
d = 35.65 # ‘d’ starts referring to a float value.
print(type(d)) # <class ‘float’>
d = ‘Anjeev’ # ‘d’ starts referring to a string value.
print(type(d)) # <class ‘str’>
type(variable or object or literal): type( ) is a built-in method in python, which returns the type of variable or object or literal.
e.g.
a = ‘hello’
type(a)
<class ‘str’>
b = 5 + 6j
type(b)
<class ‘complex’>
Click on the given link to study about –
Comments
Comments are the additional information, readable by a programmer but ignored by Python Interpreter. In Python, comments are written in three ways –
a) Full Line Comments –
Using of # symbol at the beginning of the line, i.e Physical line,
# This is a comment
# Helps in describing the purpose of the program or function or module.
b) Inline Comment –
It starts in the middle of the line i.e. Physical line.
a1 = 20 # a1 is the marks of physics , <- Inline Comments
a2 = 30 # a2 is the marks of chemistry
c) Multiline Comment-
Python allows you to write Multi-line comments or Block Comments. We can use the # symbol at the beginning of each physical line, or we can write these multiline comments inside the triple quote (either double quote or single quote).
Example – Method – 1
# Comment line 1
# Comment line2
# Comment line3
Method –
“”” Comment line 1
Comment line2 # This is also called docstring comment.
Comment line 3 “””