UNIT 1
BASICS OF PYTHON
1. PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python is used
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
2. VARIABLES
A Python variable is a reserved memory location to store values. In other words,
a variable in a python program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are
Numbers,List, Tuple, Strings, Dictionary, etc. Variables can be declared by any
name or evenalphabets like a, aa, abc, etc
Variable Naming Rules in Python
Variable name should start with letter(a-zA-Z) or underscore (_).
In variable name, no special characters allowed other than underscore (_).
Variables are case sensitive.
Variable name can have numbers but not at the beginning.
Variable name should not be a Python keyword.Keywords are also called as
reserved words.
How to Declare and use a Variable
Declare variable "a" and print it.
a=100
print (a)
Re-declare a Variable
a=100
print(a)
a=’AECS Jaduguda’
print(a)
Concatenate Variables
a='AECS'
b=1
print(a+b)
will throw error , as we cannot concatenate two different datatypes.
a='AECS'
b=1
print(a+str(b))
will display
AECS1
Delete a variable
You can also delete variable using the command del "variable name".
The below table displays the list of available assignment operators in Python
language.
3. EXECUTING PYTHON FROM COMMAND LINE
Methods to Run a Script in Python
There are various methods to Run a Python script, we will go through some generally
used methods for running a Python script:
Interactive Mode
Command Line
Text Editor (VS Code)
IDE (PyCharm)
To Execute this program, first we have to save it with the ‘.py’ extension. Then we can
execute this file with the help of the terminal, the print ( ) function is to print out any
text written within the parenthesis.
Interactively Mode
In Python Interactive Mode, you can run your script line by line in a sequence.
To enter an interactive mode, you will have to open Command Prompt on your indows
machine, type ‘python’ and press Enter.
Example1: Using Print Function
Run the following line in the interactive mode:
print('Hello World !')
Output:
Command Line
Running Python scripts on Windows via the command line provides a direct
and efficient way to execute code.
It allows for easy navigation to the script’s directory and initiation, facilitating
quick testing and automation.
Example 1:
Using Script Filename
To run Python in the terminal, store it in a ‘.py’ file in the command line, we
have to write the ‘python’ keyword before the file name in the command rompt.
In this way we can run Python programs in cmd.python hello.py
You can write your own file name in place of ‘hello.py’.
Run a Script in Python using a Text Editor
To run Python script on a text editor like VS Code (Visual Studio Code) then you will
have to do the following:
Go to the extension section or press ‘Ctrl+Shift+X’ on Windows, then search
and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs
code after that.
Now, create a new file with the name ‘hello.py’ and write the below code in
it: print('Hello World!')
Then, right-click anywhere in the text area and select the option that says
‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.
4. Run Python Scripts using an IDE
To run Python script on an IDE (Integrated Development Environment)
like PyCharm, you will have to do the following:
Create a new project.
Give a name to that project as ‘ABC’ and click on Create.
Select the root directory with the project name we specified in the last
step. Right-click on it, go to New, and to, and click on the ‘Python file’
option. Then give the name of the file as ‘hello’ (you can specify any name
as per your project requirement). This will create a ‘hello.py’ file in the
project root directory.
Now write the below Python script to print the message:
Print ('Hello World !')
To run this Python script, Right click and select the ‘Run File in Python
Console’ option. This will open a console box at the bottom and show the
output there. We can also run using the Green Play Button at the top right
corner of the IDE.
4. EDITING PYTHON FILES
Files in python can be appended to, deleted and overwritten. When writing to a
file in Python, text cannot be inserted into the middle of a file, and will require
rewriting it.
Use write ( ) or writelines ( )
Use file.seek ( )
Use file.readlines ( )
Use write ( ) or writelines ( )
When opening a file to edit with open(file, mode="r"), set mode to "w" to write
to a file or "a" to append to the end of a file. Setting mode to w will create the file
specified if it does not exist, and overwrite the file if it does exist. Use file.write(s) to
write the string s into the file and returns the number of characters written.
Use file.writelines(lines) to write multiple lines of text to a file by specifying the
strings to add as a sequence such as a list or tuple.
Use file.seek ( )
To prepend to a file, first read the file's entire content and store it in some variable.
Then rewind the file to the beginning of the file using file.seek(offset) by
setting offset to 0. Lastly, prepend the string to add to the previously stored text
from the file and write it to the file.
Use file.readlines ( )
Use open(file, mode="r") to open file in read mode. Use file.readlines() to return a
list of strings with each string as a line from file. Edit the contents of the list by
deleting or adding a line. Delete a line by removing an item from the list or add a
line by adding an item to the list. Use string.join(iterable) with the list of strings
as iterable to convert to a single string. Then write this string back to the file
with file.write(s) with s as the string.
5. RESERVED WORDS
Reserved words (also called keywords) are defined with predefined meaning and
syntax in the language. These keywords have to be used to develop programming
instructions. Reserved words can’t be used as identifiers for other programming
elements like name of variable, function etc.
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
6. BASIC SYNTAX
The Python syntax defines a set of rules that are used to create a Python Program.
The Python Programming Language Syntax has many similarities to Perl, C, and Java
Programming Languages. However, there are some definite differences between the
languages.
First Python Program
Let us execute a Python program to print "Hello, World!" in two different modes
of Python Programming.
(a) Interactive Mode Programming
(b) Script Mode Programming.
Python - Interactive Mode Programming
We can invoke a Python interpreter from command line by typing python at the
command prompt as following −
$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Here >>> denotes a Python Command Prompt where you can type your commands.
Let's type the following text at the Python prompt and press the Enter −
>>> print ("Hello, World!")
If you are running older version of Python, like Python 2.4.x, then you would need to use
print statement without parenthesis as in print "Hello, World!". However in Python
version 3.x, this produces the following result −
Hello, World!
Python - Script Mode Programming
We can invoke the Python interpreter with a script parameter which begins the
execution of the script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.
Let us write a simple Python program in a script which is simple text file. Python files
have extension .py. Type the following source code in a test.py file −
print ("Hello, World!")
We assume that you have Python interpreter path set in PATH variable. Now, let's try to
run this program as follows −
$ python3 test.py
7. COMMENTS IN PYTHON
Are the lines in the code that are ignored by the interpreter during the
execution of the program.
Syntax: #comment
Comments enhance the readability of the code and help the programmers to
understand the code very carefully. It also helps in collaborating with other
developers as adding comments makes it easier to explain the code.
Types of Comments in Python
Single line Comments
Multiline Comments
String Literals
Docstring Comments
1. Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line.
If the comment exceeds one line then put a hashtag on the next line and
continue the Python Comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the
following code snippet demonstrating single line comment
2. Multi-Line Comments
Python does not provide the option for multiline comments. However, there are
different ways through which we can write multiline comments.
A Multiline comments using multiple hashtags (#) .We can multiple
hashtags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.
3. String Literals
Python ignores the string literals that are not assigned to a variable so we can
use these string literals as Python Comments.
4.Docstring
Python docstring is the string literals with triple quotes that are appeared
right after the function.
It is used to associate documentation that has been written with Python
modules, functions, classes, and methods.
It is added right below the functions, modules, or classes to describe what
they do. In Python, the docstring is then made available via the __doc__
attribute.
8. STANDARD DATA TYPES
A variable can contain a variety of values. On the other hand, a person's id must be
stored as an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is
specified by Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
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,
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.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
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
List
Tupil
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.
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
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.
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.
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.
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.
9. PYTHON OPERATORS
Operators are used to perform operations on variables and values.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Relational operators are used for comparing the values. It either returns True or
False according to the condition. These operators are also known as Comparison
Operators.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
Greater than or equal to: True if left operand is greater than or
>= equal to the right x >= y
<= x <= y
Less than or equal to: True if left operand is less than or equal
to the right
10. LOGICAL OPERATORS IN PYTHON
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
Operator Description Syntax
Logical AND: True if both
And x and y
the operands are true
Logical OR: True if either
Or x or y
of the operands is true
Logical NOT: True if the
Not not x
operand is false
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let
shift the leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in
shift from the left, and let the rightmost bits fall off
11. BASIC INPUT OUTPUT IN PYTHON:
Input( )
The input() statement allows us to do such things in Python.
The syntax for this function is as follows:
input('prompt ')
Here, prompt is the string we want to display while taking input from the user. This is
optional.
Display Output in Python
Output( )
Python provides the print() function to display output to the standard output devices.
Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:value(s) : Any value, and as many as you like. Will be converted to
string beforeprinted
sep=’separator ’ : (Optional) Specify how to separate the objects, if there is
more than one.Default
end=’end’ : (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default
:sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed
(True) or buffered (False). Default: False
Returns : It returns output to the screen