Introduction To Python
Introduction To Python
INTRODUCTION TO PYTHON:
python is a widely used programming language that offers several
unique features and advantages compared to languages like Java and C+
+. .
In the late 1980s, Guido van Rossum dreamed of developing Python.
The first version of Python 0.9.0 was released in 1991. Since its
release, Python started gaining popularity. According to reports, Python is
now the most popular programming language among developers because
of its high demands in the tech realm.
What is Python
Python is a general-purpose, dynamically typed, high-level, compiled and
interpreted, garbage-collected, and purely object-oriented programming
language that supports procedural, object-oriented, and functional
programming.
Python Applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing,
request, beautifulSoup, Feedparser, etc. One of Python web-framework
named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
ADVERTISEMENT
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These
applications are computer program which are used commands to execute.
This kind of application was more popular in the old generation of
computers. Python can develop this kind of application very effectively. It
is famous for having REPL, which means the Read-Eval-Print Loop that
makes it the most suitable language for the command-line applications.
Python provides many free library or module which helps to build the
command-line apps. The necessary IO libraries are used to read and
write. It helps to parse argument and create console help text out-of-the-
box. There are also advance libraries that can develop independent
console apps.
4) Software Development
Python is useful for the software development process. It works as a
support language and can be used to build control and management,
testing, etc.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and
ERP are an example of a business application. This kind of application
requires extensively, scalability and readability, and Python provides all
these features.
ADVERTISEMENT
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related
architecture. It is used to develop the 3D representation of a part of a
system. Python can create a 3D CAD application by using the following
functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP,
Tryton, Picalo, etc.
o OpenCV
o Pillow
o SimpleITK
The following window will open. Click on the Add Path check box, it will set
the Python path automatically.
Now, Select Customize installation and proceed. We can also click on the
customize installation to choose desired location and features. Other
important thing is install launcher for the all user must be checked.
Here, under the advanced options, click on the checkboxes of " Install
Python 3.11 for all users ", which is previously not checked in. This will
checks the other option " Precompile standard library " automatically. And
the location of the installation will also be changed. We can change it
later, so we leave the install location default. Then, click on the install
button to finally install.
Here, we get the message "Hello World !" printed on the console.
1. print ("hello world"); #here, we have used print() function to print the message
on the console.
To run this file named as [Link], we need to run the following command
on the terminal.
Step - 1: Open the Python interactive shell, and click "File" then
choose "New", it will open a new blank script in which we can write our
code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run
Module". It will display the output to the shell.
o We need to type the python keyword, followed by the file name and hit
enter to run the Python file.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved
it with .py extension. In the following example, we have defined the
execution of the multiple code lines using the Python script.
ADVERTISEMENT
Code:
1. name = "Andrew Venis"
2. branch = "Computer Science"
3. age = "25"
4. print("My name is: ", name, )
5. print("My age is: ", age)
Script File:
Pros and Cons of Script Mode
Advantages of running code in script mode.
ADVERTISEMENT
Python Variables
A variable is the name given to a memory location. A value-holding
Python variable is also known as an identifier.
Since Python is an infer language that is smart enough to determine the
type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can
be a group of both letters and digits.
The name of the variable should be written in lowercase. Both Rahul and
rahul are distinct variables.
Object References
When we declare a variable, it is necessary to comprehend how the
Python interpreter works. Compared to a lot of other programming
languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language;
Because of this, every data item is a part of a particular class. Think about
the accompanying model.
1. print("John")
Output:
John
The Python object makes a integer object and shows it to the control
center. We have created a string object in the print statement above.
Make use of the built-in type() function in Python to determine its type.
1. type("John")
Output:
<class 'str'>
In Python, factors are an symbolic name that is a reference or pointer to
an item. The factors are utilized to indicate objects by that name.
Let's understand the following example
1. a = 50
The variable b refers to the same object that a points to because Python does
not create another object.
Let's assign the new value to b. Now both variables will refer to the
different objects.
1. a = 50
2. b =100
Object Identity
Every object created in Python has a unique identifier. Python gives the
dependable that no two items will have a similar identifier. The object
identifier is identified using the built-in id() function. consider about the
accompanying model.
1. a = 50
2. b=a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id()
function that we used to check returned the same number. We reassign a
to 500; The new object identifier was then mentioned.
Variable Names.
Rules for Naming Python Variables
1. Constant and variable names should have a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
snake_case
MACRO_CASE
camelCase
CapWords
2. Create a name that makes sense. For example, vowel makes more sense than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:
my_name
current_salary
5. Python is case-sensitive. So num and Num are different variables. For example,
var num = 5
var Num = 55
print(num) # 5
print(Num) # 55
6. Avoid using keywords like if, True, class, etc. as variable names.
4. print(name)
5. print(age)
6. print(marks)
Output:
Devansh
20
80.5
Consider the following valid variables name.
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
[Link](name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name,
na56me)
Output:
A B C D E D E F G F I
We have declared a few valid variable names in the preceding example,
such as name, _name_, and so on. However, this is not recommended
because it may cause confusion when we attempt to read code. To make
the code easier to read, the name of the variable ought to be descriptive.
The multi-word keywords can be created by the following method.
o Camel Case - In the camel case, each word or abbreviation in the middle
of begins with a capital letter. There is no intervention of whitespace. For
example - nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is
also capital. For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore.
For example - name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple
variables in a single statement, is a feature of Python.
We can apply different tasks in two ways, either by relegating a solitary
worth to various factors or doling out numerous qualities to different
factors. Take a look at the following example.
1. Assigning single value to multiple variables
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
The variables that are declared within the function and have scope within
the function are known as local variables. Let's examine the following
illustration.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
[Link]()
Output:
The sum is: 50
Explanation:
We declared the function add() and assigned a few variables to it in the
code above. These factors will be alluded to as the neighborhood factors
which have scope just inside the capability. We get the error that follows
if we attempt to use them outside of the function.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw
the NameError.
Global Variables
Global variables can be utilized all through the program, and its extension
is in the whole program. Global variables can be used inside or outside
the function.
By default, a variable declared outside of the function serves as the global
variable. Python gives the worldwide catchphrase to utilize worldwide
variable inside the capability. The function treats it as a local variable if
we don't use the global keyword. Let's examine the following illustration.
Example -
1. # Declare a variable and initialize it
2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
[Link]()
[Link](x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to
it. We then created a function and used the global keyword to access the
declared variable within the function. We can now alter its value. After
that, we gave the variable x a new string value and then called the
function and printed x, which displayed the new value.
=
Delete a variable
We can delete the variable using the del keyword. The syntax is given
below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We
deleted variable x, and print it, we get the error "variable x is not
defined". The variable x will no longer use in future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/[Link]",
line 389, in
print(x)
NameError: name 'x' is not defined
The data types will be briefly discussed in this tutorial section. We will talk about every
single one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.
ADVERTISEMENT
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20,
- 150, and so on. An integer can be any length you want in Python. Its
worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can
be accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy,
where x and y signify the genuine and non-existent parts separately. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a
repetition operator.
The Python string is demonstrated in the following example.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string
Look at the following illustration of string handling.
Example - 2
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Look at the following example.
Example:
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetition using * operator
18. print (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Let's look at a straightforward tuple in action.
Example:
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last):
File "[Link]", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Look at the following example.
ADVERTISEMENT
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
Look at the following example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used
to create the set. It can contain different kinds of values.
Look at the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. [Link](10)
12. print(set2)
13.
14. #Removing element from the set
15. [Link](2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
Python Keywords
Every scripting language has designated words or keywords, with
particular definitions and usage guidelines. Python is no exception. The
fundamental constituent elements of any Python program are Python
keywords.
This tutorial will give you a basic overview of all Python keywords and a
detailed discussion of some important keywords that are frequently used.
A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
[Link]("a:", a)
[Link]("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
V. Literal Collections.
Python provides the four types of literal collection such as List literals,
Tuple literals, Dict literals, and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e.,
modifiable.
o The values stored in List are separated by comma(,) and enclosed within
square brackets([]). We can store different types of data in a List.
Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
o Python tuple is a collection of different data-type. It is immutable which
means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is separated by the
comma(,).
Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).
Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a
symbol that performs a specific operation between two operands,
according to one definition. Operators serve as the foundation upon which
logic is constructed in a program in a particular programming language. In
every programming language, some operators perform several tasks.
Same as other languages, Python also has some operators, and these are
given below -
ADVERTISEMENT
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular
operation. There are many arithmetic operators. It includes the exponent
(**) operator as well as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder), and // (floor division) 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
- It is used to subtract the second operand from the first operand. If the first op
(Subtraction) than the second operand, the value results negative. For example, if a = 20, b
= 15
/ (divide) It returns the quotient after dividing the first operand by the second operand.
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
(Multiplicatio 80
n)
% (reminder) It returns the reminder after dividing the first operand by the second operand.
if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an expone
// (Floor It provides the quotient's floor value, which is obtained by dividing the two ope
division)
Program Code:
Now we give code examples of arithmetic operators in Python. The code is
given below -
1. a = 32 # Initialize the value of a
2. b=6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
9. print('Floor division of two numbers:',a//b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison
operators compare the values of the two operands and return a true or
false Boolean value in accordance. The example of comparison operators
are ==, !=, <=, >=, >, <. In the below table, we explain the works of the
operators.
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 ope
>= The condition is met if the first operand is greater than or equal to the second ope
> If the first operand is greater than the second operand, then the condition become
< If the first operand is less than the second operand, then the condition becomes tr
Program Code:
Now we give code examples of Comparison operators in Python. The code
is given below -
1. a = 32 # Initialize the value of a
2. b = 6 # Initialize the value of b
3. print('Two numbers are equal or not:',a==b)
4. print('Two numbers are not equal or not:',a!=b)
5. print('a is less than or equal to b:',a<=b)
6. print('a is greater than or equal to b:',a>=b)
7. print('a is greater b:',a>b)
8. print('a is less than b:',a<b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
Assignment Operators
Using the assignment operators, the right expression's value is assigned
to the left operand. There are some examples of assignment operators
like =, +=, -=, *=, %=, **=, //=. In the below table, we explain the works
of the operators.
Operato Description
r
+= By multiplying the value of the right operand by the value of the left operand, the
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal
and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will b
= a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
modified value back to then the left operand. For example, if a = 10, b = 20 => a
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
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will b
= 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 = 1
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1
Program Code:
Now we give code examples of Assignment operators in Python. The code
is given below -
1. a = 32 # Initialize the value of a
2. b=6 # Initialize the value of b
3. print('a=b:', a==b)
4. print('a+=b:', a+b)
5. print('a-=b:', a-b)
6. print('a*=b:', a*b)
7. print('a%=b:', a%b)
8. print('a**=b:', a**b)
9. print('a//=b:', a//b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise
operators. The examples of Bitwise operators are bitwise OR (|), bitwise
AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>). Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
[Link], Binary of x = 0101
11. Binary of y = 1000
[Link] OR = 1101
13.8 4 2 1
14.1 1 0 1 = 8 + 4 + 1 = 13
15.
[Link] AND = 0000
17.0000 = 0
18.
[Link] XOR = 1101
20.8 4 2 1
21.1 1 0 1 = 8 + 4 + 1 = 13
[Link] of x = ~x = (-x) - 1 = (-5) - 1 = -6
23.~x = -6
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location are
and) copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next
and vice versa.
<< (left The number of bits in the right operand is multiplied by the leftward shift of the
shift) left operand.
>> (right The left operand is moved right by the number of bits present in the right operand
shift)
Program Code:
Now we give code examples of Bitwise operators in Python. The code is
given below -
1. a=5 # initialize the value of a
2. b=6 # initialize the value of b
3. print('a&b:', a&b)
4. print('a|b:', a|b)
5. print('a^b:', a^b)
6. print('~a:', ~a)
7. print('a<<b:', a<<b)
8. print('a>>b:', a>>b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
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.
Operato Description
r
and The condition will also be true if the expression is true. If the two expressions a a
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 express
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.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is
given below -
1. a=5 # initialize the value of a
2. print(Is this statement true?:',a > 3 and a < 5)
3. print('Any one statement is true?:',a > 3 or a < 5)
4. print('Each statement is true then return False and vice-versa:',(not(a > 3 and
a < 5)))
Output:
Now we give code examples of Bitwise operators in Python. The code is
given below -
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True
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 tru
or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true (
dictionary).
Program Code:
Now we give code examples of Membership operators in Python. The code
is given below -
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Is value Present? True
Is value not Present? True
Identity Operators
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
Program Code:
Now we give code examples of Identity operators in Python. The code is
given below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c = a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
True
False
False
True
True
False
Operator Precedence
The order in which the operators are examined is crucial to understand
since it tells us which operator needs to be considered first. Below is a list
of the Python operators' precedence tables.
Operator Description
* / % // the division of the floor, the modules, the division, and the
multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater
than, greater then equal to).
<> == != Equality operators.
Example
#This is a comment
print("Hello, World!")
OUTPUT
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest
of the line:
Example
print("Hello, World!") #This is a comment
OUTPUT
Hello, World!
A comment does not have to be text that explains the code, it can also be
used to prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
OUTPUT
Cheers, Mate!
Multiline Comments
Python does not really have a syntax for multiline comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OUTPUT:
Hello, World!
Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
OUTPUT:
Hello, World!
Statement Description
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition to
be checked. If the condition provided in the if statement is false, then
the else statement will be executed.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't
allow the use of parentheses for the block level code. In Python,
indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the
same level indentation. We will see how the actual indentation takes
place in decision making and other stuff in python.
Example 1
1. # Simple Python program to understand the if statement
2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the
block
6. print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
If the condition is true, then the if-block is executed. Otherwise, the else-
block is executed.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example 1
Example 2
1. # Simple Python program to understand elif statement
2. marks = int(input("Enter marks? "))
3. # Here, we are taking an integer marks and taking input dynamically
4. if marks > 85 and marks <= 100:
5. # Here, we are checking the condition. If the condition is true, we will enter the
block
6. print("Congrats ! you scored grade A ...")
7. elif marks > 60 and marks <= 85:
8. # Here, we are checking the condition. If the condition is true, we will enter the
block
9. print("You scored grade B + ...")
[Link] marks > 40 and marks <= 60:
11.# Here, we are checking the condition. If the condition is true, we will enter the
block
12. print("You scored grade B ...")
[Link] (marks > 30 and marks <= 40):
14.# Here, we are checking the condition. If the condition is true, we will enter the
block
15. print("You scored grade C ...")
[Link]:
17. print("Sorry you are fail ?")
Output:
Enter the marks? 89
Congrats ! you scored grade A ...
As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Python Loops
The following loops are available in Python to fulfil the looping needs.
Python offers 3 choices for running the loops. The basic functionality of all
the techniques is the same, although the syntax and the amount of time
required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a
loop command.
The following sorts of loops are available in the Python programming
language.
2 For loop This type of loop executes a code block multiple times and abbrevia
that manages the loop variable.
1 Break statement This command terminates the loop's execution and transfers th
control to the statement next to the loop.
2 Continue This command skips the current iteration of the loop. The
statement following the continue statement are not executed once
interpreter reaches the continue statement.
Code
1. # Python program to show how the for loop works
2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
[Link] = []
11.
12.# Creating a for loop
[Link] num in numbers:
14. square = num ** 2
15. [Link](square)
[Link]("The list of squares is", squares)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1,
81, 4]
L
If block
If block
p
Now similarly, using else with for loop.
Syntax:
1. for value in sequence:
2. # executes the statements until sequences are exhausted
3. else:
4. # executes these statements when for loop is completed
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10.# giving an else statement
[Link]:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
While Loop
While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is
executed once the condition changes to false.
Syntax of the while loop is:
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code
block. These statements are intended with the same number of spaces.
Python groups statements together with indentation.
Code
1. # Python program to show how to use a while loop
2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6.
7. print("Python Loops")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
1. # Python program to show how the break statement works
2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.
Code
1. # Python program to show how the pass statement works
2. for a string in "Python Loops":
3. pass
4. print( 'Last Letter:', string)
Output:
Last Letter: s
1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over list
[Link] num in range( len(numbers) ):
11.
12.sum_ = sum_ + numbers[num] ** 2
13.
[Link]("The sum of squares is: ", sum_)
Output:
The sum of squares is: 774
The len() worked in a technique that profits the complete number of
things in the rundown or tuple, and the implicit capability range(), which
returns the specific grouping to emphasize over, proved helpful here.
Example
Program code 1:
Now we give code examples of while loops in Python for printing numbers
from 1 to 10. The code is given below -
1. i=1
2. while i<=10:
3. print(i, end=' ')
4. i+=1
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
1 2 3 4 5 6 7 8 9 10
Program Code 2:
Now we give code examples of while loops in Python for Printing those
numbers divisible by either 5 or 7 within 1 to 50 using a while loop. The
code is given below -
1. i=1
2. while i<51:
3. if i%5 == 0 or i%7==0 :
4. print(i, end=' ')
5. i+=1
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
Program Code:
Now we give code examples of while loops in Python, the sum of squares
of the first 15 natural numbers using a while loop. The code is given below
-
1. # Python program example to show the use of while loop
2.
3. num = 15
4.
5. # initializing summation and a counter for iteration
6. summation = 0
7. c = 1
8.
9. while c <= num: # specifying the condition of the loop
10. # begining the code block
11. summation = c**2 + summation
12. c = c + 1 # incrementing the counter
13.
14.# print the final sum
[Link]("The sum of squares is", summation)
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
The sum of squares is 1240
Provided that our counter parameter i gives boolean true for the
condition, i less than or equal to num, the loop repeatedly executes the
code block i number of times.
Next is a crucial point (which is mostly forgotten). We have to increment
the counter parameter's value in the loop's statements. If we don't, our
while loop will execute itself indefinitely (a never-ending loop).
Finally, we print the result using the print statement.
Program Code:
Now we give code examples of while loops in Python for a number is
Armstrong number or not. The code is given below -
1. n = int(input())
2. n1=str(n)
3. l=len(n1)
4. temp=n
5. s=0
6. while n!=0:
7. r=n%10
8. s=s+(r**1)
9. n=n//10
[Link] s==temp:
11. print("It is an Armstrong number")
[Link]:
13. print("It is not an Armstrong number ")
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
342
It is not an Armstrong number
1. Keyword:
2. pass
Ordinarily, we use it as a perspective for what's to come.
Let's say we have an if-else statement or loop that we want to fill in the
future but cannot. An empty body for the pass keyword would be
grammatically incorrect. A mistake would be shown by the Python
translator proposing to occupy the space. As a result, we use the pass
statement to create a code block that does nothing.
An Illustration of the Pass Statement
Code
1. # Python program to show how to use a pass statement in a for loop
2. '''''pass acts as a placeholder. We can fill this place later on'''
3. sequence = {"Python", "Pass", "Statement", "Placeholder"}
4. for value in sequence:
5. if value == "Pass":
6. pass # leaving an empty if block using the pass keyword
7. else:
8. print("Not reached pass keyword: ", value)
Output:
Not reached pass keyword: Python
Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
The same thing is also possible to create an empty function or a class.
Code
1. # Python program to show how to create an empty function and an empty class
2.
3. # Empty function:
4. def empty():
5. pass
6.
7. # Empty class
8. class Empty:
9. pass