Every Python program contains some basic elements like character set, tokens, expressions, statements, input & output.
Tokens
Python has following tokens –
(i) Keyword (ii) Identifier (iii) Literals (iv) Operators (v) Punctuators
1. Keywords –
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 –
Do’s :
Don’ts :
Example of Valid Identifiers –
Example of Invalid Identifiers-
3. Literals / Values –
Python allows five kinds of literals –
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 –
Integer Literals (int) – integers or ints, are positive or negative whole numbers with no decimal point. Commas cannot appear in integer constant.
a. Decimal Integer: An integer contain digits. E.g. – 1254, +589, -987
b. Octal Integer : Digit starting with 0o (Zero followed letter o) e.g.0o27, 0o35
c. Hexadecimal Integer: Digit preceded by 0x or OX. E.g. 0x19A, 0xFA
Floating Point Literals (float) – real numbers, written with a decimal point with integer and fractional part.
a. 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
b. 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
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 :
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.
Operator 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:
( ) [ ] { } ’ : . ; @ = += -= *= /= //= %= @= &= |= ^= >>= <<= **=
Variable Name:
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 to assign multiple values to multiple variables. All variables and values are separated with comma, and evaluated from left to right and assigned in 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 comma in rhs of assignment operator, but did not written multiple variable names in lhs, then Python create a tuple internally,
u = 4, 5 # will not raise an error, it will create a tuple
type(u) # class ‘tuple’
print(u) # shows result (4,5)
Example : l-value = r-value
X = 25 #Here R-value is a literals
Y = X #Here R-value is a variable or object
Z = X + Y #Here R-value is an expression.
Dynamic Typing
Example :
d = 35.65 # ‘d’ starts referring to an 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’>
20 videos|20 docs|5 tests
|
|
Explore Courses for Humanities/Arts exam
|