Python Basics to Advanced by Sardar Azeem (1)
Python Basics to Advanced by Sardar Azeem (1)
Python Basics to
Advanced
Compiled By Sardar Azeem
CONTENTS
Introduction to Programming
1.1. What is a program?
1.2. Languages of Programming a computer
1.2.1. Machine Language
1.2.2. Assembly Language
1.2.3. High Level Language
1.3. Algorithm
1.4. Compiler vs Interpreter
1.5. Introduction and Benefits of Python
1.6. History of Python
1.7. Exercise
STRINGS
4.1. Understanding Strings
4.2. Combine vs Repeat Strings
4.3. String’s Buit in Methods
(capitalize (), len (), lower (), upper (), strip (), replace (), startwith(), endswith())
4.4. Exercise
LISTS
5.1. Understanding Lists
5.2. Forward vs Backward Accessing
5.3. Changing, Removing and Adding Element
5.4. Slice a List
5.5. Membership Operator: in vs not in
5.6. Exercise
CONDITIONAL STATEMENT:
6.1. if statement
6.2. else statement
6.3. elif statement
6.4. Exercise
LOOPS:
7.1. for loop
7.2. while loop
7.3. continue vs break
7.4. Exercise
FUNCTIONS
Low-level language
The low-level language is a programming language that provides no abstraction from
the hardware, and it is represented in 0 or 1 forms, which are the machine instructions.
The languages that come under this category are the Machine level language and
Assembly language.
Machine-level language
The machine-level language is a language that consists of a set of instructions that are
in the binary form 0 or 1. As we know that computers can understand only machine
instructions, which are in binary digits, i.e., 0 and 1, so the instructions given to the
computer can be only in binary codes. Creating a program in a machine-level language
is a very difficult task as it is not easy for the programmers to write the program in
machine instructions. It is error-prone as it is not easy to understand, and its
maintenance is also very high. A machine-level language is not portable as each
computer has its machine instructions, so if we write a program in one computer will
no longer be valid in another computer.
The different processor architectures use different machine codes, for example, a
PowerPC processor contains RISC architecture, which requires different code than
intel x86 processor, which has a CISC architecture.
Assembly Language
The assembly language contains some human-readable commands such as mov, add,
sub, etc. The problems which we were facing in machine-level language are reduced to
some extent by using an extended form of machine-level language known as assembly
language. Since assembly language instructions are written in English words like mov,
add, sub, so it is easier to write and understand.
As we know that computers can only understand the machine-level instructions, so we
require a translator that converts the assembly code into machine code. The translator
used for translating the code is known as an assembler.
The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
The assembly code is not faster than machine code because the assembly language
comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero
abstraction.
High-Level Language
The high-level language is a programming language that allows a programmer to write
the programs which are independent of a particular type of computer. The high-level
languages are considered as high-level because they are closer to human languages
than machine-level languages.
When writing a program in a high-level language, then the whole attention needs to be
paid to the logic of the problem.
A compiler is required to translate a high-level language into a low-level language.
It requires the assembler to convert the It requires the compiler to convert the
assembly code into machine code. high-level language instructions into
machine code.
The machine code cannot run on all The high-level code can run all the
machines, so it is not a portable platforms, so it is a portable language.
language.
Debugging and maintenance are not Debugging and maintenance are easier in
easier in a low-level language. a high-level language.
Characteristics of an Algorithm
1. An algorithm needs specific input values. A number other than 0 may be
provided as input to an algorithm.
2. An algorithm will provide one or more outputs when it is finished.
3. Unambiguity: An ideal algorithm has specific instructions, which implies that
they should be simple and obvious.
4. Algorithms must be finite to function. In this context, "finiteness" refers to the
requirement that an algorithm has limited instructions or instructions that can
be counted.
5. Effectiveness: An algorithm should be sufficient since each instruction impacts
the whole procedure.
6. An algorithm must be language-independent, which implies that its instructions
must work the same no matter what language is used to implement them.
1. Compiler: The language processor allows the computer to run and understand the
program by reading the complete source program in one time, which is written in a
high-level language. The computer can then interpret this code because it is translated
into machine language. In modern times, to compile the program, most of the high-
level languages have toolkits or a compiler. Gcc command for C and C++ and Eclipse
for Java are two popular compilers.
Features of Python:
Python provides many useful features which make it popular and valuable from the
other programming languages.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line to
execute, while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at
a time. The advantage of being interpreted language, it makes debugging easy and
portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte code,
and any platform can use that byte code.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We
can use Python source code in another programming language as well. It can embed
other language into our code.
Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.
1) Web Applications
We can use Python to develop web
applications. Python provides many useful
frameworks, and these are given below:
1. Django and Pyramid framework
(Use for heavy applications)
2. Flask and Bottle (Micro-
framework)
3. Plone and Django CMS (Advance
Content management)
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.
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.
1. SCons is used to build control.
2. Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
3. Round or Trac for bug tracking and project management.
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.
1. Oddo is an example of the all-in-one Python-based application which offers a
range of business applications.
2. Python provides a Tryton platform which is used to develop the business
application.
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.
1. Fandango (Popular )
2. CAMVOX
3. HeeksCNC
4. AnyCAD
5. 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
1. OpenERP
2. Tryton
3. Picalo
Python provides us the feature to execute the Python statement one by one at the interactive prompt. It
is preferable in the case where we are concerned about the output of each line of our Python program.
To open the interactive mode, open the command prompt and type python
Here, we get the message "Hello World !" printed on the console.
The interpreter prompt is best to run the single-line statements of the code. However, we cannot write
the code every-time on the terminal. It is not suitable to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be executed later.
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.
Step - 4: Apart from that, we can also run the file using the operating system terminal. But we should be
aware of the path of the directory where we have saved our file.
1. Write a Program
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.
E.g.
age = "35"
Like C:\Users\SardarAzeem\Desktop>
3. We need to type the python keyword, followed by the file name and hit enter to run the Python
file.
Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit
the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to
download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking
next at each step.
Step - 1. Open PyCharm editor. Click on "Create New Project" option to create new project.
We can save the newly created project at desired memory location or can keep file location as it is but
atleast change the project default name untitled to "FirstProject" or something meaningful name.
Step - 3. Click on "File" menu and select "New". By clicking "New" option it will show various file formats.
Select the "Python File".
Step - 4. Now type the name of the Python file and click on "OK". We have written the "FirstProgram".
Step - 5. Now type the first program - print("Hello World") then click on the "Run" menu to run program.
In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores
the lines followed by a hash character. A good programmer always uses the comments to make code
under stable.
1. Single-Line Comments
Single-line remarks 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.
Example
2. Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to
create multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line
with a (#) before it will be regarded as a single-line comment.
Example
# it is a
# comment
3. Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function are called Python
docstring. It's designed to link documentation developed for Python modules, methods, classes, and
functions together. It's placed just beneath the function, module, or class to explain what they perform.
The docstring is then readily accessible in Python using the __doc__ attribute.
Example
return x + y
print( add.__doc__ )
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Variable Names
The process for declaring the valid variable has already been discussed. Variable
names can be any length can have capitalized, lowercase (start to finish, a to z), the
digit (0-9), and highlight character(_).
Example
name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
The multi-word keywords can be created by the following method.
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.
Pascal Case - It is the same as the Camel Case, but here the first word is also capital.
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
2. 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.
Example -
# 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 = 'Welcome To PICT Abbottabad'
print(x)
mainFunction()
print(x)
a=5
We did not specify the type of the variable a, which has the value five from an integer.
The Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type()
function in Python returns the type of the passed variable.
Example -
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
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 following is a list of the Python-defined data types.
➢ Numbers
➢ Sequence Type
➢ Boolean
➢ Set
➢ Dictionary
1. 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.
Example -
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Python supports three kinds of numerical data.
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.
2. Sequence Type
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.
Example - 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Example - 2
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
3. 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 (*).
Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)
4. 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.
Example:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
t[2] = "hi"
5. 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.
Example -
d = {1:'Aliya', 2:'Maryam', 3:'Saba', 4:'Aneela'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
6. 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.
Example -
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20
- (Subtraction) It is used to subtract the second operand from the first operand. If
the first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a =
(Multiplication) 20, b = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it
is an exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing
division) the two operands.
Example-
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)
2. 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.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the
second operand.
>= The condition is met if the first operand is greater than or equal to the
second operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Example -
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
3. Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left
operand.
Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left
operand, the left operand receives a changed value. For example, if a = 10,
b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assigns the modified value back to left operand. For example, if a = 20,
b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assigns the modified value back to then the left operand. For
example, if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a
= 200.
%= It divides the value of the left operand by the value of the right operand
and assigns the reminder back to the left operand. For example, if a = 20,
b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Example-
a = 32 # Initialize the value of a
4. Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators.
For example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary 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 bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward
shift of the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Example-
a=5 # initialize the value of a
b=6 # initialize the value of b
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
5. Logical Operators
The assessment of expressions to make decisions typically uses logical operators.
Operator Description
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Example -
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-
versa:',(not(a > 3 and a < 5)))
6. Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators.
Operator Description
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.
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.
Nested if Nested if statements enable us to use if ? else statement inside an
Statement outer if statement.
1. The if statement
The if statement is used to test a particular condition and if the
condition is true, it executes a block of code known as if-block.
The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
if expression:
statement
Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print("The Given number is an even number")
Example 2 : Program to print the largest of the three numbers.
# Simple Python Program to print the largest of the three numbers.
a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given a is largest");
if b>a and b>c:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given b is largest");
if c>a and c>b:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given c is largest");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
Example 1
# Python program to show how the for loop works
# Creating a sequence which is a tuple of numbers
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
# variable to store the square of the number
square = 0
# Creating an empty list
squares = []
# Creating a for loop
for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)
Using else Statement with for Loop
For loop executes the code block until the sequence element is reached. The statement
is written right after the for loop is executed after the execution of the for loop is
complete.
Only if the execution is complete does the else statement comes into play. It won't be
executed if we exit the loop or if an error is thrown.
Example -2
# Python program to show how if-else statements work
string = "Python Loop"
# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)
Now similarly, using else with for loop.
Syntax:
for value in sequence:
# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed
Example -3
# Python program to show how to use else statement with for loop
# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
# Initiating the loop
for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
print("These are the odd numbers present in the tuple")
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10)
will produce values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop,
step size). If the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object
can be characterized as being "slow." It does provide in, len, and __getitem__ actions,
but it is not an iterator.
Example- 4
# Python program to show the working of range() function
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
Now we will discuss the loop control statements in detail. We will see an example of
each control statement.
Continue Statement
It returns the control to the beginning of the loop.
Example -1
# Python program to show how the continue statement works
pass
print( 'Last Letter:', string)
Example -1
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Example -2
# Given String
str = "SARDARAZEEM"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
Example -3
str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new
string since its content cannot be partially replaced. Strings are immutable in Python.
Example -4
str = "PICT"
str[0] = "A"
print(str)
Example -5
str = "HELLO"
print(str)
str = "hello"
print(str)
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.
str1 = "SARDARAZEEM"
del str1
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either
side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of
the same string.
[] It is known as slice operator. It is used to access the sub-strings of a
particular string.
[:] It is known as range slice operator. It is used to access the characters
from the specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such as
Output:
Hello
13 \xHH Character with hex value. print("\x48\x65\x6c\x6c\x6f")
Output:
Hello
Example -9
print("C:\\Users\\SardarAzeem\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
Output:
The format() method
The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.
Example -10
# Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Python String Formatting Using % Operator
Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However,
Python provides an additional operator %, which is used as an interface between the
format specifiers and their values. In other words, we can say that it binds the format
specifiers to the values.
Example -11
Integer = 10;
Float = 1.290
String = "SardarAzeem"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ...
My value is %s"%(Integer,Float,String))
Example # 2
a = [ 1, 2, "Rahim", 3.50, "Rizwan", 5, 6 ]
b = [ 1, 2, 5, "Rashid", 3.50, "Rasheed", 6 ]
a == b
Example # 3
a = [ 1, 2, "Zia", 3.50, "Zafar", 5, 6]
b = [ 1, 2, "Zia", 3.50, "Zafar", 5, 6]
a == b
Example # 4
# list example in detail
emp = [ "Azeem", 102, "USA"]
Dep1 = [ "CS",10]
Dep2 = [ "IT",11]
HOD_CS = [ 10,"Mr.Azeem"]
HOD_IT = [11, "Mr.Aftab"]
print("printing employee data ...")
print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
print("printing departments ...")
print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0],
Dep2[1], Dep2[0], Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator
[] can be used to get to the List's components.
The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
Example # 5
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0 so its starts from the 0th element and go for index -
1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
The negative indices are counted from the right. The index -1 represents the final
element on the List's right side, followed by the index -2 for the next member on the
left, and so on, until the last element on the left is reached.
Example # 6
# negative indexing example
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and insert()
methods can also add values to a list.
Example # 7
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
The list elements can also be deleted by using the del keyword. Python also provides
us the remove() method if we do not know which element is to be deleted from the list.
Example # 8
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1 Repetition 3 Length 5 Membership
2 Concatenation 4 Iteration
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on
different occasions.
Example # 9
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Example # 10
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
3. Length
It is used to get the length of the list
Example # 11
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
4. Iteration
The for loop is used to iterate over the list elements.
Example # 12
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Example # 13
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.
Example # 14
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element i
n each iteration.
print(i)
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case, the annex()
capability can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown
from the client and print the rundown on the control center.
Example # 15
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Removing Elements from the List
The remove() function in Python can remove an element from the List. To comprehend
this idea, look at the example that follows.
Example # 16
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
1 len() 3 min()
2 max() 4 len( )
print(min(list1))
Example # 20
Create a program to eliminate the List's duplicate items.
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Example # 21
Compose a program to track down the amount of the component in the rundown.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Example # 22
Compose the program to find the rundowns comprise of somewhere around one
normal component.
Code
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
Accessing Tuple Elements
A tuple's objects can be accessed in a variety of ways.
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the
index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be
raised assuming we attempt to get to a list from the Tuple that is outside the scope of
the tuple record. An index above four will be out of range in this scenario.
Example # 4
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
Tuple Methods
The following are some examples of these methods.
Count () Method
The times the predetermined component happens in the Tuple is returned by the count
() capability of the Tuple.
Example # 9
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
The thing that must be looked for.
Start: (Optional) the index that is used to begin the final (optional) search: The most
recent index from which the search is carried out
Example # 10
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Tuple Membership Test
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Example # 11
# Python program to show how to perform membership test for tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Iterating Through a Tuple
A for loop can be used to iterate through each tuple element.
Example # 12
# Python program to show how to iterate over tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Iterating over tuple elements using a for loop
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Adding a tuple to the tuple_
print(tuple_ + (4, 5, 6))
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Example # 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda
y"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
It can contain any type of element such as integer, float, tuple etc.
Example # 3
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
Empty Set
Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an
argument to create an empty set.
Example # 4
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
set3 = set1.intersection(set2)
print(set3)
The intersection_update() method
The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
Example # 15
a = {"ali", "bilal", "jamal"}
b = {"kamran", "bilal", "sultan"}
c = {"ali”, “bilal", "zia"}
a.intersection_update(b, c)
print(a)
Difference between the two sets
The difference of two sets can be calculated by using
the subtraction (-) operator or intersection() method.
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
Dict[3] = 'Zaheer'
print("\nDictionary after adding 3 elements: ")
print(Dict)
all({1:'',2:'','':''})
sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Example # 13
dict = {5: "Ayan", 4: "Aryan", 3: "Sufyan", 6: "Zafran"}
sorted(dict)
Built-in Dictionary methods
clear()
It is mainly used to delete all the items of the dictionary.
Example # 14
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
copy()
It returns a shallow copy of the dictionary which is created.
Example #15
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
pop()
It mainly eliminates the element using the defined key.
Example # 16
# dictionary methods
get()
It is used to get the value specified for the passed key.
Example # 20
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))
update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.
Example # 21
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)
values()
It returns all the values of the dictionary with respect to given input.
Example # 22
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())
return len(string)
1) Default Arguments
A default contention is a boundary that takes as information a default esteem,
assuming that no worth is provided for the contention when the capability is called. The
following example demonstrates default arguments.
Example # 4
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function.
One more method for utilizing watchwords to summon the capability() strategy is as
per the following:
Example # 5
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
# Calling function and passing two arguments out of order, we need num1 to be 20 and
num2 to be 30
print( "Passing out of order arguments" )
function( 30, 20 )
Example # 7
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
return Statement
When a defined function is called, a return statement is written to exit the function and
return the calculated value.
Syntax:
return < expression to be returned as output >
Syntax
Lambda functions have exactly one line in their syntax:
lambda [argument1 [,argument2... .argumentn]] : expression
Example # 9
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
num = 10
number()
print( "Value of num outside the function:", num)
Factors past the capability are available inside the capability. The impact of these
variables is global. We can retrieve their values within the function, but we cannot alter
or change them. The value of a variable can be changed outside of the function if it is
declared global with the keyword global.
import turtle
Now, we can access all methods and functions.
First, we need to create a dedicated window
where we carry out each drawing command.
We can do it by initializing a variable for it.
s = turtle.getscreen()
The screen same as the canvas and turtle acts like a pen. You can move the turtle to
design the desired shape. The turtle has certain changeable features such as color,
speed, and size. It can be moved to a specific direction, and move in that direction
unless we tell it otherwise.
Programming with turtle
First, we need to learn to move the turtle all direction as we want. We can customize
the pen like turtle and its environment. Let's learn the couple of commands to perform
a few specific tasks.
Turtle can be moved in four directions.
➢ Forward
➢ Backward
➢ Left
➢ Right
Turtle motion
The turtle can move forward and backward in direction that it's facing. Let's see the
following functions.
forward(distance) or turtle.fd(distance) - It moves the turtle in the forward direction by
a certain distance. It takes one parameter distance, which can be an integer or float.
Example - 2:
import turtle
# Creating turtle screen
t = turtle.Turtle()
# To stop the screen to display
t.forward(100)
turtle.mainloop()
right(angle) or turtle.rt(angle) - This method moves the turtle right by angle units.
Example - 4:
import turtle
t.heading()
# Move turtle in opposite direction
t.right(25)
t.heading()
# To stop the screen to display
turtle.mainloop()
Example -5
import turtle
# Creating turtle screen
t = turtle.Turtle()
t.heading()
# Move turtle in left
t.left(100)
t.heading()
# To stop the screen to display
turtle.mainloop()
Example - 6
import turtle
# Creating turtle screen
t = turtle.Turtle()
# Move turtle with coordinates
t.goto(100, 80)
# To stop the screen to display
turtle.mainloop()
Drawing a Shape
We discussed the movement of the turtle. Now, we learn to move on to making actual
shape. First, we draw the polygon since they all consist of straight lines connected at
the certain angles. Let's understand the following example.
Example - 7
t.fd(100)
t.rt(90)
t.fd(100)
t.rt(90)
t.fd(100)
t.rt(90)
t.fd(100)
t.circle(50)
turtle.mainloop()
Example - 9
import turtle
# Creating turtle screen
t = turtle.Turtle()
t.dot(50)
turtle.mainloop()
import turtle
# Creating turtle screen
t = turtle.Turtle()
turtle.bgcolor("red")
turtle.mainloop()
Output:
turtle.bgpic()
turtle.bgpic(r"C:\Users\DEVANSH SHARMA\Downloads\person.jpg")
turtle.bgpic()
turtle.mainloop()
turtle.screensize()
turtle.screensize(1500,1000)
turtle.screensize()
turtle.mainloop()
Changing the Screen Title
Sometimes, we want to change the title of the screen. By default, it shows the Python
tutorial graphics. We can make it personal such as "My First Turtle
Program" or "Drawing Shape with Python". We can change the title of the screen using
the following function.
turtle.Title("Your Title")
Let's see the example.
Example - 13
import turtle
# Creating turtle
t = turtle.Turtle()
turtle.mainloop()
Output:
t.pensize(4)
t.forward(200)
turtle.mainloop()
We can also change both the pen color and turtle color if we want. We suggest
increasing the size of the turtle that changes in the color can be clearly visible. Let's
understand the following code.
Example - 15
import turtle
# Creating turtle turtle
t = turtle.Turtle()
t.pencolor("red")
t.fillcolor("orange")
t.pensize(10)
t.speed(7)
t.begin_fill()
t.circle(75)
turtle.bgcolor("blue")
t.end_fill()
turtle.mainloop()
Change the Pen Direction
By default, the turtle points to the right on the screen. Sometimes, we require moving
the turtle to the other side of the screen itself. To accomplish this, we can use
the penup() method. The pendown() function uses to start drawing again. Consider the
following example.
Example - 17
import turtle
# Creating turtle
t = turtle.Turtle()
t.fd(100)
t.rt(90)
t.penup()
t.fd(100)
t.rt(90)
t.pendown()
t.fd(100)
t.rt(90)
t.penup()
t.fd(100)
t.pendown()
turtle.mainloop()
Clearing Screen
We have covered most of designing concepts of the turtle. Sometimes, we need a clear
screen to draw more designs. We can do it using the following function.
t.clear()
The above method will clear the screen so that we can draw more designs. This
function only removes the existing designs or shapes not make any changes in
variable. The turtle will remain in the same position.
Resetting the Environment
We can also reset the current working using the reset function. It restores
the turle's setting and clears the screen. We just need to use the following function.
t.reset
All tasks will be removed and the turtle back to its home position. The default settings
of turtle, such as color, size, and shape and other features will be restored.
We have learned the basic fundamental of the turtle programming. Now, we will
discuss a few essential and advanced concepts of the turtle library.
Leaving a Stamp
We can leave the stamp of turtle on the screen. The stamp is nothing but an imprint of
the turtle. Let's understand the following example.
Example - 18
import turtle
# Creating turtle
t = turtle.Turtle()
t.stamp()
t.fd(200)
t.stamp()
t.fd(100)
turtle.mainloop()
Cloning of a turtle
Sometimes, we look for the multiple turtle to design a unique shape. It provides the
facility to clone the current working turtle into the environment and we can move both
turtle on the screen. Let's understand the following example.
Example - 19
import turtle
# Creating turtle
t = turtle.Turtle()
c = t.clone()
t.color("blue")
c.color("red")
t.circle(20)
c.circle(30)
for i in range(40, 100, 10):
c.circle(i)
turtle.mainloop()
Example - 20
import turtle
# Creating turtle
t = turtle.Turtle()
s = turtle.Screen()
s.bgcolor("black")
turtle.pensize(2)
# To design curve
def curve():
for i in range(200):
t.right(1)
t.forward(1)
t. speed(3)
t.color("red", "pink")
t.begin_fill()
t.left(140)
t.forward(111.65)
curve()
t.left(120)
curve()
t.forward(111.65)
t.end_fill()
t.hideturtle()
turtle.mainloop()
Ram 27 Mumbai
Bheem 29 Pune
Sita 23 Delhi
if __name__ == '__main__':
main()
2. Read a CSV into a Dictionary
We can also use DictReader() function to read the csv file directly into a dictionary
rather than deal with a list of individual string elements.
Example # 2
import csv
with open('python.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
print( f'\t{row[ " Name " ]} lives in {row[" City "]} department and is {row[" Age "]} y
ears old. ')
line_count += 1
Example# 3
Code
import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv(' hrdata.csv ')
writer.writeheader()
writer.writerow({'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'})
writer.writerow({'Rank': 'A', 'first_name': 'Smith',
'last_name': 'Rodriguez'})
writer.writerow({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'})
writer.writerow({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Loive'})
print("Writing complete")
Write a CSV into a Dictionary
We can also use the class DictWriter to write the CSV file directly into a dictionary.
A file named as python.csv contains the following data:
Parker, Accounting, November
Smith, IT, October
Example # 2
import csv
with open('python.csv', mode='w') as csv_file:
Example # 1
# Import the xlrd module
import xlrd
sheet.cell_value(0, 0)
Reading from the Pandas
Pandas is defined as an open-source library which is built on the top of the NumPy
library. It provides fast analysis, data cleaning, and preparation of the data for the user
and supports both xls and xlsx extensions from the URL.
It is a python package which provides a beneficial data structure called a data frame.
Example # 2
import pandas as pd
You can easily export your arrays back to a spreadsheet by using the save_as()
function and pass the array and name of the destination file to the dest_file_name
argument.
It allows us to specify the delimiter and add dest_delimiter argument. You can pass the
symbol that you want to use as a delimiter in-between " ".
Example # 1
# import xlsxwriter module
import xlsxwriter
book = xlsxwriter.Book('Example2.xlsx')
sheet = book.add_sheet()
book.close()
PyCharm
Spyder
PyDev
Atom
Wing
Jupyter Notebook
Thonny
Rodeo
Microsoft Visual Studio
Eric
PyCharm
The Jet Brains created PyCharm, a cross-platform
Integrated Development Environment (IDE) created
specifically for Python. It is the most popular IDE and is
accessible in both a premium and a free open-source
version. By handling everyday duties, a lot of time is saved.
It is a full-featured Python IDE with a wealth of features
including auto code completion, easy project navigation, quick error checking and
correction, support for remote development, database accessibility, etc.
Features
1. Smart code navigation
2. Errors Highlighting
3. Powerful debugger
Atom
Thonny
and iOS operating systems. Since its initial release in 1997, it has grown to be a well-
liked software development tool.
Features
1. Supports Python Coding in Visual studio
2. Available in both paid and free version
Eric Python