Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Basics 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

PYTHON PROGRAMMING

1
INDEX:

S.No Topic Name Page No.


1. INTRODUCTION 1-7

2. HISTORY OF PYTHON 7-9

3. PYTHON INSTALLATION 9-11

4. PYTHON IDENTIFIERS 12-13

5. KEYWORDS 14-16

6. PYTHON-VARIABLES 16-23

7. PYTHON DATATYPES 23-28

8. PYTHON STRINGS 28-36

9. PYTHON ARRAYS 36-40

10. PYTHON IF…ELSE 40-43

11. PYTHON FUNCTIONS 44-46

12. PYTHON FILE HANDLING 47-52

NOTE: If you really strong in the basics, then remaining things will
become so easy

2
INTRODUCTION:
1. WHAT IS PYTHON ?

Python is a programming language which is object-oriented , Interpreted and also


known as High level programming Language.
Here, Immediately we may get the doubt that, what is the meaning of High level
Programming, Object-oriented and Interpreted.
Let’s know about them one by one.

-High level programming language:


High-Level means Programmer friendly Programming Language. This means we
are not required to worry about Low-levelthings[i.e.,Memory management, security,
destroying the objects and so on.]

- By simply seeing the code, programmer can understand the program. He can write the code
very easily.
- High level languages are Programmer friendly languages but not machine friendly languages

Lets take the following example:

a = 10

b = 20

c = 30

if (a<b):
print('true')

else:
print('false')

Output: true

Do you Know, if we can take this code, are in a position to understand this code?
Yes,You are not required to have any programming knowledge.
By observing the code you can say that, the output is true.
This type of thing is called as High level programming.

3
-Why Python is called as Interpreted Language?

Python is an interpreted language, which means that the code is executed line by line,
rather than being compiled all at once. This has several advantages, including faster development
time and easier debugging.

Before learning about Python interpreter and how it works, let us start by discussing what
an interpreter is.

WHAT IS INTERPRETER?

An Interpreter is a program that converts the code a developer writes into an intermediate
language, called the byte code. It converts the code line by line, one at a time. It translates
till the end and stops at that line where an error occurs, if any, making the debugging process easy.

What happens when you run a Python Code?

1. *Code Compilation*: Python code (e.g., "Hello, World!") is translated into bytecode, a
binary format.

2. *Interpreter Operation*: Python Interpreter, acting like a compiler and a virtual


machine, converts source code into bytecode.

3. *Bytecode Generation*: Source code is converted into platform-independent bytecode.

3. *Execution by PVM*: Python Virtual Machine (PVM) reads and executes the bytecode
on the hardware.

Features of Python Interpreter

The Python Interpreter is user friendly and its features include:

-Interactive editing
-Use of variables initialized in the previous prompts
-Writing the complete code in it with a readline facility.
-To get command-line editing, one can press Ctrl+P, which gives a beep
indicating the mode is activated.
4
This is how a Python interpreter works. The following chart summarizes

the above process:

Getting started with the Python Interpreter:

To open the Python interpreter, installed in the system, search in the Start menu. Then click on

Python 3.12 or other, depending on the installed version.

-In Windows, it looks like Command Prompt.

-And on Mac, it looks like a terminal.

The interpreter environment works using REPL:

-Read the lines of the code

-Evaluate and execute the code

-Print the output of the code (if any) to the console

-Looping to repeat the above process

The picture below shows the Python interpreter once opened. Small description of the Python

version, storage, etc. Along with this, you can see three arrows (>>>), called prompt. This is the

place where you have to write the code.

5
Coding in the Python Interpreter Environment

The interpreter allows interactive editing. Once you write the code, press the “Enter” button to

see the results. The below example shows a simple code of printing “Hello, World!”

“Hello, World!” program in Interpreter:


print("Hello, World!")

Output

Hello, World!

After the result, the interpreter gives another prompt for the next program/code.

You can see this in the below picture.

Finally, Let’s understand with an example on how python interpreted nature works:

x=5

6
y = 10

z=x+y

print(z)

When this code is run, the Python interpreter reads the code line by line and executes each line

in turn. It starts by assigning the value 5 to the variable ‘x’, then assigns the value 10 to the variable

‘y’. It then adds ‘x’ and ‘y’ together and stores the result in the variable ‘z’. Finally, it prints the

value of ‘z’ to the console.

If this program contained a syntax error, such as a misspelled keyword or missing parentheses,

the Python interpreter would catch the error and print a message explaining what went wrong.

This is because the interpreter checks each line of code as it is executed, rather than compiling

the entire program at once and detecting errors later.

 Python is a general-purpose language, not specialized for any specific problems, and

used to create various programmes.. For example, Desktop Applications Web Applications,

Data Science Applications, Machine learning applications and so on. Everywhere you can use Python

2. HISTORY OF PYTHON:
Python was created by Guido van Rossum, and
first released on February 20,

1991. While you may know the python as

a large snake, the name of the Python

programming language comes from an

old BBC television comedy sketch series

called Monty Python’s Flying Circus.

Python goals:

In 1999, Guido van Rossum defined his goals for Python:

 an easy and intuitive language just as powerful as those of the major competitors;
 open source, so anyone can contribute to its development;
 code that is as understandable as plain English;
 suitable for everyday tasks, allowing for short development times.

7
2. WHY LEARN PYTHON?

There are couple of factors that make Python great for learning:

 It is easy to learn – the time needed to learn Python is shorter than for many other languages; this

means that it’s possible to start the actual programming faster;

 It is easy to use for writing new software – it’s often possible to write code faster when using

Python;

 It is easy to obtain, install and deploy – Python is free, open and multiplatform; not all languages

can boast that.

3.Easyness of Python compared to other programming languages:

If you want to learn Python programming, what is the prerequisite knowledge required?

The answer for the above Question is:

Nothing is required, If you are in a position to read English statements, that is enough to learn
Python programming.

8
Just to print 'Hello World',

C language takes 5 lines of code.

Java takes 7 lines of code.

But, Python takes only one line of code.

When compared with any other prgramming language (C, C++, C## or Java),

the easiest programming langague is Python.

4. Where We Can Use Python?

We can use Python everywhere. The most common important application areas are as follows:

1. For developing Desktop Applications

The Applications which are running on a single systems (i.e., Stand alone applications)

Eg: Simple Calculator application

2. For developing Web Applications

Eg: Gmail Application, Online E-commerce applications, Facebook application,

Blog applications etc.,

3. For Network Applications

Eg: Chatting applications, Client-Server applictaions etc.,

4. For Games development

5. For Data Analysis Applications

6. For Machine Learning applications

7. For developing Artificial Intelligence, Deep Learning, Neural Network Applications

8. For IOT

9. For Data Sciene

That's why Python is called as General Purpose Programming Language.

Which Software companies are using Python

1. Internally Google and Youtube use Python coding

2. NASA and Nework Stock Exchange Applications developed by Python.

3. Top Software companies like Google, Microsoft, IBM, Yahoo, Dropbox, Netflix, Instagram

using python.

9
GETTING STARTED WITH PYTHON:
 PYTHON INSTALLATION:
-IN WINDOWS:

There are many interpreters available freely to run Python scripts like IDLE

(Integrated Development Environment) that comes bundled with the Python software downloaded

from https://www.python.org/

Step 1: Select Version of Python to Install

Step 2: Download Python Executable Installer.

On the web browser, in the official site of python (www.python.org), move to the

Download for Windows section.

All the available versions of Python will be listed. Select the version required by you

and click on Download.

On clicking download, various available executable installers shall be visible with

different operating system specifications. Choose the installer which suits your system

operating system and download the instlaller. Let suppose, we select the Windows

installer(64 bits).

Step 3: Run Executable Installer.

Run the installer. Make sure to select both the checkboxes at the bottom and then click Install Now.

On clicking the Install Now, The installation process starts.

The installation process will take few minutes to complete and once the installation is successful,

Verify the next step.

Step 4: Verify Python is installed on Windows.

To ensure if Python is succesfully installed on your system. Follow the given steps -

1. Open the command prompt.


2. Type ‘python’ and press enter.
3. The version of the python which you have installed will be displayed if the

python is successfully installed on your windows.


10
Step 5: Verify Pip was installed

Pip is a powerful package management system for Python software packages.

Thus, make sure that you have it installed.

To verify if pip was installed, follow the given steps -

1. Open the command prompt


2. Enter pip --V to check if pip was installed.
3. The following output appears if pip is installed successfully.

Now successfully installed python and pip on Windows system.

-Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and in Fedora.

To check which version of Python you're running, type "python" in the terminal emulator.
The interpreter should start and print the version number.

-macOS: Generally, Python 2.7 comes bundled with macOS. You'll have to manually install

Python 3 from http://python.org/.

11
 Python Identifiers:
What is an Identifier?

- A name in Python program is called identifier. It can be class name or function name or module name

or variable name.

-The identifier is a combination of character, digits and an underscore.


They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers
in python.
We can also use the Python string isidentifier() method to check whether a string is a valid

identifier or not.

Eg: a = 20

It is a valid Python statement. Here 'a' is an identifier.

Rules for Naming Python Identifiers

 It cannot be a reserved python keyword.


 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).

Examples for indentifiers:

12
2.Identifier should not starts with digit

3.Identifiers are case sensitive. Of course Python language itself is case sensitive language.

4.There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.

5. We cannot use reserved words as identifiers.

13
 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. There are 35 keywords in Python 3.12.

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. Furthermore, we can check the name of the
keywords in Python by using the kwlist attribute of the keyword module.

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.

List of Python Keywords

Keywords Description

This is a logical operator which returns true if both the operands are
and
true else returns false.

This is also a logical operator which returns true if anyone operand is


or
true else returns false.

This is again a logical operator it returns True if the operand is false


not
else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif


elif
statement is executed if the previous conditions were not true.

Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.

14
Keywords Description

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.

This function is used for debugging purposes. Usually used to check the
assert
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 is used with exceptions, a block of code that will be executed no


finally
matter if there is an exception or not.

from It is used to import specific parts of any module.

15
Keywords Description

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.

This is a special constant used to denote a null value or avoid. It’s


none 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.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

The following code allows you to view the complete list of Python’s keywords.
This code imports the “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.

 PYTHON VARIABLES:

Python Variables are 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

16
moment we first assign a value to it.

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.

Examples:

1. x = 5
y = "John"
print(x)
print(y)

Output: 5

John

-Variables do not need to be declared with any particular type, and can even change

type they have been set.

2. x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Output: Sally

Case-Sensitive

Variable names are case-sensitive.

3.This will create two variables:

a = 4
A = "Sally"
#A will not overwrite a

17
4.

Multi Words Variable Names

-Variable names with more than one word can be difficult to read.

-There are several techniques you can use to make them more readable:

Camel Case

-Each word, except the first, starts with a capital letter:

myVariableName = "John"

Pascal Case

-Each word starts with a capital letter:

MyVariableName = "John"

Snake Case

-Each word is separated by an underscore character:

my_variable_name = "John"

Assign Multiple Values


-Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

Output: Orange

Banana

Cherry

Note: Make sure the number of variables matches the number of values, or else you will get an error.
18
-One Value to Multiple Variables

-And you can assign the same value to multiple variables in one line:

Example

x = y = z = "Orange"
print(x)
print(y)
print(z)

Output: Orange

Orange

Orange

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values

into variables. This is called unpacking.

Example

Unpack a list:

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

Output: apple

banana

cherry

Learn more about unpacking in our Unpack Tuples topic.

Python - Output Variables


The Python print() function is often used to output variables.

Example:

19
Output: Python is awesome

-In the print() function, the output multiple variables, separated by a comma:

Example:

Output:Python is awesome

You can also use the + operator to output multiple variables:

Example:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Output: Python is awesome

Notice the space character after "Python " and "is ", without them the result

would be "Pythonisawesome".

-In the print() function, when you try to combine a string and a number with the + operator

Python will give you an error:

Example:

Output:

The best way to output multiple variables in the print() function is to separate them with

commas, which even support different data types:

20
Example:

Output: 5 John

-Python - Global Variables


Variables that are created outside of a function (as in all of the examples above) are known as

global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example:

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

Output: Python is awesome

-If you create a variable with the same name inside a function, this variable will be local,

and can only be used inside the function. The global variable with the same name will

remain as it was, global and with the original value.

Example:

Create a variable inside a function, with the same name as the global variable

21
Output:

-The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only

be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example:

If you use the global keyword, the variable belongs to the global scope:

Output:

-Also, use the global keyword if you want to change a global variable inside a function.

Example:

22
Output:

 PYTHON DATATYPES:

Python Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since everything
is an object in Python programming, Python data types are classes and variables
are instances (objects) of these classes. The following are the standard or built-in data
types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
 Binary Types( memoryview, bytearray, bytes)

23
Getting the Data Type:

You can get the data type of any object by using the type() function:

Example:

Print the data type of the variable x:

x = 5
print(type(x))

Output:

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", frozenset


"cherry"})

x = True bool

24
x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

-Numeric Data Types in Python:

The numeric data type in Python represents the data that has a numeric value.

A numeric value can be an integer, a floating number, or even a complex number.

These values are defined as Python int, Python float, and Python complex classes in Python..

-Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example:

Float
Float, or "floating point number" is a number, positive or negative, containing one or more

decimals.

Example:

25
-Complex
Complex numbers are written with a "j" as the imaginary part:

Example:

 Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:

Example:

26
Output:

Note: You cannot convert complex numbers into another number type.

-Random Number
Python does not have a random() function to make a random number, but Python has a

built-in module called random that can be used to make random numbers:

Example:

Import the random module, and display a random number between 1 and 9:

27
Output:

Note: It gives the random number between 1 and 10.

 PYTHON STRINGS:

STRING:A String is a sequence of characters enclosed within single quotes or double quotes.
In Python to represent a string, can we use a pair of single quotes ('') or double quotes ("")?

The answer is, We can use either single quotes or double quotes.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example:

Output:

-Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal

sign and the string:

-Multiline Strings
You can assign a multiline string to a variable by using three quotes:

You can use three double quotes:

a ="""Good morning!
Hope all are doing well,
Welcome to the world of python."""
print(a)

Output:
28
Or three single quotes:

a = '''Good morning!
Hope all are doing well,
Welcome to the world of python.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.

-Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes

representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a

length of 1.

Square brackets can be used to access elements of the string.

Output:

-String Length
To get the length of a string, use the len() function.

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Output:

13

-Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.

29
Example:

Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Output:

True

Use it in an if statement:

Example:

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

Output:

-Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Example:

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Output:

True

Use it in an if statement:

Example:

print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Output:

30
-Python - Slicing Strings
First, let’s know the indexing of python string:

String Slicing:
-In Python, the String Slicing method is used to access a range of characters in the String.

-Slicing in a String is done by using a Slicing operator, i.e., a colon (:).

- One thing to keep in mind while using this method is that the string returned after

slicing includes the character at the start index but not the character at the last index.

Example:

1. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5])

Output:

-Slice From the Start


By leaving out the start index, the range will start at the first character:

Example:

2.Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Output:
31
-Slice To the End
By leaving out the end index, the range will go to the end:

Example:

3.Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

Output:

-Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example:

4.Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Output:

-Python - Modify Strings

Upper Case:
Example: The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

#returns HELLO, WORLD!

32
Lower Case:
Example: The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

#returns hello, world!


Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to

remove this space.

Example:The strip() method removes any whitespace from the beginning or the

end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

- Split String
The split() method returns a list where the text between the specified separator becomes the list items.

Example:The split() method splits the string into substrings if it finds instances

of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

-Python - String Concatenation


To concatenate, or combine, two strings you can use the + operator.

Example:Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Output:

To add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)

33
Output:

-Python - Format - Strings:


String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

Example:age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the

string where the placeholders {} are:

Example:Use the format() method to insert numbers into strings:


age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Output:

The format() method takes unlimited number of arguments, and are placed

into the respective placeholders:

Example:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Output:

34
-Python - Escape Characters
To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by

double quotes:

Example: You will get an error if you use double quotes inside a string that is

surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

-Escape Characters

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

35
 PYTHON ARRAYS:
What is an Array in Python?

An array is a collection of items stored at contiguous memory locations.


The idea is to store multiple items of the same type together. This makes it easier
to calculate the position of each element by simply adding an offset to a base value,
i.e., the memory location of the first element of the array (generally denoted by
the name of the array).

Creating an Array

Array in Python can be created by importing an array module.


array(data_type, value_list) is used to create an array with data type and value list specified in
its arguments.
This code creates two arrays: one of integers and one of doubles. It then prints the
contents of each array to the console.
import array as arr
a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")

Output:

36
- Complexities for Creation of Arrays:

Time Complexity: O(1)


Auxiliary Space: O(n)

Adding Elements to a Array

Elements can be added to the Array by using built-in insert() function.


Insert is used to insert one or more data elements into an array. Based on the requirement,
a new element can be added at the beginning, end, or any given index of array. append()
is also used to add the value mentioned in its arguments at the end of the array.
The code first imports the `array` module as `arr`. Then, it creates an array of integers
named `a` with elements `[1, 2, 3]`. The array is printed before and after inserting the integer
`4` at index 1. Similarly, an array of doubles named `b` with elements `[2.5, 3.2, 3.3]` is
created and printed before and after appending the double `4.4` to the array.

Observe the code below:


import array as arr
a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in (a):
print(i, end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
print()
b.append(4.4)
print("Array after insertion : ", end=" ")
for i in (b):
print(i, end=" ")
print()
37
Output:

-Accessing Elements from the Array

In order to access the array items refer to the index number. Use the index operator [ ] to access
an item in a array. The index must be an integer.
This code demonstrates the use of indexing to access elements in arrays. The a[0]
expression accesses the first element of the array a, which is 1. The a[3] expression accesses
the fourth element of the array a, which is 4. Similarly, the b[1] expression accesses the
second element of the array b, which is 3.2, and the b[2] expression accesses the third
element of the array b, which is 3.3.

Output:

-Removing Elements from the Array

Elements can be removed from the array by using built-in remove() function but an
Error arises if element doesn’t exist in the set.
Remove() method only removes one element at a time, to remove range of elements, iterator
is used.

38
pop() function can also be used to remove and return an element from the array, but
by default it removes only the last element of the array, to remove element from a
specific position of the array, index of the element is passed as an argument to the
pop() method.

Note – Remove method in List will only remove the first occurrence of the searched
element.
This code demonstrates how to create, print, remove elements from, and access
elements of an array in Python. It imports the array module, which is used to work
with arrays. It creates an array of integers and prints the original array.
It then removes an element from the array and prints the modified array.
Finally, it removes all occurrences of a specific element from the array and prints
the updated array.

Output:

39
 Python If ... Else
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in

"if statements" and loops.

An "if statement" is written by using the if keyword.

Example:

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

Output:

-Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope

in the code. Other programming languages often use curly-brackets for this purpose.

Example:

if statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

-Elif
40
The elif keyword is Python's way of saying "if the previous conditions were not true,

then try this condition".

Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Output:

-Else
The else keyword catches anything which isn't caught by the preceding conditions.

Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Output:

You can also have an else without the elif:


Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Output:

41
-Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.

Example:One line if statement:


if a > b: print("a is greater than b")

-Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it

all on the same line:

One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

-Nested If
You can have if statements inside if statements, this is called nested if statements.

Example:

Output:

42
-The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with

no content, put in the pass statement to avoid getting an error.

Example:
a = 33
b = 200

if b > a:
pass

# having an empty if statement like this, would raise an error without the pass statement.

 Python Functions:
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example:
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example:
def my_function():
print("Hello from a function")

my_function()

 Arguments
Information can be passed into functions as arguments.
43
Arguments are specified after the function name, inside the parentheses.

You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is

called, we pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Output:

Arguments are often shortened to args in Python documentations.

 POSITIONAL ARGUMENTS:

Positional arguments are passed to a function based on their position or order.

Example:

def greet(name, greeting):


return f"{greeting}, {name}!"

print(greet("Alice", "Hello")) # Output: Hello, Alice!

 Keyword Arguments:

Keyword arguments are passed with their corresponding parameter names.

They don't rely on the order of parameters.

Example:

def greet(name, greeting):


return f"{greeting}, {name}!"

print(greet(greeting="Hello", name="Alice")) # Output: Hello, Alice!

 Default Arguments:

Default arguments have a default value assigned in the function definition.

If the value is not provided during the function call, the default value is used.
44
Example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

 Variable-Length Positional Arguments (Arbitrary Arguments):

Allows passing a variable number of positional arguments to a function.

They are collected into a tuple.

Example:

def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6

 Variable-Length Keyword Arguments (Arbitrary Keyword Arguments):

Allows passing a variable number of keyword arguments to a function.

They are collected into a dictionary.

Example:

def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

person_info(name="Alice", age=30, city="New York")


# Output:
# name: Alice
# age: 30
# city: New York

 Passing Arguments by Reference:

Mutable objects (like lists, dictionaries) are passed by reference, meaning changes made

inside the function affect the original object.

Immutable objects (like strings, integers) are passed by value, meaning

changes made inside the function do not affect the original object.

45
Example:

def modify_list(lst):
lst.append(4)

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]

 PYTHON FILE HANDLING

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

In addition you can specify if the file should be handled as binary or text mode

Syntax
To open a file for reading it is enough to specify the name of the file:

46
f = open("demofile.txt")

The code above is the same as:


f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

-Open a File on the Server


Assume we have the following file, located in the same folder as Python:

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading

the content of the file:

Example:

Output:

If the file is located in a different location, you will have to specify the file path, like this:

47
-Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how

many characters you want to return:

Example:

Output:

-Read Lines
You can return one line by using the readline() method:

Example:

Output:

By calling readline() two times, you can read the two first lines:

Example:

Output:

48
By looping through the lines of the file, you can read the whole file, line by line:

Example:

Output:

-Close Files
It is a good practice to always close the file when you are done with it.

Note: You should always close your files, in some cases, due to buffering, changes

made to a file may not show until you close the file.

 Python File Write


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

49
"w" - Write - will overwrite any existing content

Output:

Open the file "demofile3.txt" and overwrite the content:


f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())

OUTPUT:

Note: the "w" method will overwrite the entire file.

 Create a New File


To create a new file in Python, use the open() method, with one of the

following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example:
50
Result: a new empty file is created!

Create a new file if it does not exist:


f = open("myfile.txt", "w")

 Python Delete File


Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:

-Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try

to delete it:

- Delete Folder

To delete an entire folder, use the os.rmdir() method:

51
Note: You can only remove empty folders.

NOTE: The file should be saved with an extension “.py”.

52

You might also like