PYTHON NOTES
Introduction
Python is an interpreter based, dynamically typed programming language. Dynamically typed programming language means, the data type of a variable is determined at runtime, rather than explicitly declared at the compile time.
a = 10
Here, a is called variable, it just act as container and references for the value 10. When the above code is executed first value 10 get assigned to variable a. You can display the value contained in variable a using print() function. print() is the standard output function in python programming.
print(a)
we can use print to display text and value of variables in multiple way as follows:
print("value of a=",a)
In the above code, content within quote is printed as it is and value of variable to be printed is kept outside of the quote.
#simply display hello world message
print("hello world")
# display 'hello world' message
print("'hello world'")
There are multiple ways to print variable, some of the popular ways are:
#This is called as f-string, {a} act as placeholder for value of variable a
print(f'value of a={a}')
#This uses string formatter method
print('value of a={}'.format(a))
since python is dynamically typed programming language, we must have to perform type checking of a variable before performing any computations. python provides us with type() to check data type of variable.
print(type(a))
PYTHON BASIC DATA TYPES
Number
In python programming, the integer values (2,4,6,8,-10,....) have type int, while the one with fractional part (2.4,6.25,0.27,...) have type float.
x = 10
y = 2.5
print(f'value of x={x} and data type: {type(x)}')
print(f'value of y={y} and data type: {type(y)}')
Arithmetic Operators: using basic arithmetic operators, we can perform arithmetic and numerical operations on the int and float values:
+ |
ADD |
- |
SUBTRACT |
* |
MULTIPLY |
/ |
DIVIDE |
// |
FLOOR DIVISION |
% |
MODULUS: remainder of division |
** |
EXPONENT |
res = a+b
print(f'{a}+{b}={res}')
res = a-b
print(f'{a}-{b}={res}')
res = a*c
print(f'{a}+]*{c}={res}')
res = c/a
print(f'{c}/{a}={res}')
res = c//a
print(f'{c}//{a}={res}')
res = b**a
print(f'{b} to the power of {a}={res}')
Text
In python programming, text which is called a string, is a sequence of characters enclosed within a single quote(‘.......’) or double quote(“..................”). The string value is represented as str data type.
# both variable contains same value: hello world
msg1 = "hello world"
msg2 = 'hello world'
print(msg1)
print(msg2)
To quote a quote, we need to “escape” it, by preceding it with \
a = 'He doesn\'t want to out'
print(a)
b = '"Hello!" How are you?'
print(b)
Operations on string
string can be concatenated using + operator
a = 'hello'
b = 'world'
# string can be concatenated using + operator
c = a+b
print(c)
# string values next to each other is also automatically concatenated
res = 'Thank' 'you'
print(res)
Python also supports the use of * operator, by string repetitions, for 'val'*num, val is repeated num number of times.
res = 'hello'*2
print(res)
Indexing in string
In Python programming, string is a collection of characters, enclosed within quotes. Individual characters in string can be accessed by using Index, from left to right, the characters in strings are indexed from 0 to length of string-1. Note: There is no separate character data type in string, each character that we access using index is simply string of size 1. syntax to index the string to get substring is as:
variable_name[ index ]
a = "Python"
print(a[0])
print(a[1])
print(a[2])
Another utility function commonly used in python is len() its syntax is:
Signature: len(obj, /)
Docstring: Return the number of items in a container.
function len() is commonly used to calculate length or size of a given container.
# we can get number of character in the given string as:
a = "Python"
length = len(a)
print(f'Length of given string is: {length}')
# since strings are indexed from 0 to size of string-1
# we can get last character in string as:
a = "Programming"
print(a[len(a)-1])
Unlike other programming languages, python also supports negative indexing from right to left. The concept makes it very convenient for programmers to access the last character of the string.
b = "Test"
print(b[-1])
print(b[-2])
Slicing python string
In python programming, indexing is used to get single character while slicing operation can be used to get substring from the given string.The basic form of slicing operation is as:
Variable_name[start_index:end_index]
By default start_index=0 while end_index=-1
# slicing operation, for slicing operation the given string is treated as:
+----+----+-----+----+----+----+
P | y | t | h | o | n |
+----+----+-----+----+----+----+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
a = "Python"
# inorder to get substring "yth", we need to perform slicing as follows:
a[1:4]
b = "Hello"
#to get substring "Hell", we can perform operation as follows:
print(b[0:3])
print(b[:3]) # as default startindex is 0
# to get substring "llo"
print(b[2:5])
print(b[2:]) # by default last index is -1 or len(b)
InBuilt String functions
In python programming, when we create a string variable as:
a = "Python"
Here a is an object or instance of class<str>, so variable a which is an object of class str can access all the methods defined for str class. [Note: object and class is a concept related to object oriented programming. So python programming language is object oriented programming, all variables we create in python are actually instances of some classes.]
Python provides a built-in method called dir(), to list all available methods for that particular class,object or values. let us see all the method available for string class:
name = "Hello world"
print(dir(name))
The output below list all the method available for string class:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Following are most commonly used string methods:
text = "hello world"
result = text.capitalize()
print(result) # Output: Hello world
text = "Hello World"
result = text.casefold()
print(result) # Output: hello world
text = "hello"
result = text.center(10, '*')
print(result) # Output: **hello***
text = "hello world, hello universe"
count = text.count("hello")
print(count) # Output: 2
text = "hello"
encoded = text.encode('utf-8')
print(encoded) # Output: b'hello'
text = "hello world"
result = text.endswith("world")
print(result) # Output: True
text = "hello world"
index = text.find("world")
print(index) # Output: 6
name = "John"
age = 25
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # Output: My name is John and I am 25 years old.
text = "hello world"
index = text.index("world")
print(index) # Output: 6
text = "hello123"
result = text.isalnum()
print(result) # Output: True