Introduction to Python Programming

Python is far and away the most popular programming language for data scientists around the world. Its ease of learning, versatility and robust community support all contribute to its suitability for analytics and machine learning.

Whether you’re an experienced coder or a programming newbie, your Python journey will have to start with the basics. In this article, we’ll focus on the very basic but completely essential skills, specifically:

  • The Print Command. Learning how to output data to the screen.
  • Running Math Operations. Understanding how to perform and use basic arithmetic operations.
  • Comments in Python Code. Knowing how to document your code properly.

By the end of this guide, you will have a solid foundation in these core concepts, enabling you to write simple Python code and prepare for more advanced topics. Over the next several posts, we will build skills on top of each other so you can move from solving very basic problems to running complex models on massive amounts of data.

The Print Function

The print() function in Python is one of the first commands most new programmers learn. It’s simple yet powerful, allowing you to output information to the console, which is crucial for debugging and displaying results. Understanding how to use print() effectively is a fundamental skill in Python programming.

Python Print Syntax

The basic syntax of the print() function is straightforward:

print(object(s), sep='separator', end='end', file=sys.stdout, flush=False)

Where:

  • Function Name. In this case, print is the name of the function.
  • Parentheses. The opening ( and closing ) parentheses are used to pass arguments to functions.
  • Arguments. Inside the parentheses, you can place the items you wish to print, separated by commas if there are multiple items.
  • Quotation Marks. Denote a string literal, or a sequence of characters that should be treated as text. You can use either single quotes ‘ ‘ or double quotes ” ” to create a string.
  • object(s). This can be any number of objects; you want Python to print. These objects are converted to strings and written to the standard output (your screen, by default).
  • sep=’separator’: Optional. Specifies how to separate multiple objects if there is more than one. The default separator is a space.
  • end=’end’: Optional. Specifies what to print at the end. Default is a newline.
  • file: Optional. Specifies the object where the values are printed. The default is sys.stdout (screen).
  • flush: Optional. A Boolean specifying whether the output is flushed (True) or buffered (False). Default is False.

Here’s an example of a simple line of print code on Pyton:

print("Hello, world!")

In this line of code, the function print is invoked, while the parentheses are there to contain the argument (text). The quotation marks denote that the data inside the paretheses is a string. In the output box, you will see only the text hello world since everything else is just there to give Jupyter notebook instructions on what you want to output.

Running Math Operations in Python

Math operations are fundamental to nearly all programming tasks, from simple calculations to complex algorithmic processing. Python provides a straightforward way to perform arithmetic operations using basic operators. Understanding these operations is crucial for manipulating numerical data efficiently.

Syntax

Python supports the usual arithmetic operations for addition (+), subtraction (), multiplication (*), and division (/). Here is a brief overview of each:

  • Addition (+): Adds two numbers.
  • Subtraction (): Subtracts the second number from the first.
  • Multiplication (*): Multiplies two numbers.
  • Division (/): Divides the first number by the second, resulting in a float.
  • Floor Division (//): Divides the first number by the second, rounding down to the nearest whole number.
  • Modulus (%): Returns the remainder of the division of the first number by the second.
  • Exponentiation (**): Raises the first number to the power of the second.
    • Examples
      1. Calculating the Sum of Two Numbers

        print(15 + 4)

        Output

        19

      2. More Complex Calculation. Calculating the result of a more complex expression involving multiple types of operations:
        print((8 * 3) + (18 / 3))

        Output:

        30

        This example uses multiplication, addition, and division to compute the final result. The parentheses are used to explicitly define the order of operations, ensuring that multiplication and division are completed before addition.

Python Math FAQs

  • How does Python handle integer and float division differently?

In Python, the division operator (/) always returns a float, even if the result is a whole number. However, if you use the floor division operator (//), Python will return the largest whole number smaller than or equal to the result, effectively discarding any fractional part.

  • What are the precedence rules for arithmetic operations in Python?

Python follows the standard mathematical precedence rules, which can be remembered by the acronym PEMDAS:

      • Parentheses: Have the highest precedence and can override the conventional order.
      • Exponentiation: Next, handling raising to powers.
      • Multiplication and Division: These occur next, from left to right.
      • Addition and Subtraction: These have the lowest precedence and also occur from left to right.

Understanding these basic operations and how to execute them in Python is crucial for anyone looking to develop software, analyze data, or solve problems that involve numerical computations. This foundation will be built upon in future discussions about variables and more complex data types.

Comments in Python Code

Comments are crucial in programming as they help make the code more readable and maintainable. In Python, comments are lines that the Python interpreter ignores, but they are invaluable to developers who need to understand the code’s purpose and functionality. Proper use of comments can greatly aid in the communication of intent among team members and even to the future self.

Syntax

In Python, comments begin with a hash (#) symbol. Anything following the # on the same line will not be executed by Python. Here’s the basic usage:

# This is a single-line comment

Python does not have a specific syntax for multi-line comments, but you can use the hash (#) symbol at the beginning of each line, or use triple quotes (”’ or “””) for multi-line strings that aren’t assigned to a variable, often used as a form of block comment:

# This is a longer comment

# that spans multiple lines

“””

This is another way to

handle multi-line comments

Python Comment FAQs

  • Why is commenting your code important?

Comments are essential for several reasons: they can explain the intent behind a code block, provide steps of complex algorithms, note bugs or issues to be fixed, and help new developers understand what the code is supposed to do. Well-commented code is easier to maintain, update, and use.

  • Can comments be placed anywhere in Python code, and are there any restrictions?

Comments in Python can be placed at the end of a line of code or on a new line by themselves. However, they should not be placed within string literals, as they would be interpreted as part of the string text. While there are no strict rules on where comments must be placed, placing them strategically to improve readability and understanding is best practice.

Comments are a simple yet powerful tool in your programming arsenal. By effectively using comments to document your Python code, you enhance its readability and maintainability, making it easier for others (and yourself) to work with it long-term.

Best Practices for Writing Code in Jupyter Notebooks

Writing code in Jupyter Notebooks is not just about getting the correct output; it’s also about ensuring that your code is readable, maintainable, and reusable. Adhering to best practices can greatly enhance the clarity and usefulness of your notebooks, both for yourself and others who may read your work. Here are some essential guidelines to follow:

  1. Writing Readable and Maintainable Code
    • Clarity is Key: Write code as if someone else has to understand it without your explanation. Use meaningful variable names and keep functions focused on performing a single task.
    • Comment Generously: Comments are crucial in explaining why something is being done, not just what is being done. Use comments to describe the logic behind complex sections of code or to explain the purpose of certain functions and variables.
    • Consistent Style: Adopt a consistent coding style in terms of indentation, use of spaces, naming conventions, etc. Tools like PEP8 for Python can help enforce coding standards.
  1. Writing on Your Code
    • Document Intentions: Comments should convey the purpose behind code blocks and decisions. This is especially important in data science, where the reasoning for a particular data processing step needs to be clear.
    • Update Comments: As your code evolves, ensure your comments are updated to reflect changes. Outdated comments can be more misleading than no comments at all.
  1. Structuring Your Code for Easy Understanding
    • Logical Organization: Structure your notebook logically. Begin with data loading and cleaning, followed by exploratory data analysis, model building, and finally, results evaluation. Each section should be clearly defined using markdown headings.
    • Modular Code: Break down complex processes into smaller, reusable functions or modules. This not only cleans up your main analysis pipeline but also makes it easier to test individual components.
  1. Utilizing Code Cells Effectively
    • One Idea Per Cell: Keep code cells concise and focused on a single task or idea. This makes your notebook easier to follow and debug.
    • Sequential Flow: Ensure that your notebook can be run from top to bottom without needing to execute cells out of order to function properly. This is essential for reproducibility.
    • Use of Cell Magic Commands: Jupyter offers cell magic commands (%magic) which are useful for various tasks like timing execution, writing files, or running code in different languages within a single notebook.
  1. Testing and Debugging in Notebooks
    • Incremental Testing: Test code incrementally as you write it to catch errors early in the process. This approach helps to isolate issues quickly and ensures each part of your code works correctly before moving on.
    • Interactive Debugging: Utilize Jupyter’s interactive debugging features, such as %debug, to examine the state of your program and trace issues more efficiently.

By adhering to these best practices, you can enhance the effectiveness and readability of your Jupyter Notebooks, making them more useful tools for data analysis and collaboration. Remember, the goal is not only to write functional code but to write code that is easily understandable and maintainable by others, which is a hallmark of good programming practice.

 

In summary, code cells are the most essential part of any Jupyter Notebook since they’re the containers of the Python code that will give the computer instructions on how to load and process data for any analytics project. By learning their basic functions and best ractices, we can ensure that our code will run properly en route to our desired outcomes.

About Glen Dimaandal

Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines’ most respected SEO agency.
Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines’ most respected SEO agency.
ARTICLE & NEWS

Check our latest news

In our last post on Python programming for data science, we discussed the list data structure…

In the previous entry, we touched upon commonly occurring distributions: Bernoulli distribution, binomial distribution, uniform distribution,…

In our last coding post, we discussed the concept of data structures in Python and the…

Ready to get started?

Reveal the untapped potential of your data. Start your journey towards data-driven decision making with Griffith Data Innovations today.