Python
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility.
- created by Guido van Rossum in 1991
- programs and scripts use
.pyfile extension - running Python scripts requires the Python runtime
Key Features
- Readable syntax
- Dynamic typing
- variable types are determined at runtime
- Extensive standard library
- provides modules and packages for a wide range of tasks
- Cross-platform compatibility
- Python code can run on various operating systems without modification
- Community and ecosystem
- large community of developers
- numerous third-party libraries and frameworks that extend capability
- Interpreted nature
- allows for quick development and testing without the need for compilation
- Versatility
- used in a wide range of applications
Python Syntax
Python syntax refers to the set of rules that dictate the combinations of symbols and keywords that form valid Python programs.
- ensure the interpreter can understand and execute code
Indentation
- python uses indentation to define blocks of code
- typically 4 spaces per indentation level
Comments
- Comments begin with
# - ignored by interpreter
- used to explain code or make notes
Variables
- used to store data
x = 10
var_name = 122Conditional Statements
if,else, andelifare used for conditional execution of code
Loops
forandwhileloops are used for iterative execution of code
Classes
- classes and objects are fundamental to object-oriented programming
class CiscoRouter:
def_init_ (self, name):
self.name = name
def config(self):
print("Here is the configuration for this router: ")print() Statement
- used to output data to the console
Functions
- defined using the
defkeyword
def greet(name):
print("Hello, " + name + "!")Importing Modules
- external functionality is added using the
importstatement
JSON (JavaScript Object Notation)
- used to send, receive, store, and share data using text
- in Python, JSON looks like a dictionary because it stores data in key-value pairs
- each key connects to a value
- Python has a built-in
jsonmodule
{
"name":"Alex",
"age":15,
"hobbies":["coding", "reading", "gaming"]
}Executing Python Code
- several ways to run a Python script
python your_script.py- if using Python3:
python3 your_script.py
- some IDEs provide a Run button to execute code directly from IDE
- e.g. PyCharm, VSCode, Jupyter Notebooks
Interactive Mode
- can run Python code interactively in a Python shell or REPL (Read-Eval-Print Loop)
- run
pythonorpython3to enter interactive mode- can then enter and execute Python code line by line
Integrated Development Environments (IDEs)
- IDEs provide a more user-friendly environment for coding, debugging, and running Python scripts
Whitespace
In Python, whitespace refers to spaces, tabs, and line breaks that are used to format and structure the code.
- Python relies on indentation to indicate the beginning and end of code
- unlike other languages that use
{}
- unlike other languages that use
- primary use of whitespace is to define the structure and hierarchy of code
Whitespace and Blocks
- Python uses indentation to define the scope of control flow statements (e.g., if, for, while, etc.) and structures like functions and classes
- Python enforces consistent level of indentation within the same block
- mixing tabs and spaces for indentation can lead to errors
- recommended to use four spaces for each indentation level
Blocks and Scope
A Block groups code associated with a control statement (e.g., if).
- block is indicated by consistent indentation and
- indentation defines block hierarchy
- don’t determine a variable’s scope
- variables defined within blocks maintain scope outside
- this contrasts with functions, objects, and modules
- Variable scope is influenced by functions, objects, and modules
- variables defined within blocks maintain scope outside
Input/Output
- input and output operations facilitate communication between the program and user
input()function is used to capture user input- prompts information
- stores it as a string
print()function displays output (as part ofstdout)format()method enhances output formatting by incorporating variables into strings- file I/O enables reading from and writing to external files using
open()and other methods
# Input example
user_name = input("Enter your name: ")
# Output example
print("Hello, {}! Welcome to Python.".format(user_name))Built-in Functions
Python built-in functions are pre-defined functions provided by the Python programming language, offering essential functionalities to perform common tasks.
- available without the need for additional imports
Common Built-in Functions
print(): outputs text or variables to the consoleinput(): reads user input from the consolelen(): determines the length of a sequence (e.g., string, list, tuple)type(): returns the type of an objectint(),float(),str(): converts values to integers, floats, or strings, respectivelymax(),min(): returns the maximum or minimum value from a sequencesum(): calculates the sum of elements in a sequenceabs(): returns the absolute value of a numberrange(): generates a sequence of numberssorted(): returns a sorted list from an iterableany(),all(): checks if any or all elements in an iterable are truemap(),filter(): applies a function to elements or filters elements based on a functionopen(),read(),write(): handles file I/O operationsdir(): lists the names in the current scope or attributes of an objecthelp(): provides help information about an object or Python
Python IDE
A Python IDE (Integrated Development Environment) is a software application that provides comprehensive tools and features to facilitate the development of Python programs.
- key features:
- code editor: A text editor designed for Python, offering features like syntax highlighting, code completion, and indentation
- debugger: Allows developers to identify and fix errors in their code by providing tools for step-by-step execution and variable inspection
- interactive shell: Enables the execution of Python code interactively, providing a command-line interface for testing snippets of code
- project management: Helps organize and manage Python projects by providing tools for creating, opening, and saving projects
- version control integration: Supports integration with version control systems like Git for efficient collaboration and code versioning
- code navigation: Facilitates easy navigation through large codebases by offering features such as code folding, code outlining, and quick navigation to definitions
- integrated documentation: Provides access to documentation for Python libraries and modules directly within the IDE
- code profiling: Allows developers to analyze code performance and identify areas for optimization