0% found this document useful (0 votes)
24 views13 pages

Python Notes

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, data science, and more. It features an easy learning curve, is dynamically typed, and supports object-oriented programming. The document also covers Python variables, keywords, command-line execution, and file handling techniques.

Uploaded by

sonasona.cs27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views13 pages

Python Notes

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, data science, and more. It features an easy learning curve, is dynamically typed, and supports object-oriented programming. The document also covers Python variables, keywords, command-line execution, and file handling techniques.

Uploaded by

sonasona.cs27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON - INTRODUCTION

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
 Data Science
 Machine learning

Key Features of Python

Python is Easy to Learn and Use: There is no prerequisite to start Python, since it is Ideal programming
language for beginners.

High Level Language: Python don’t let you worry about low-level details, like memory management,
hardware-level operations etc.

Python is Interpreted: Code is executed line-by-line directly by interpreter, and no need for separate
compilation. Which means –

We can run the same code across different platforms.

We can make the changes in code without restarting the program.

Dynamic Typed: Python is a dynamic language, meaning there are no need to explicitly declare the data
type of a variable. Type is checked during runtime, not at compile time.

Object Oriented: Python supports object-oriented concepts like classes, inheritance, and polymorphism
etc. OOPs empowers Python with modularity, reusability and easy to maintain code.

Basics:

 Python code can be written using any plain text editor that can load and save
text using either the ASCII or the UTF-8 Unicode character encoding.
 Python files normally have an extension of .py and Python GUI (Graphical User Interface)
programs usually have an extension of .pyw, particularly on Windows and Mac OS X.

First example, create a file called [Link] in a plain text editor.

#!/usr/bin/env python3

print("Hello", "World!")
 The first line is a comment. In Python, comments begin with a # and continue to the end of the
[Link] second line is blank—outside quoted strings, Python ignores blank lines,but they are
often useful to humans to break up large blocks of code to makethem easier to read. The third
line is Python code. Here, the print() function is called with two arguments, each of type str
(string; i.e., a sequence of characters).
 Each statement encountered in a .py file is executed in turn, starting with the first one and
progressing line by line.
 Python programs are executed by the Python interpreter, and normally this is done inside a
console window. On Windows the console is called “Console”, or “DOS Prompt”, or “MS-DOS
Prompt”

Python Variable :

Python Variable is containers that store values. Python is not “statically typed”. We do not need to
declare variables before using them or declare their type. A variable is created the moment we first
assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage
in a program.

Example of Variable in Python :

An Example of a Variable in Python is a representational name that serves as a pointer to an object.


Once an object is assigned to a variable, it can be referred to by that name.

Here we have stored “data" in a variable var, and when we call its name the stored information will get
printed.

Var = "data"

print(Var)

Output: data

Note:

 The value stored in a variable can be changed during program execution.


 A Variables in Python is only a name given to a memory location, all the operations done on
the variable effects that memory location.

Rules for Python variables:

 A Python variable name must start with a letter or the underscore character.
 A Python variable name cannot start with a number.
 A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
 Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
 The reserved words(keywords) in Python cannot be used to name the variable in Python.

Python Variable Types

There are two types of variables in Python - Local variable and Global variable.

Local Variable

The variables that are declared within the function and have scope within the function are
known as local variables.
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()

Output: sum is 50

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.

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 [Link] default, a variable declared outside of the
function serves as the global variable.

# Declare a variable and initialize it

x = 101

# Global variable in function

def mainFunction():
# printing a global variable

global x

print(x)

# modifying a global variable

x = 'Hello world'

print(x)

mainFunction()

print(x)

Output:

101

Hello world

Hello world

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.

Run Python Script by the 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 prompt. In this way we can run Python programs in cmd.

python [Link]

Example 2: Redirecting output


To run a Python script in Terminal from the command line, navigate to the script’s directory and use the
python script_name.py command. Redirecting output involves using the > symbol followed by a file
name to capture the script’s output in a file. For example, python script_name.py > [Link] redirects
the standard output to a file named “[Link].”

Command line programming:( no need to write)

If we need a program to be able to process text that may have been redirectedin the console or that
may be in files listed on the command line, we can usethe fileinput module’s [Link]()
function. This function iterates overall the lines redirected from the console (if any) and over all the
lines in thefiles listed on the command line, as one continuous sequence of lines. The module can
report the current filename and line number at any time [Link]() and
[Link](), and can handle some kinds of compressed files.

Two separate modules are provided for handling command-line options,


optparse and getopt.

 Parsing an argument means that how the command line argument passed by us is handled in
the program. Also, all the command line arguments or arguments which we pass inside the
command prompt shell are handled only by the main() function of the program.
 Optparse module makes easy to write command-line tools.
 It allows argument parsing in the python program.
 optparse make it easy to handle the command-line argument.
 It comes default with python.

# Importing optparse module

 import optparse

Python Reserved words :


Python programming language, there are a set of predefined words, called Keywords which along with
Identifiers will form meaningful sentences when used together. Python keywords cannot be used as the
names of variables, functions, and classes.

Keywords in Python

Python Keywords are some predefined and reserved words in Python that have special meanings.
Keywords are used to define the syntax of the coding. The keyword cannot be used as an identifier,
function, or variable name. All the keywords in Python are written in lowercase except True and False.

In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be used to
check whether a given string is a valid keyword or not.

Rules for Keywords in Python

 Python keywords cannot be used as identifiers.


 All the keywords in Python should be in lowercase except True and False.
and- This is a logical operator which returns true if both the operands are true else returns false.
or - This is also a logical operator which returns true if anyone operand is true else returns false.
not- This is again a logical operator it returns True if the operand is false else returns false.
if - This is used to make a conditional statement.
elif - Elif is a condition statement used with an if statement. The elif statement is executed if the
previous conditions were not true.
else- Else is used with if and elif conditional statements. The else block is executed if the given
condition is not true.
for- This is used to create a loop.
while- This keyword is used to create a while loop.
break- This is used to terminate the loop.
as- This is used to create an alternative.
def- It helps us to define functions.
lambda- It is used to define the anonymous function.
pass- This is a null statement which means it will do nothing.
return- It will return a value and exit the function.
True- This is a boolean value.
False- This is also a boolean value.
try- It makes a try-except statement.
with- The with keyword is used to simplify exception handling.
assert- This function is used for debugging purposes. Usually used to check the correctness of
code
class- It helps us to define a class.
continue- It continues to the next iteration of a loop
del- It deletes a reference to an object.
except - Used with exceptions, what to do when an exception occurs
finally- Finally is used with exceptions, a block of code that will be executed no matter if there is
an exception or not.
from- It is used to import specific parts of any module.
global- This declares a global variable.
import -This is used to import a module.
in- It’s used to check whether a value is present in a list, range, tuple, etc.
is- This is used to check if the two variables are equal or not.
none- This is a special constant used to denote a null value or avoid. It’s important to remember,
0, any empty container(e.g empty list) do not compute to None
nonlocal- It’s declared a non-local variable.
raise- This raises an exception.
yield- It ends a function and returns a generator.

Example

[Link]

age = 19

If age >= 18:

print ("You are eligible to vote.")

[Link] del statement is used to delete an object in Python.

name = [‘Ben’, ‘Nick’, ‘Steph’]


del name[1]
print (name)

[Link] in statement is used to check if an element is present in an iterable like list or tuple.

Input:

name = ['Ben', 'Nick', 'Steph']


exist = 'Steph' in name
print (exist)

[Link] with statement is used to simplify the exception handling.


Input:

with open("[Link]", "r") as file:

lines = [Link]()

[Link] statement is used when you can to include a specific part of the module.

from math import sqrt


print(sqrt(9))

"keyword” module in Python and then prints a list of all the keywords in Python using the “kwlist”
attribute of the “keyword” module. The “kwlist” attribute is a list of strings, where each string
represents a keyword in Python. By printing this list, we can see all the keywords that are reserved in
Python and cannot be used as identifiers.

Editing Python file:

Before performing any operation on the file like reading or writing, first, we have to open that file. For
this, we should use Python’s inbuilt function open() but at the time of opening, we have to specify the
mode, which represents the purpose of the opening file.

f = open(filename, mode)

Different modes :

r: open an existing file for a read operation.

w: open an existing file for a write operation. If the file already contains some data, then it will be
overridden but if the file is not present then it creates the file as well.

a: open an existing file for append operation. It won’t override existing data.

r+: To read and write data into the file. This mode does not override the existing data, but you

can modify the data starting from the beginning of the file.

w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file to zero
length or create a file if it does not exist.

a+: To append and read data from the file. It won’t override existing data.

Inplace editing:
Inplace editing is a technique that allows us to modify the contents of a file directly, without the need
for creating a new file or loading the entire file into memory. It offers a streamlined approach to file
manipulation by allowing us to make changes directly to the existing file, making it an efficient and
resource-friendly method.

To facilitate inplace editing in Python, the fileinput module comes into play. The fileinput module, part
of the Python standard library, provides a high-level interface for reading and writing files, streamlining
the process of inplace editing.

The Fileinput Module

The fileinput module in Python provides a convenient and efficient way to perform inplace editing of
files. It abstracts the complexities of file handling and iteration, making it easier to modify file contents
[Link] we can start using the fileinput module, we need to import it into our Python script. We
can do this by including the following import statement at the beginning of our code −

import fileinput

 To open a file for inplace editing, we use the [Link]() function. This function takes the
file path as an argument and returns an instance of the [Link] class, which provides
the necessary methods for reading and modifying the file.
 To open a file for inplace editing, we need to provide the file path as an argument to the
[Link]() function. For example, let's say we have a file named "[Link]" that we
want to edit in place. We can open it for inplace editing using the following code −eg:

with [Link]('[Link]', inplace=True) as f:

for line in f:

# Modify the line as needed

In the code above, we open the file "[Link]" for inplace editing by passing its path to the
[Link]() function. The inplace=True argument tells the fileinput module to modify the file in
place.
Suppose we have the following content in the "[Link]" file −

This is a sample file.

It contains some foo words.

Modify:

Here's an example of iterating over the lines in the file −

with [Link]('[Link]', inplace=True) as f:

for line in f:

# Modify the line as needed

For example, let's say we want to replace all occurrences of the word "foo" with "bar" in each line. We
can achieve this by using the replace() method:

with [Link]('[Link]', inplace=True) as f:

for line in f:

modified_line = [Link]('foo', 'bar')

Reversing the line

with [Link]('[Link]', inplace=True) as f:

for line in f:

modified_line = line[::-1]

print(modified_line, end='')

Output
elif elpmis elgnitedi ecnetneidni repmetS

.sdrow oof emos sniatnoc tnuocnoc sI

Converting to uppercase

with [Link]('[Link]', inplace=True) as f:

for line in f:

modified_line = [Link]()

print(modified_line, end='')

Output

THIS IS A SAMPLE FILE.

IT CONTAINS SOME FOO WORDS.

Python Comments

 Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program.
 Comments enhance the readability of the code.
 Comment can be used to identify functionality or structure the code-base.
 Comment can help understanding unusual or tricky scenarios handled by the code to prevent
accidental removal or changes.
 Comments can be used to prevent executing any specific part of your code, while making
changes or testing.
Single line comments

Single-line comments in Python have shown to be effective for providing quick descriptions for
parameters, function definitions, and expressions. A single-line comment of Python is the one that has a
hashtag # at the beginning of it and continues until the finish of the line. If the comment continues to
the next line, add a hashtag to the subsequent line and resume the conversation.

Eg :

# This code is to show an example of a single-line comment

print( 'This statement does not have a hashtag before it' )

Output:

This statement does not have a hashtag before it.

The following is the comment

# This code is to show an example of a single-line comment

The Python compiler ignores this line.

Multi-Line Comments

 Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
 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.

# Python program to demonstrate

# multiline comments

print("Multiline comments")
String literals as comments

the string literal is not assigned to any variable, it is ignored by the interpreter. To write a multi-line
comment, we can use ‘, “, or “”” quotes.

You might also like