An Overview of Python - ECE-180D-WS-2024/Wiki-Knowledge-Base GitHub Wiki

An Overview of Python

Introduction:

Python powers everything from simple scripts to complex machine learning algorithms, making it a favorite among programmers worldwide. With over 17 million users across the globe, it’s one of the most popular programming languages today. Despite its wide adoption, many people are still unfamiliar with its syntax, benefits, and drawbacks. This tutorial will provide a clear overview of how to write basic Python scripts, along with insights into when and why you should use Python.

History:

Python was developed by Dutch programmer Guido van Rossum in 1991, driven by his frustrations with the programming language ABC (Munro 2024). Python’s key features included being object-oriented, high-level, and executable without a compiler. Object-oriented languages are built around objects, which represent real-world or abstract entities (Gillis 2021). High-level languages are portable, maintainable, and easier to understand and debug, though they offer less control over memory management (Beal 2022).

Unlike ABC, Python emphasized simplicity and a better user experience. ABC was powerful but had a steep learning curve and lacked extensibility. Python addressed these issues with a clean syntax, extensive libraries, and an open-source model, making it accessible and versatile for programmers.

Now, let's dive into how you can get started with Python, from installation to exploring its many use cases.

Why Python?:

Python stands out among programming languages like C++, Java, JavaScript, Ruby, and R for several reasons:

  • Ease of Learning and Use: Python's clear and readable syntax makes it great for beginners. Unlike C++ and Java with their complex syntax, or JavaScript with its asynchronous nature, Python allows quick learning and coding.

  • Versatility: Python can be used for web development, data analysis, machine learning, and more. It combines the functionalities of languages like C++ for system programming, Java for enterprise apps, JavaScript for web development, Ruby for web applications, and R for statistical computing.

  • Community and Support: Python has a large, active community that contributes to many open-source libraries and frameworks. This means abundant resources for problem-solving and continuous improvement.

  • Interpreted Language: Python runs code line by line, making debugging easier compared to compiled languages like C++ and Java.

  • Dynamic Typing: Python determines variable types at runtime, allowing for flexible and quick development. While Ruby also uses dynamic typing, Python’s syntax and structure often make it easier to maintain.

Comparing Python with C++, Java, JavaScript, Ruby, and R highlights its strengths in readability, versatility, community support, and ease of use, making it an excellent choice for all levels of programming projects.

Getting Started:

In order to write Python code, a user first needs two things: an installation of Python, and a code editor.

To install Python, one can download the latest version for their operating system at python.org/downloads/.

To start writing Python, one needs to download a code editor from a variety of choices such as Visual Studio Code, Vim, GNU Emacs, and many others. Visual Studio Code is often recommended for its user-friendliness, large community of supportive users, and extensive customization options (Corrales 2023). Once a code editor is downloaded, a user simply needs to create a new file named {filename}.py in the editor, and they can begin coding.

Fundamentals:

One fundamental concept of Python is variable instantiations. To instantiate a variable, one should follow such a syntax:

var1 = 10
var2 = "Hello!"

There are a couple key pieces of information that should be noted from these variable instantiations. For one, a variable can be named any combination of alphanumeric characters (including “_”), as long as the variable name does not start with a number. Additionally, a variable can store any data type, such as integers, floats, strings, booleans, etc. Finally, one should note that a variable cannot be declared without a value (W3Schools 2024).

Another fundamental concept of Python are operations, which perform logic on variables. These operations include assignment, addition, subtraction, multiplication, division, modulation, exponentiation, and comparisons (Geeks for Geeks 2024). Here is a chart showing how to perform all of these operations in Python:

Mathematical Operations:

Operator Syntax Description
Addition (+) x + y Adds two operands together
Subtraction (-) x - y Subtracts the second operand from the first
Multiplication (*) x * y Multiplies two operands
Division (float) x / y Divides the first operand by the second
Division (floor) x // y Rounds the result down to the nearest int
Modulo (%) x % y Returns the remainder when the first operand is divided by the second
Exponent (**) x ** y Raises the first operand by the second

Comparison Operations:

Operator Syntax Description
Greater than (>) x > y Returns true if left operand is greater than right
Greater than or equal to (>=) x >= y Returns true if left operand is greater than or equal to right
Less than (<) x < y Returns true if left operand is less than right
Less than or equal to (<=) x <= y Returns true if left operand is less than or equal to right
Equivalence (==) x == y Returns true if left and right operand are equal
Un-equivalence (!=) x != y Returns true if left and right operand are unequal

Printing:

Printing in Python is essential for displaying information to the console. The print() function serves as the primary tool for this task. It accepts various inputs, including strings, numbers, and variables, and outputs them to the console.

print("Hello, World!")
print(42)
my_variable = "Python"
print(my_variable)

You can also combine strings and variables within the print() function using formatted string methods:

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

Note, the 'f' before the string allows the string to take in variables and seamlessly integrate them within the printed text.

Syntax:

One key feature of Python’s syntax that differentiates it from other languages is its use of indents as part of its syntax. Where other languages would use indents purely as a means of increasing user readability, indents are essential in Python, as they indicate where blocks of code begin and end. For example, after any if statement, loop, or function declaration, an indent must be made in order to show which code belongs to the respective statement (W3Schools 2024).

Ex.

if 5 > 2:
  print("Five is greater than two!")
print("Comparison done!")

In this case, since the first print statement is one indent ahead of the if statement, the executable knows that the first print statement is part of the if block. Since the second print statement is on the same indent row as the if statement, the exceutable knows it is not a part of the if block. If statements and their syntax/use cases will be explored in the next section.

Control Flow:

Control flow in Python comes in the form of if/else statements and loops.

If/else statements determine what code will be executed depending on whether the conditional statements read as True or False (Python Software Foundation 2024). Additionally, the comparison operators from earlier are used extensively in these statements.

Ex.

if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

As for loops, Python loops continue to execute code repeatedly while a conditional statement is True.

Here is an example of a while loop, that continues until the while statement is False.

count = 0
while (count < 3):
    count = count + 1
    print(count)

For loops, on the other hand, iterate over a sequence of items. Here are a few examples:

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Iterating over a string
for letter in "Python":
    print(letter)

# Iterating over a range of numbers
for num in range(5):
    print(num)

These loops demonstrate how for loops can iterate over various data types, including lists, strings, and ranges.

Functions:

Python functions are reusable pieces of code that can take in arguments, run operations on said arguments, and then return a value (W3Schools 2024). It’s important to note that there are different syntaxes for declaring and running a function, both of which are shown below:

Declaring example:

def my_function(name):
  print("Hello from " + name)

Running example:

my_function(“Nicholas”)

Functions can be created both with and without arguments. Additionally, there is no limit on the number of arguments that are inserted into a function. Functions also do not necessarily need to have a return value, as shown by the example provided.

Classes:

Another key aspect of Python is its ability to instantiate classes. These classes are key to the object-oriented functionality of Python code (Ramos 2023). To instantiate a class, one should follow the syntax:

class Animal:
  def __init__(self, species, name):
    	self.species = species
	self.name = name

Again, there are a couple of important key points to take note of. For one, the init function occurs every time a class is instantiated. Additionally, the “self” variable that is passed into init represents an instance of the object itself. While other languages would hide this method, Python does not do that.

A variety of functionality can occur within the init statement, but the most common is to instantiate class variables that will be used later. It’s also important to note that Python does not have private variables like other languages do. However, if one were to unofficially declare that a variable is private, they would lead its name with an underscore “_”.

Additionally, Python classes can have methods in addition to variables. To define a new method in Python, do the following:

class Animal:
  def __init__(self, species, name):
    	self.species = species
	self.name = name

  def get_name(self):
    print("This animal’s name is: " + self.name)

In order to access these methods and variables, one would follow a syntax like so:

cat = Animal(“cat”, 36)
print(cat.species)
cat.get_name()

Data Structures:

Next, we will cover some common data structures in Python: lists, tuples, dictionaries, and sets. These data structures are great ways to organize and address data in an efficient manner (Python Software Foundation 2024). Below is a table with the syntax, benefits, and drawbacks of each data type:

Data Type Description Syntax Benefits Drawbacks
List Holds an arbitrary number of objects of the same type. Allows dynamic resizing and mutable operations. Instantiation: my_list = []Adding element:my_list.append(element)Removing element:my_list.remove(element)Accessing element:my_list[index] - Dynamic size- Ease of use- Mutability - Potentially slower adding and removing operations
Tuple Holds a fixed number of objects of different types. Immutable after creation. Instantiation: my_tuple = (1, 2, 3)Adding element:my_tuple = my_tuple + other_tupleAccessing element:my_tuple[index] - Uses less memory due to immutability - Cannot add or remove elements after instantiation
Dictionary Holds unique unordered key-value pairs. Provides fast lookups but unordered data. Instantiation: my_dict = {}Adding or changing key value pairs:my_dict[key] = 'test'Deleting key-value pairs:my_dict.pop(key)Accessing key-value pairs:my_dict[key] - Quick lookup times- Improves code readability - Data is unordered- Takes up more space than other data structures
Set Collection of unique unordered elements. Useful for checking membership and eliminating duplicates. Instantiation: my_set = {}Adding elements:my_set.add(element)Removing elements:my_set.remove(element) - Relatively fast search time- Preserves unique values by avoiding duplication - Data is unordered- Can use more memory than other data types

Please note that there are ways to manipulate these data types beyond what was described here. If curious, one can view these methods at python.org.

Running Python code:

To run Python code, one can either execute the Python commands listed above directly in the command line, or by creating a .py file and running that file in the command line. If one were to create a .py file, the syntax would look like:

C:\path python myfile.py

Versatility of Python:

Python's versatility extends far beyond its syntax and core concepts. One of its most compelling features lies in its vast ecosystem of libraries, APIs, and frameworks. In this section, we'll delve into some of the most prominent tools in Python's arsenal, exploring how they enhance its capabilities and cater to a wide range of applications. Whether you're delving into data analysis, web development, machine learning, or beyond, Python's extensive library ecosystem provides the tools you need to succeed. Let's take a closer look at the key players in Python's versatile toolkit.

  • NumPy: Widely used for numerical computing, offering powerful tools for working with arrays and matrices. Learn more about NumPy at https://numpy.org/.

  • Pandas: Indispensable for data analysis and manipulation, providing high-performance data structures and easy-to-use functions. Explore Pandas at https://pandas.pydata.org/.

  • Django: Known for its "batteries-included" approach, providing a robust set of features for building complex web applications. Discover Django at https://www.djangoproject.com/.

  • Flask: Offers a lightweight and flexible framework for web development, ideal for smaller projects. Learn more about Flask at https://flask.palletsprojects.com/.

  • TensorFlow and PyTorch: Powerful libraries for machine learning and artificial intelligence, offering tools for building and training neural networks. Explore TensorFlow at https://www.tensorflow.org/ and PyTorch at https://pytorch.org/.

  • Python Standard Library: Provides a wide range of modules for tasks such as file I/O, networking, and database access, making it versatile for various programming tasks. Learn more about the Python Standard Library at https://docs.python.org/3/library/index.html.

Python's extensive ecosystem of libraries, APIs, and frameworks, coupled with its simplicity and readability, make it an exceptional choice for developers across diverse domains. If you want to dive deeper into any of these specific tools, you can easily find more information using the provided links.

Conclusion:

This tutorial gives you a solid start with Python, covering its basics, like syntax and core ideas, and showing you how to use them practically with vast amount of libraries. As you get to grips with Python's ins and outs, remember you're not alone. There's a huge online community of Python enthusiasts ready to help out and share their knowledge. Plus, the best way to learn is by doing, so dive into your own projects. The more you build, the more you'll learn. So, get coding, explore, and enjoy the journey with Python!

References:

https://www.webopedia.com/definitions/high-level-language/

https://www.developer.com/languages/visual-studio-code-review/

https://www.geeksforgeeks.org/python-operators

https://www.techtarget.com/searchapparchitecture/definition/object-oriented-programming-OOP

https://www.britannica.com/technology/Python-computer-language

https://docs.python.org/3/tutorial/controlflow.html

https://docs.python.org/3/tutorial/datastructures.html

https://realpython.com/python-classes/

https://www.w3schools.com/python/python_functions.asp

https://www.w3schools.com/python/python_syntax.asp