Basic Python
Basic Python
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991. Python is an open-source programming language, having features like object-oriented,
interpreted and high-level too.
It is used for:
software development,
mathematics,
system scripting.
Python Variables
Variables are containers for storing data values.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
Variable names are case-sensitive (age, Age and AGE are three different variables)
x=5
y = "John"
print(x)
print(y)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float
literals Casting
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
Consider the following table for a detailed explanation of arithmetic operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less than
the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a
= 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80
(Multiplication)
% (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a
= 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two operands.
division)
Comparison operator
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
Operator Description
+= By multiplying the value of the right operand by the value of the left operand, the left operand receives
a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a =
30.
-= It decreases the value of the left operand by the value of the right operand and assigns the modified
value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the modified
value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b
and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the reminder back
to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore,
a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
print('a=b:', a=b)
print('a+=b:', a+=b)
print('a-=b:', a-=b)
print('a*=b:', a*=b)
print('a%=b:', a%=b)
print('a**=b:', a**=b)
print('a//=b:', a//=b)
Bitwise Operators
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice
versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of the left
operand.
>> (right shift) The left operand is moved right by the number of bits present in the right operand.
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<1)
print('a>>b:', a>>1)
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of
logical operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend
upon the second one. In the case of logical OR, if the first one is 1, it does not depend on the second
one. Python supports the following logical operators. In the below table, we explain the works of the
logical operators.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a and b are the same,
then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b
must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Membership Operators
The membership of a value inside a Python data structure can be verified using Python membership
operators. The result is true if the value is in the data structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be true (list, tuple, or
dictionary).
not in If the first operand is not present in the second operand, the evaluation is true (list, tuple, or dictionary).
x = ["Rose", "Lotus"]
Identity operator
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to be true.
x = ["apple", "banana"]
print("banana" in x) //true
x = ["apple", "banana"]
print(thislist)
S.no MethodDescription
Python Tuples
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.
print(thistuple)
Tuple Methods
index() Searches the tuple for a specified value and returns the position of where it was found
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.
print(thisset)
Set Methods
Python has a set of built-in methods that you can use on sets.
MethodDescription
intersection_update() Removes the items in this set that are not present in other, specified set(s)
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
Conditional Statements
Python if statement :
# python program to illustrate If statement
i = 10
if (i > 15):
if (i < 15):
print("i'm in if Block")
else:
i = 10
if (i == 10):
# First if statement
if (i < 15):
# it is true
if (i < 12):
else:
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
i=1
while i < 6:
print(i)
i += 1
for i in l:
print(i)
print(i)
Python Functions
def my_function():
my_function()
my_function("Emil", "Refsnes")
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
class Person:
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Exception Handling
The try block lets you test a block of code for errors.
try:
a = 10
b=0
print(a/b)
except Exception as e: