0% found this document useful (0 votes)
0 views

PDF

Spyder is an open-source IDE designed for scientific and data science programming in Python, featuring tools like an interactive console, code editor, variable explorer, and integration with scientific libraries. It allows users to manage projects, debug code, and customize the environment through plugins. Additionally, the document covers essential Python concepts such as setting the working directory, creating and executing script files, clearing the console and environment, and using comments.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

PDF

Spyder is an open-source IDE designed for scientific and data science programming in Python, featuring tools like an interactive console, code editor, variable explorer, and integration with scientific libraries. It allows users to manage projects, debug code, and customize the environment through plugins. Additionally, the document covers essential Python concepts such as setting the working directory, creating and executing script files, clearing the console and environment, and using comments.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

INTRODUCTION OF SPYDER

Spyder is an open-source integrated development environment (IDE) for scientific and data
science programming in Python. It is specifically designed for scientists, engineers, and data
analysts, providing a range of tools and features to facilitate data analysis, scientific research,
and development. Here are some key features and aspects of Spyder:

1. *Interactive Environment*: Spyder provides an interactive development environment


where you can write and execute Python code. It includes an interactive IPython console,
which is excellent for exploratory data analysis and quick testing of code snippets.
2. *Code Editor*: Spyder has a built-in code editor with features like syntax highlighting,
code completion, and code analysis to make coding in Python more efficient.
3. *Variable Explorer*: This tool allows you to view, inspect, and modify the values of
variables in your code, making it easier to understand and debug your programs.
4. *Plots and Graphs*: Spyder integrates with Matplotlib and other plotting libraries,
making it simple to create and visualize data through charts and graphs directly within
the IDE.
5. *File Explorer*: Spyder includes a file explorer that helps you navigate and manage
your project's files and directories.
6. *Project Support*: You can create and manage projects within Spyder, which helps
organize your code, data, and resources effectively.
7. *Debugger*: Spyder offers a built-in debugger with features like setting breakpoints,
stepping through code, and inspecting variables, which aids in identifying and resolving
issues in your programs.
8. *Integration with Scientific Libraries*: It comes with built-in support for popular
scientific libraries like NumPy, SciPy, Pandas, and scikit-learn, which are commonly
used in data analysis and scientific computing.
9. *Documentation Integration*: Spyder provides access to Python's documentation and
allows you to view docstrings and help information for functions and modules.
10. *Plugin System*: Spyder's functionality can be extended through a plugin system,
allowing users to customize the IDE to suit their specific needs.
11. *Version Control Integration*: Spyder supports version control systems like Git,
making it easier to manage and track changes in your code.
12. *Cross-Platform*: Spyder is cross-platform, meaning it can be used on Windows,
macOS, and Linux.

Spyder is a popular choice among data scientists and researchers because of its emphasis on
scientific computing and data analysis tools. It provides an environment that streamlines the
workflow for these tasks, making it a valuable tool for Python users in scientific and data-related
fields.
SETTING WORKING DIRECTORY

In Python, the "working directory" refers to the directory from which your Python script or
program is currently running. It serves as the base directory for relative file paths and is
important for various file operations. Here's how it works:
1. *Default Working Directory*: When you run a Python script or program, the working
directory is set to the location of the script by default.

2. *Changing the Working Directory*: You can change the working directory using the `os`
module. For example, you can use `os.chdir()` to set a new working directory:

python import os
os.chdir('/path/to/new/directory')

Example:

OS module in Python provides functions for interacting with the operating system. OS, comes
under Python’s standard utility modules. This module provides a portable way of using
operating system dependent functionality.
os.chdir() method in Python used to change the current working directory to specified path. It
takes only a single argument as new directory path.

Syntax: os.chdir(path)
Parameters:
path: A complete path of directory to be changed to new directory path.
Returns: Doesn’t return any value

Example: # Python3 program to change the


# directory of file using os.chdir() method

# import os library
import os

# change the current directory


# to specified directory
os.chdir(r"C:\Users\Gfg\Desktop\python")

print("Directory changed")

3*Relative File Paths*: The working directory is crucial when dealing with relative file paths.
If you specify a file path without an absolute path (starting from the root directory), Python will
assume it's relative to the working directory.
For example, if your script is in `/home/user/scripts/` and you use a relative path like
`"data.txt"`, Python will look for the file in `/home/user/scripts/data.txt`.

3. *Absolute Paths*: If you want to work with files in specific locations regardless of the
working directory, you should use absolute file paths, e.g., `"/home/user/documents/file.txt"`.

4. *`os.getcwd()`*: You can retrieve the current working directory using `os.getcwd()`:
python import os
current_directory =
os.getcwd()

Change current working directory with Python

The OS module in Python is used for interacting with the operating system. This module comes
under Python’s standard utility module so there is no need to install it externally. All functions in
OS module raise OSError in the case of invalid or inaccessible file names and paths, or other
arguments that have the correct type but are not accepted by the operating system.
To change the current working directory(CWD) os.chdir() method is used. This method changes
the CWD to a specified path. It only takes a single argument as a new directory path.
Note: The current working directory is the folder in which the Python script is operating.
Syntax: os.chdir(path)
Parameters:
path: A complete path of the directory to be changed to the new directory path.
Returns: Doesn’t return any value

Example # Python program to change the


# current working directory
import os
Current_directory=os.getcwd()
# Function to Get the current working directory
os.getcwd()
print("Current working directory ", Current_directory)

5 *Importance*: Understanding and managing the working directory is important, especially


when working with files, because it ensures that your program can access the right files in the
right locations.
Remember that it's good practice to be explicit about file paths by using absolute paths or
explicitly setting the working directory in your code when necessary to avoid unexpected issues
related to working directory changes.

Creating and saving script files

Creating and saving script files in Python is a fundamental aspect of writing and running Python
code. Here are the steps to create and save Python script files:
1. *Text Editor*:
To create a Python script, you need a text editor. You can use a variety of text editors, such as
Notepad (on Windows), TextEdit (on macOS), or code editors like Visual Studio Code, Sublime
Text, or PyCharm.
2*Writing Python Code*:
Open your text editor and start writing your Python code. You can write Python scripts for
various purposes, including data analysis, web development, automation, and more. Ensure your
code has the `.py` file extension, which is the standard for Python script files.
3. *Example Python Script*:
python
# This is a simple Python script
print("Hello, World!")

4*Saving the Script*: To save the script, choose "Save" or "Save As" from the text editor's
menu. Select the location where you want to save the script and provide a filename with the `.py`
extension. For example, you can save the script as `hello.py`.

5. *Choosing the Location*:


- You can save your script in any directory on your computer. It's a good practice to create a
dedicated folder or directory for your Python projects to keep your files organized.

6. *Executing the Script*:


- To run your Python script, you can open a command prompt or terminal, navigate to the
directory where your script is located, and then type `python filename.py`. In this case, you
would use `python hello.py` to run the `hello.py` script.

Alternatively, if you're using a code editor like Visual Studio Code or PyCharm, you can
simply click a "Run" or "Execute" button to run your script.
7. *Saving Changes*:
- After making changes to your script, don't forget to save it again. You can usually use the
"Save" or "Save As" option in your text editor.

8. *Version Control*:
- If you're working on larger projects or collaborating with others, consider using version
control systems like Git to track changes and manage your code efficiently.

9. *Documentation*:
- It's a good practice to add comments and docstrings to your code to explain its functionality.
This makes it easier to understand your code, especially when others need to work with it.

Remember to save your Python script files with a `.py` extension, as this tells the Python
interpreter that the file contains Python code. This extension is essential for Python to recognize
and execute the script properly.

FILE EXECUTION

File execution in Python refers to the process of running Python code that is saved in script files.
Python uses the `.py` file extension for script files, and you can execute these files in several
ways:
1. *Command Line Execution*:
Open a command prompt or terminal

Navigate to the directory where your Python script file is located using the `cd` ( change
directory) command.
Execute the script by running `python filename.py`, where `filename.py` is the name of your
script file.
Example:
shell python my_script.py
2. *Integrated Development Environments ( IDEs )*:
- Many Python IDEs, such as PyCharm, Visual Studio Code, and IDLE, provide a
convenient way to run Python scripts.
- Open the script file in your chosen IDE.
- Use the "Run" or "Execute" button within the IDE to run the script.
3. *Interactive Python Console*:
- You can open an interactive Python console (usually IPython) and execute code from a
script interactively.
- Use the `%run` magic command in IPython to execute a script.

Example:
python
%run filename.py

4. *Shebang Line ( Unix/Linux )*:


- On Unix-like systems (Linux, macOS), you can use a shebang line at
the beginning of your script to specify the Python interpreter to use.
- Make the script executable using the `chmod +x filename.py`
command. - Run the script directly with `./filename.py`

Example of a script with a shebang line: python


#!/user/bin/env python
print("Hello, World!")

5*Interactive Development Environments ( IDEs )*:


Some Python IDEs, such as Spyder, provide interactive coding environments where you can
execute parts of a script interactively.

6*Jupyter Notebooks*:
- In Jupyter notebooks, you can execute code cells individually by pressing Shift+Enter or use
the "Run All" option to execute the entire notebook.

File execution is a common way to run Python scripts for various purposes, from simple "Hello,
World!" programs to complex applications and data analysis tasks. The choice of how you
execute a Python script depends on your preferred workflow and the development environment
you are using.
CLEARING CONSOLE

Clearing the console in Python typically means removing or erasing the content displayed in the
terminal or command prompt where you're running your Python code. Clearing the console is
often used to get a clean and uncluttered output, especially when you want to present
information or results from your Python program more cleanly. How you clear the console
depends on your operating system:

1. *Windows*:
- You can use the `os` module to clear the console in Windows. Here's a simple example:

python
import os
os.system('cls')This code executes the "cls" command, which clears the console in a Windows
terminal.

2. *Linux and macOS*:


- You can use the `os` module to clear the console in Linux and macOS as well. Here's an
example:

python
import os
os.system('clear')
This code executes the "clear" command, which clears the console in a Linux or macOS
terminal.

3. *Cross-Platform*:
- If you want a cross-platform way to clear the console, you can use the `os` module to detect
your operating system and choose the appropriate command:

python import
os import
platform
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')

Please be cautious when clearing the console, especially in scripts meant for distribution or use
by others, as it can be disruptive. It's often best used sparingly, such as when you want to start
with a clean slate before displaying new information or results

CLEARING VARIABLE FROM ENVIRONMENT

In Python, you can remove variables from the environment, also known as the global namespace
or scope, by using the `del` statement. The `del` statement is used to delete a variable or a list of
variables, effectively removing them from memory. Here's how it works:
1. *Removing a Single Variable*:
To remove a single variable from the environment, use the `del` statement followed by the
variable name:

python my_variable = 42 del my_variable # Removes the


'my_variable' from the environment

*Removing Multiple Variables*:


You can also remove multiple variables in a single `del` statement by separating the variable
names with commas:

python var1 = 10 var2 = "hello" del var1, var2 # Removes both 'var1' and 'var2' from the
environment

*Removing Variables from a List*:


If you have a list of variable names to remove, you can iterate through the list and use the `del`
statement within a loop:
python variables_to_remove = ['var1', 'var2', 'var3'] for var in variables_to_remove: del
globals()[var]
This approach uses the `globals()` function to access the global namespace and delete the
specified variables.
*Be Cautious*:
Be careful when removing variables from the environment, as it can lead to unexpected behavior
in your code, especially if you remove variables that are still needed. It's usually best to remove
variables that you are certain are no longer required in your program.

*Garbage Collection*:
In most cases, you don't need to manually remove variables to free up memory. Python has
automatic memory management and a garbage collector that reclaims memory when variables
are no longer referenced.

*Namespace Cleanup*:
Removing variables from the environment can be helpful when working on interactive
environments like Jupyter notebooks, where you want to clean up the workspace after a specific
task.
Remember that excessive use of `del` to remove variables is not a common practice in regular
Python scripts or programs. It is more commonly used in interactive environments where you
want to manage your workspace or clear variables between steps of an analysis.
Clearing the environment

Clearing the environment in Python typically refers to resetting or cleaning up the entire Python
workspace or global namespace. This involves removing all variables, functions, and objects that
have been defined during the current session. Clearing the environment is often used when you
want to start with a clean slate, especially in interactive environments like Jupyter notebooks or
when dealing with long-running scripts. Here's how you can clear the environment in Python:

1. *Restarting the Python Interpreter*:


- The simplest way to clear the environment is to restart the Python interpreter. This effectively
wipes the entire workspace and starts from scratch.

2. *Exit and Re-run the Script*:


- If you're running a Python script in an interactive environment like Jupyter Notebook, you
can exit the current session and re-run the script. This will clear all the variables defined in that
session and load a fresh environment.

3. *Manually Remove Variables*:


- You can manually remove variables and objects from the environment using the `del`
statement. For example, you can use a loop to delete all variables:

python for var


in dir():
if not var.startswith("__"):
del globals()[var]

Be cautious when using this method, as it can lead to unexpected consequences if you
accidentally remove necessary variables.

4. *Using IPython Magic Commands* (for IPython environments):


- If you are working in an IPython environment (like Jupyter Notebook), you can use magic
commands to clear the environment. The `%reset` command can remove all names defined
interactively:
python
%reset - f

Use `%reset -f` with caution, as it will remove all interactive variables without confirmation.
5. *Reloading Modules*:
- If you have imported modules in your script and you want to reload them, you can use the
`importlib` module. This allows you to reload a module without clearing everything else in the
environment.

python import importlib


importlib.reload(module_name
)

Remember that clearing the environment should be done with care, as it can lead to data loss and
might not be suitable for all scenarios. It's typically used when you want to reset the environment
for a specific purpose or after a significant change in your code. Always make sure you
understand the implications of clearing the environment, especially in interactive environments
where you might lose important data.

Comments in Python

Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully.

There are three types of comments in Python:


Single line Comments
Multiline Comments
Docstring Comments
Comments in Python
In the example, it can be seen that Python Comments are ignored by the interpreter during the
execution of the program.

#samplecomet
name="abcd"
print(name)
Output: abcd

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them:

#This is a comment
print("Hello, World!")

OUTPUT
Hello, World!

Comments can be placed at the end of a line, and Python will ignore the rest of
the line:

print("Hello, World!") #This is a comment

OUTPUT
Hello, World!

A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code:

#print("Hello, World!")
print("Cheers, Mate!")
OUTPUT
Cheers, Mate!

Multiline Comments

Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")

OUTPUT

Hello, World!

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

OUTPUT
Hello, World!

Advantages of comments in Python


 Comments are generally used for the following purposes:
 Code Readability
 Explanation of the code or Metadata of the project
 Prevent execution of code
 To include resources
Variable creation

In Python, we need not declare a variable with some specific data type.

Python has no command for declaring a variable. A variable is created when some value is
assigned to it. The value assigned to a variable determines the data type of that variable.
Thus, declaring a variable in Python is very simple.

 Just name the variable

 Assign the required value to it

 The data type of the variable will be automatically determined from the value assigned,
we need not define it explicitly.

Declare an integer variable


 To declare an integer variable −
 Name the variable
 Assign an integer value to it

Example x=2
print(x)
print(type(x))

This is how you declare a integer variable in Python. Just name the variable and assign the
required value to it. The datatype is automatically determined.
Output
2
<class 'int'>

Declare a string variable

Assign a string value to the variable and it will become a string variable. In Python, the string
value cane be assigned in single quotes or double quotes.
Example
x='2'
print(x)
print(type(x))
Output
2
<class 'str'>
Declare a float variable
A float variable can be declared by assigning float value. Another way is by typecasting.
We will use both.

Example
x=2.0
print(x)
print(type(x))
y=float(2)
print(y)
print(type(y))

Output
2.0
<class 'float'>
2.0
<class 'float'>
Note: The string variable can also be declared using type casting, when using integer values as
string.

Unlike some another languages, where we can assign only the value of the defined data type to a
variable. This means an integer variable can only be assigned an integer value throughout the
program. But, in Python , the variable are not of a particular datatype. Their datatype can be
changed even after it is set.

The following example will clarify the above concept.


Example x=10
print(x)
print(type(x))
x="abc"
print(x)
print(type(x))
Output
10
<class 'int'>
abc
<class 'str'>
The variable x was of type int. Later when string value is assigned to it, it changes into a string
variable.
Python String split() Method

Split a string into a list where each word is a list item:

txt = "welcome to the jungle"

x = txt.split()

print(x)

OUTPUT
['welcome', 'to', 'the', 'jungle']

Python input() Function

Ask for the user's name and print it:

print('Enter your name:')


x = input()
print('Hello, ' + x)

OUTPUT
Enter your name:

Python type() Function

Return the type of these objects:

a = ('apple', 'banana', 'cherry')


b = "Hello World"
c = 33

x = type(a)
y = type(b)
z = type(c)
OUTPUT:
<class 'tuple'>
<class 'str'>
<class 'int'>

Python id() Function


Return the unique id of a tuple object:

x = ('apple', 'banana', 'cherry')


y = id(x)

OUTPUT
60621140

This value is the memory address of the object and will be different every time you run the
program

Definition and Usage

The id() function returns a unique id for the specified object.

All objects in Python has its own unique id.

The id is assigned to the object when it is created.

The id is the object's memory address, and will be different for each time you run the program.
(except for some object that has a constant unique id, like integers from -5 to 256)

Syntax

id(object)

Python range() Function

Create a sequence of numbers from 0 to 5, and print each item in the


sequence:

x = range(6)
for n in x:
print(n)

OUTPUT
0
1
2
3
4
5

Definition and Usage

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.

Syntax

range(start, stop, step)

Arithmetic and logical operators


In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic operations. In
this article, we will look into different types of Python operators.

OPERATORS: These are the special symbols. Eg- + , * , /, etc.

OPERAND: It is the value on which the operator is applied

Types of Operators in Python


 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Identity Operators and Membership Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers
was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.
Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

Division (float): divides the first operand by the


/ x/y
second

Division (floor): divides the first operand by the


// x // y
second

Modulus: returns the remainder when the first


% x%y
operand is divided by the second

** Power: Returns first raised to power second x ** y

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power


Here is an example showing how different Arithmetic Operators in Python work:

# Examples of Arithmetic Operator


a=9b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a – b

# Multiplication of number
mul = a * b

# Modulo of both number


mod = a % b
# Power
p = a ** b
# print results print(add)
print(sub)
print(mul)
print(mod)
print(p)

Output:
13
5
36
1
6561
Division Operators

Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or
number at the left is divided by the second number or number at the right and returns the quotient.

There are two types of division operators:

Float division

Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:
# python program to demonstrate the use of "/"
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0
5.0
-5.0
10.0
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being passed. If any of the
numbers is float, it returns output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
# python program to demonstrate the use of "//"
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-3
2.0
-3.0

Logical operators
In Python, Logical operators are used on conditional statements (either True or False).
They perform Logical AND, Logical OR and Logical NOT operations

SYNTA
OPERATOR DESCRIPTION
X

and Logical AND: True if both the operands are true x and y

Logical OR: True if either of the operands is


or x or y
true

not Logical NOT: True if operand is false not x

.
Logical AND operator
operator returns True if both the operands are True else it returns False.

Example 1
# Python program to demonstrate
# logical and operator

a = 10
b = 10
c = -10

if a > 0 and b > 0:


print("The numbers are greater than 0")

if a > 0 and b > 0 and c > 0:


print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")

Output
The numbers are greater than 0
Atleast one number is not greater than 0

Example 2
# Python program to demonstrate
# logical and operator

a = 10
b = 12
c=0

if a and b and c:
print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")
Output
Atleast one number has boolean value as False

Note: If the first expression evaluated to be false while using and operator, then the further
expressions not evaluated.

Logical OR operator
or operator returns True if either of the operands is True.

are
Example 1

# Python program to demonstrate


# logical or operator

a=
10
b=
-10
c=
0

if a > 0 or b > 0:
print("Either of the number is greater than
0") else:
print("No number is greater than 0")

if b > 0 or c > 0:
print("Either of the number is greater than
0") else:
print("No number is greater than 0")
Output
Either of the number is greater than 0
No number is greater than 0

Example 2

# Python program to demonstrate


# logical and operator

a=
10
b=
12
c=
0

if a or b or c:
print("Atleast one number has boolean value as
True") else:
print("All the numbers have boolean value as False")

Output
Atleast one number has boolean value as True

Note: If the first expression evaluated to be True while using or operator, then the further
expressions are not evaluated.

Logical not operator


not operator work with the single boolean value. If the boolean value is True it
returns False and vice-versa.

# Python program to demonstrate


# logical not operator

a = 10

if not a: print("Boolean value


of a is True")

if not (a%3 == 0 or a%5 == 0):


print("10 is not divisible by either 3 or
5") else:
print("10 is divisible by either 3 or 5")
Output
10 is divisible by either 3 or 5
Data types

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, data types are actually classes and variables are instances (object) 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)

Numeric Data Type 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.
Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.

Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or
E followed by a positive or negative integer may be appended to specify scientific
notation.

Complex Numbers – Complex number is represented by a complex class. It is


specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.

# Python program to # demonstrate numeric value


=5
print("Type of a: ", type(a))
= 5.0
print("\nType of b: ", type(b))
= 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

To define the values of various data types and check their data types we use the type()
function. Consider the following examples.

Sequence Data Type in Python

Strings in python are surrounded by either single quotation marks, or double


quotation marks.

'hello' is the same as "hello".

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

print("Hello")
print('Hello')

OUTPUT

Hello
Hello

Quotes Inside Quotes

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

OUTPUT
It's alright
He is called 'Johnny'
He is called "Johnny"

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:

Example
a = "Hello"
print(a)
OUTPUT
Hello

Multiline Strings

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

Example

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
OUTPUT

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
OUTPUT
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

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.

Example

Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello, World!"
print(a[1])
OUTPUT

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with
a for loop.

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)
OUTPUT
b
a
n
a
n
a

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.

Example

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

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


print("free" in txt)
OUTPUT
True

Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.
Python List

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

List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Create a List:

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


print(thislist)

List Items

List items are ordered, changeable, and allow duplicate values.


List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length

To determine how many items a list has, use the len() function:
Print the number of items in the list:

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


print(len(thislist))
OUTPUT
3

Python Tuples

mytuple = ("apple", "banana", "cherry")

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

output
('apple', 'banana', 'cherry')
List Items - Data Types

List items can be of any data type:

Example
String, int and boolean data types:

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


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

OUTPUT
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example

Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple Length

To determine how many items a tuple has, use the len() function:

Example

Print the number of items in the tuple:


thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
3

Tuple Items - Data Types

Tuple items can be of any data type:

Example

String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)

A tuple can contain different data types:

Example

A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

('abc', 34, True, 40, 'male')

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':

<class 'tuple'>
Example

What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))
OUTPUT

<class 'tuple'>
The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Example

Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)
OUTPUT

('apple', 'banana', 'cherry')

Python Dictionaries

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Dictionaries are written with curly brackets, and have keys and values:

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
OUTPUT
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items

Dictionary items are ordered, changeable, and do not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

Example

Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
OUTPUT
Ford

Ordered or Unordered?

When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.

Unordered means that the items do not have a defined order, you cannot refer to an item by
using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:


Example

Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
OUTPUT

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Python Sets

myset = {"apple", "banana", "cherry"}

Set

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

OUTPUT
{'banana', 'apple', 'cherry'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been
created.

Once a set is created, you cannot change its items, but you can remove items and add new
items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
OUTPUT
{'banana', 'cherry', 'apple'}

Note: The values True and 1 are considered the same value in sets, and are treated as
duplicates:

Example

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

OUTPUT
{True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets, and are treated as
duplicates:

Example

False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

OUTPUT

{False, True, 'cherry', 'apple', 'banana'}

Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

OUTPUT
3

Set Items - Data Types

Set items can be of any data type:

Example

String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
OUTPUT
{'cherry', 'apple', 'banana'}
{1, 3, 5, 7, 9}
{False, True}
Type()

From Python's perspective, sets are defined as objects with the data type
'set':

<class 'set'>

What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))

OUTPUT
<class 'set'>

The set() Constructor

It is also possible to use the set() constructor to make a set.

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-


brackets
print(thisset)
OUTPUT
{'cherry', 'banana', 'apple'}

You might also like