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:
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
# import os library
import os
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()
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
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`.
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
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.
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
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 var1 = 10 var2 = "hello" del var1, var2 # Removes both 'var1' and 'var2' from the
environment
*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:
Be cautious when using this method, as it can lead to unexpected consequences if you
accidentally remove necessary variables.
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.
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.
#samplecomet
name="abcd"
print(name)
Output: abcd
Creating a Comment
#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:
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
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OUTPUT
Hello, World!
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!
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.
The data type of the variable will be automatically determined from the value assigned,
we need not define it explicitly.
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'>
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.
x = txt.split()
print(x)
OUTPUT
['welcome', 'to', 'the', 'jungle']
OUTPUT
Enter your name:
x = type(a)
y = type(b)
z = type(c)
OUTPUT:
<class 'tuple'>
<class 'str'>
<class 'int'>
OUTPUT
60621140
This value is the memory address of the object and will be different every time you run the
program
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)
x = range(6)
for n in x:
print(n)
OUTPUT
0
1
2
3
4
5
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
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 of numbers
add = a + b
# Subtraction of numbers
sub = a – b
# Multiplication of number
mul = a * b
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.
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 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
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
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
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.
a = 10
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.
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memoryview, bytearray, bytes)
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.
To define the values of various data types and check their data types we use the type()
function. Consider the following examples.
print("Hello")
print('Hello')
OUTPUT
Hello
Hello
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"
Example
a = "Hello"
print(a)
OUTPUT
Hello
Multiline Strings
Example
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.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
OUTPUT
Since strings are arrays, we can loop through the characters in a string, with
a for loop.
Example
for x in "banana":
print(x)
OUTPUT
b
a
n
a
n
a
String Length
a = "Hello, World!"
print(len(a))
OUTPUT
13
Check String
Example
There are four collection data types in the Python programming language:
List
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.
Create a List:
List Items
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:
Python Tuples
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.
Create a Tuple:
output
('apple', 'banana', 'cherry')
List Items - Data Types
Example
String, int and boolean data types:
OUTPUT
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
Tuple Items
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
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Example
Example
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
<class 'tuple'>
The tuple() Constructor
Example
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
OUTPUT
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
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.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
OUTPUT
Python Sets
Set
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.
* Note: Set items are unchangeable, but you can remove items and add new items.
Create a Set:
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.
Example
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
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
print(thisset)
OUTPUT
To determine how many items a set has, use the len() function.
Example
print(len(thisset))
OUTPUT
3
Example
From Python's perspective, sets are defined as objects with the data type
'set':
<class 'set'>
OUTPUT
<class 'set'>