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 .py file 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 = 122

Conditional Statements

  • if, else, and elif are used for conditional execution of code

Loops

  • for and while loops 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: ")
  • used to output data to the console

Functions

  • defined using the def keyword
def greet(name):
	print("Hello, " + name + "!")

Importing Modules

  • external functionality is added using the import statement

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 json module
{
	"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 python or python3 to 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 {}
  • 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

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 of stdout)
  • 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 console
  • input():  reads user input from the console
  • len():  determines the length of a sequence (e.g., string, list, tuple)
  • type():  returns the type of an object
  • int()float()str():  converts values to integers, floats, or strings, respectively
  • max()min():  returns the maximum or minimum value from a sequence
  • sum():  calculates the sum of elements in a sequence
  • abs():  returns the absolute value of a number
  • range():  generates a sequence of numbers
  • sorted():  returns a sorted list from an iterable
  • any()all():  checks if any or all elements in an iterable are true
  • map()filter():  applies a function to elements or filters elements based on a function
  • open()read()write():  handles file I/O operations
  • dir():  lists the names in the current scope or attributes of an object
  • help():  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