Introduction to Python


This tutorial is a companion article to week 1 of the Clinicians Who Code course and is an introduction to basic Python concepts and syntax.

Follow along with the instructional comments in each of the blocks to complete the tour!

Introduction to Python

Python is a popular programming language that is known for its simplicity and readability. It is widely used in various fields, including web development, data science, artificial intelligence, and more.

Below are interactive code blocks that will introduce you to some basic Python concepts and syntax. You can run the code in each block by clicking the “Run Code” button and see the output in the console below.

You can also edit and tinker with the code to experiment with different Python features and see how they work.

Python Types

In programming, it’s really important to know about different kinds of data because they tell us what we can do with the data and how it’s saved. Python makes this easy and has many types of data built right in for all sorts of projects.

Python types include (but are not limited to) the following:

  • Text is handled by the str type, which lets us make and change text.
  • For numbers, Python uses int for whole numbers, float for numbers with decimals.
  • Types like list, tuple, and range let us store and use lists or collections of data.
  • The dict type is for when you want to connect unique keys to values, kind of like making a dictionary.
  • For unique items, there is the set type
  • The bool type is for true or false values, which are super important for making decisions in code.
  • Types like bytes, bytearray, and memoryview deal with data in a form that computers like, which is great for working with data at a basic level.
  • And NoneType, with its only value None, is used when there’s nothing there or no value.

All these data types are key in Python, helping people who write code to handle all kinds of data easily.

Variables

Variables in programming are used to store information that can be referenced and manipulated in a program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by readers and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

Anatomy of a Variable Assignment

<variable_name> = <value>

Variables are fundamental to any programming language, acting as the basic units of storage in a program. Each variable assignment in Python has a specific anatomy or structure that defines its behavior and capabilities. Let’s break down the components that make up a variable:

  1. Variable Name: This is the identifier assigned to the variable. It is the name you use to access or modify the value of the variable. Python has rules for naming variables, such as starting with a letter or underscore, not beginning with a number, and avoiding the use of reserved keywords.
  2. Assignment Operator: The equals sign (=) is used to assign values to variables. The operator tells the Python interpreter to store the value on the right-hand side of the operator in the variable name on the left-hand side.
  3. Variable Value: This is the data or information stored within the variable. The value can be of various types, including integers, floats, strings, lists, dictionaries, and more. The type of the variable is dynamically determined based on the value it is assigned.

String Operations

In Python, strings are sequences of characters that can be manipulated in various ways. String operations include formatting, concatenation, repetition, indexing, slicing, and applying built-in methods for transformation and search. These operations allow for dynamic and efficient handling of text data in Python programs.

For example, the code below demonstrates several common string operations:

  1. String Formatting with f-strings: Allows embedding expressions inside string literals, making it easy to include variable values and expressions within a string.
  2. Concatenating Strings: Using the + operator to join strings together.
  3. Multiplying Strings: Creating repeated sequences of a string by multiplying it with an integer.
  4. Accessing Characters by Index: Retrieving specific characters from a string using their index.
  5. Slicing Strings: Extracting substrings from a string by specifying start and end indices.
  6. Finding String Length: Using len() to determine the number of characters in a string.
  7. Converting Data Types to Strings: Using str() to convert other data types into strings.
  8. String Methods: Applying methods like upper(), lower(), replace(), and find() to transform or find content within strings.
  9. Splitting Strings: Using the split() method to divide a string into a list of substrings based on a delimiter.

These operations are fundamental for text processing and manipulation in Python.

Functions

In this section, we delve deeper into Python functions, focusing on their ability to not only execute tasks but also return values. Functions are fundamental building blocks in Python, enabling you to execute code multiple times without repetition. They make your code more modular, readable, and maintainable.

When defining a function using the def keyword, followed by the function name and parentheses, you can specify parameters within these parentheses. These parameters act as inputs that the function uses to perform its operations. The code block under the function definition, which is indented, contains the instructions the function executes when called.

A powerful feature of functions is their ability to return values to the caller using the return statement. Once a function executes a return statement, it immediately stops execution and sends the return value back to the caller. This means any code within the function that follows the return statement will not be executed.

If a return value is not specified, the function will return None by default.

This capability allows you to encapsulate complex logic within functions and use their outputs in different parts of your program. Functions can thus return results from their computations, making them not just tools for organizing code but also mechanisms for transferring data and information throughout your application.

Note that you need to define a function before you can call it in your code. This means that the function definition should come before any calls to the function.

Anatomy of a Function

def function_name(parameter1, parameter2):
  # Code block result = parameter1 + parameter2
  return result

The anatomy of a function in Python includes:

  1. The def keyword: This signals the start of the function definition.
  2. The function name: A descriptive name that identifies the function.
  3. Parameters: Inputs that the function uses to perform its operations.
  4. The code block: The instructions the function executes when called.
  5. The return statement: Sends a value back to the caller and stops function execution. Optional, if not used, the function returns None.

Conditionals

In this section, we’ll explore how Python makes decisions through conditionals. Conditionals allow your program to execute different blocks of code based on certain conditions. This is akin to making decisions in real life based on various scenarios.

Python uses if, elif (short for “else if”), and else statements to control the flow of execution. These statements evaluate conditions and decide which block of code to execute. It’s a fundamental concept that enables your programs to react differently to different inputs or situations.

For instance, you might want to print a message if a number is greater than 10, another message if it’s exactly 10, and a different message if it’s less than 10. Python’s conditional statements make this straightforward.

Anatomy of an if Statement

if <condition here>:
  <block of code here>

Before diving into more examples, let’s break down the anatomy of an if statement in Python. An if statement consists of three main parts:

  1. The if keyword: This signals the start of the conditional statement.
  2. The condition: A boolean expression that evaluates to either True or False. The Python interpreter checks this condition to decide whether to execute the block of code that follows.
  3. The code block: If the condition is True, the code block under the if statement executes. This block is indented to indicate that it is part of the conditional statement.

Using elif and else Statements

if <condition1>:
  <block of code1>
elif <condition2>:
  <block of code2>
else:
  <block of code3>

In addition to if statements, Python provides elif and else statements to handle multiple conditions. The elif statement allows you to check additional conditions if the previous condition was False, while the else statement provides a fallback block of code to execute if all previous conditions were False.

Note that in a if/elif/else statement, only the first condition that matches will execute. Once a condition is met, the rest of the conditions are skipped.

The example code provided below demonstrates a simple use of these conditional statements. By changing the value of the variable and observing the output, you can get a hands-on understanding of how Python’s conditionals work. This is a crucial step towards writing more dynamic and interactive Python programs.

Note: A single = is used for assignment of a variable, while == is used for comparison of two variables in Python. It is important to not get these confused when writing conditionals. See below for an example.

Loops

Loops are a fundamental concept in programming that allow you to execute a block of code multiple times. Python provides several types of loops, including for and while loops, which can be used to iterate over a sequence (like a list, tuple, or string) or execute a block of code repeatedly under certain conditions.

A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.

A while loop in Python repeats as long as a certain boolean condition is met. See the example below for a demonstration of both types of loops.

Note: If you get stuck in a loop that never ends, you may need to refresh your page or close your browser tab to stop the code execution. I’m working on a fix for this!

Understanding the Anatomy of a while Loop

while <condition>:
  <block of code>

A while loop in Python is used to execute a block of code as long as a certain condition is true. The anatomy of a while loop includes:

  1. The while keyword: This signals the start of the loop.
  2. The condition: A boolean expression that is checked before each iteration of the loop. If the condition is True, the loop continues; if it is False, the loop exits.
  3. The code block: A block of code that you want to execute for each iteration of the loop. This block is indented to indicate that it is part of the loop.

Understanding the Anatomy of a for Loop

for <loop variable> in <sequence>:
  <block of code>

A for loop in Python is used to iterate over a sequence (like a list, tuple, or string) or any other iterable object (like range). The anatomy of a for loop includes:

  1. The for keyword: This signals the start of the loop.
  2. The loop variable: This variable takes the value of the next item in the sequence with each iteration of the loop.
  3. The in keyword: It is used to specify the sequence to iterate over.
  4. The sequence: The iterable object you want to iterate over.
  5. The code block: A block of code that you want to execute for each item in the sequence. This block is indented to indicate that it is part of the loop.

The example code provided demonstrates the use of for and while loops in Python. By running the code and observing the output, you can gain a better understanding of how loops work and how they can be used to automate repetitive tasks in your programs.

Conclusion

Congratulations! You’ve completed the introductory tutorial on Python programming. You’ve learned about basic Python concepts, such as data types, variables, string operations, functions, conditionals, and loops. These concepts are foundational to programming in Python and will serve as building blocks for more advanced topics.

I’ll continue to update this post if the community runs into common issues or has questions about the content. Feel free to reach out to me on the CWC slack!