Basics of Python Programming

Hey everyone! It’s already been a week since I started the first programming course at Western Governors University and I thought I’d share my experience with you all. In just one short week, I’ve already learned the basics of the Python language. We’ve covered a wide range of topics, including the language’s basic syntax, variables, functions, data types, and the significance of whitespace in writing clean code.

Whitespace is the term used to describe spaces, tabs, and line breaks in your code. The reason whitespace matters so much in Python is because it’s used to indicate the structure of your code, which can affect how it runs.

For example, in many other programming languages, you might use curly braces {} or parentheses () to group blocks of code together and determine where one block ends and another begins. In Python, however, you use whitespace to indicate where those lines end.

This is called indentation, and it’s used to make your code easier to read and understand. Python uses indentation as part of its syntax. Many code editors, like VS code for instance, will automatically indent your code accordingly if your file ends with the .py extension.

Consider the following example:

if x < 5:
    print("x is less than 5")
else:
    print("x is greater than or equal to 5")

In this code, the lines that use the print() function to print the two different messages are indented differently than the rest of the code. This indentation tells Python which lines are actually part of the if statement and which are part of the else statement.

If you were to remove the indentation, Python wouldn’t know which lines belong to which statement. This could result in a syntax error, or even worse, your code running but operating incorrectly.

It’s very important to pay careful attention to indentation and make sure your code is properly structured, or else you might run into errors or unexpected behavior. Python places a strong emphasis on whitespace as part of its syntax, which sets it apart from many other programming languages.

Variables

In Chapter 2 of the course zyBook, I learned about variables and how to assign them different values. They’re pretty useful and essential in any coding language.

A variable is just a name that we can use to refer to a value. For example, the number 34 is an integer value, and we can assign age to that value so that we can call it up later in our code by name. Whenever we use age in the future, we know that it’s referring to a number.

Variables don’t just hold numbers though. They can hold all kinds of different data values. For example, I can assign the variable GPA to 3.4, which is a floating point number instead of an integer. Or I can just assign it the word 'Good', which is just text.

We call these different types of values, data types.

Data Types

In programming, a data type is a classification or categorization that specifies which type of value a variable can hold, or which operations can be performed on that value. Data types are essential because they define how the computer manipulates data.

name = "Rick"  # this is a string of characters
age = 34  # this is an integer value

Understanding and using the appropriate data types is crucial for writing efficient and correct programs. Different data types have different behaviors and are suited for different kinds of tasks in programming.

Let me explain some common data types in Python:

  1. Integer (int): This data type represents whole numbers, both positive and negative, without any decimals. For example: age = 34
  2. Float (float): Float data type represents real numbers with a decimal point. For example: weight = 320.0
  3. String (str): Strings are sequences of characters enclosed in single or double quotes. They are used to represent text data. For example: name = "Rick"
  4. Boolean (bool): Boolean data type represents either True or False. It is often used for making logical decisions and comparisons. For example: is_adult = True

These are some of the basic data types in Python. Python is a dynamically typed language, which means you don’t need to declare the data type explicitly when defining a variable; the interpreter infers it based on the assigned value.

Identifiers

An identifier is anything you as the programmer name yourself. For example, variable names, function names, module names, etc., all require you to name them. Whenever you are naming something in your code, that is considered an identifier.

The opposite of that would be referring to something that Python has already given a name to, such as a reserved keyword like def or print().

Make sure that your identifiers actually make sense. For example, don’t name a function get_color() if you’re not going to be getting some type of color with it. Similarly, don’t name a variable something like first_name if you’re only accepting numbers inside of it. This gets confusing for other developers who may have to look through your code or debug it in the future (which could possibly be future you!)

Arithmetic Expressions

Arithmetic expressions in Python are mathematical expressions that involve numbers and operators. These expressions are evaluated to produce a numeric result. Python supports various arithmetic operators, including addition, subtraction, multiplication, division, and more.

Here is a table with some common arithmetic operators in Python:

These operators can be combined with numerical literals or variables to form arithmetic expressions. For example, 5 + 3 is an arithmetic expression that uses the addition operator to add the numbers 5 and 3, resulting in the value 8.

Arithmetic expressions can also include parentheses to enforce precedence and control the order of operations. For example, (5 + 3) * 2 evaluates the addition first and then multiplies the result by 2, giving the value 16.

It’s important to note that Python follows the standard order of operations (PEMDAS), where parentheses are evaluated first, followed by exponentiation, multiplication, division, and finally, addition and subtraction.

The course zyBook also covered how to incorporate the Math module for getting mathematical functions such as floor() and sqrt().

Statements and Expressions

Somewhere in between these chapters, the difference between statements and expressions (in not just Python but any programming language) was explained.

statement is a line of code that performs some kind of an action, such as printing to the screen or assigning a value to a variable. Statements are usually separated by a new line or semicolon. They essentially create an effect.

# This is an example of a statement
x = 3 + 5

On the other hand, an expression is anything that evaluates to a value, such as the expression sqrt(16) since that evaluates to 4.

Or the expression 3 + 5 since that evaluates to 8.

# This is an example of an expression
3 + 5

Expressions can be used inside statements, such as when using the value of an expression to do something with it. For example, print(3 + 5) would print the result of the expression to the screen. The whole thing combined is a statement.

The main difference between a statement and an expression is that a statement is executed for its side effect, while an expression is executed to get its value. In other words, an expression evaluates to a value and a statement does something with that value.

Data Structures

Lists, tuples, sets, and dictionaries are different data structures in Python. Data structures allow you to organize data in interesting ways. Each data structure has its own unique properties and methods that make them suitable for specific use cases. For example, you can use the sort() method in a list to sort its contents in ascending order by default, or change it to be descending order. Different data structures have different methods and ways of manipulating data.

Let’s go over these data structures one by one.

List

myList = [1, 2, 3, 4, 5]

list is a type of data structure that allows you to store and manipulate a collection of elements in a particular order. You can add, remove, or modify elements in a list as needed. Lists are represented by square brackets, and elements within a list are separated by commas. In other programming languages, these are typically known as arrays.

Tuple

myTuple = (1, 2, 3, 4, 5)

tuple is similar to a list, but it is immutable, meaning that once you create a tuple, you cannot change its contents. Tuples are represented by parentheses, and elements within a tuple are separated by commas. Tuples are often used to group related data together, such as the latitude and longitude of a location. A tuple allows for duplicate items and is ordered (just like lists).

Set

mySet = {3, 2, 5, 4, 1}

set is another type of data structure that allows you to store a collection of elements, but unlike lists and tuples, sets do not maintain a particular order. Additionally, sets only allow unique elements, meaning that if you try to add the same element to a set multiple times, it will only be added once. Sets are represented by curly braces, and elements within a set are separated by commas. Also, because of their unordered nature, values have no index or stored position in memory inside a set.

Dictionary

myDictionary = { 'name': 'Rick', 'age': 34 }

dictionary is a data structure that allows you to store and manipulate key-value pairs, where each key is associated with a particular value. You can add, remove, or modify key-value pairs in a dictionary as needed. Dictionaries are represented by curly braces, and key-value pairs within a dictionary are separated by colons and commas.

All of these data structures have their own unique properties and methods, and understanding when to use one over another can help optimize your code.

String Formatting

In Chapter 4, we explored type conversion, string formatting, and how to use different built-in functions in Python to stylize your output. I found this chapter particularly helpful because it provided us with tools to make our code more readable and clean, especially when handling string outputs.

One popular method of string formatting in Python is through f-strings, which were introduced in Python 3.6. With f-strings, you can embed expressions and variables directly within curly braces {} in a string. The expression inside the curly braces is evaluated and its value is inserted into the final string.

Here are some examples to illustrate the usage of f-strings:

name = "Alice"
age = 25
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # Output: Hello, Alice! You are 25 years old.

radius = 4
pi = 3.14159
area = f"The area of a circle with radius {radius} is {pi * radius ** 2}."
print(area)  # Output: The area of a circle with radius 4 is 50.26544.

In the examples above, the values of variables name, age, radius, and pi are dynamically inserted into the strings using f-strings. The expressions inside the curly braces are evaluated at runtime, allowing for flexible and readable string formatting.

F-strings also support various format specifications to control the appearance of values in the resulting string. For example, you can specify the number of decimal places, padding, alignment, and more. Here’s an example:

price = 19.99
discount = 0.25
final_price = f"The final price is ${price * (1 - discount):.2f}."
print(final_price)  # Output: The final price is $14.99.

In this example, the expression (price * (1 - discount)) is evaluated, and the resulting value is formatted as a floating-point number with two decimal places using the format specifier :.2f.

F-strings provide a concise and expressive way to construct formatted strings in Python, making it easier to generate dynamic output with variables and expressions. They are widely used in tasks such as generating reports, logging, user interfaces, and more.

Conclusion

Throughout the week, I used a variety of resources to supplement my learning. I watched YouTube tutorials, took a Udemy course called “The Complete Python Bootcamp From Zero to Hero in Python”, and read the book “Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming”.

Overall, my first week of learning Python has been challenging but exciting. I can’t believe how much I’ve learned already and I’m looking forward to continuing to build on this knowledge in the coming weeks.


Last Updated on October 13, 2024


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *