DEV Community

Cover image for Basic Intro to Python
sandrockj
sandrockj

Posted on

Basic Intro to Python

What is Python?

Python describes itself as an 'interpreted, interactive, object-oriented programming language' that also supports 'multiple programming paradigms beyond object-oriented programming, such as procedural and functional programming'.


Why was Python created?

Python was created so that it could combine the strengths of the Modula-3 and ABC progamming languages into a separate programming language. Python credits the Modula-3 language for the overall syntax and the semantics used for exceptions, however there were similar inspirations from the ABC language and the SET language by proxy.


Why choose Python?

Python describes itself as 'a high-level general-purpose programming language that can be applied to many different classes of problems'. The Python Standard Library covers multiple concerns for developers:

String Processing Internet Protocols Software Engineering Operating System Interfaces
Regular expressions HTTP Unit testing System calls
File comparisons FTP Logging File systems
Unicode SMTP, XML-RFC, & more Profiling TCP/IP sockets

Comparing Python & JavaScript

First, it might be best for us to understand why there are so many programming languages available for developers. The simple answer is that, while many programming languages can execute similar processes, some are better equipped to handle those executions. According to Linsi Tuttle's article on the WGU (Western Governors Univserity) website:

Each programming language is designed with specific applications in mind and has unique strengths and limitations. Depending on the project, one language may be better suited than another in terms of speed efficiency, versatility, or scalability.

With that in mind, let's also look into the observations of Estefania Cassingena Navone in her article comparing Python & JavaScript:

Python JavaScript
It is widely used in scientific and specialized applications. It is widely used for web development, user-facing functionalities, and servers.
Used in data science, artificial intelligence, machine learning, computer vision and image processing. Used in web development, especially for making interactive and dynamic content for web applications.
It can be used for web development; Python is typically used for back-end development. It can be used to develop both the back-end and front-end of the application.

Examples from Python 3

Function Invocation

I think it's best for us to ground ourselves with something simple. Let's start with the basics, how can we use Python to log messages to the console?

print("Hello world!");
Enter fullscreen mode Exit fullscreen mode

This outputs a very basic to our console, and while it might not be useful now it can certainly prove useful for troubleshooting while we continue to learn the language!

# OUTPUT => "Hello world!"
Enter fullscreen mode Exit fullscreen mode

Variables & Data Types

According to Python, variables do not require a declaration before they can be used and it is also not required for you to declare a type. It is especially important to know that in Python, every variable is an object.

It might be difficult to wrap your head around this starting out, so let us take a loot at some variable declarations and assignments.

first_name = 'Jolly' # string with single quotes
last_name = "Roger" # string with double quotes

height = 6 # integer number
age = 36.253256 # float number

is_liar = True # boolean

# concatenation example
print(first_name + " " + last_name + " sails the high seas!")

# interpolation example
print("At %d years old he stands at %d feet tall!" %(age, height))
Enter fullscreen mode Exit fullscreen mode

Notice that in the examples above, we are avoiding camelCase and we are using the snake_case instead. This is mainly done because the official style guide for Python uses snake_case in many of its examples. If you are interested in more styling recommendations, you can view the documentation here.

Now let's take a quick look at our outputs, because we are doing something slightly different in both uses of our print statement. This is what our outputs would look like:

# OUTPUT => "Jolly Roger sails the high seas!"
# OUTPUT => "At 36 years old, he stands at 6 feet tall!"
Enter fullscreen mode Exit fullscreen mode

The + operator is expecting that the data types served to it will match. In other words if the + operator is served with numbers then it will attempt to compute these numbers. If the + operator is served with strings, then it will try to concatenate the two items into one string.

In this first example, we essentially performed string concatentation. This is great, and it will work because in this case the + operator is being used for items of the same data type (string). In the second example, however, this would not work!

In the second example, we want to accomplish string interpolation. In order to do this we can create placeholders (%s %d %f) in a string, and then we can pass in our arguments to those placeholders in sequence %('cat', 3, 4.56231).


Code Blocks & Indentation

In JavaScript, we typically indicate the opening of a code-block through the use of braces {...} which wrap around a set of code for execution. However, Python handles this concept a bit differently...this is where good habits in other languages can help out.

x = 1

if x == 1:
    print("x is 1.")
Enter fullscreen mode Exit fullscreen mode

In this case, Python uses indentation to know when a code-block starts and ends. The standard indentation requires standard Python code to use four spaces. If we wrote this line without indentation, we would receive the error IndentationError: expected an indented block .


Conditional Statements & Expressions

Let's try to apply our new knowledge of code blocks to the example in the Variables & Data Types section. In that case, we had an unused boolean which we are now going to implement.

first_name = 'Jolly' # string with single quotes
last_name = "Roger" # string with double quotes

height = 6 # integer number
age = 36.253256 # float number

is_liar = True

if is_liar:
    print("%s %s lied to you!" %(first_name, last_name))
else:
    print(first_name + " " + last_name + " sails the high seas!")
    print("At %d years old he stands at %d feet tall!" %(age, height))
Enter fullscreen mode Exit fullscreen mode

Now we have created a code-block, and this code block executes only if the expression is truthy. In this example is_liar points to the value of True , so our output would be:

# OUTPUT => "Jolly Roger lied to you!"
Enter fullscreen mode Exit fullscreen mode

It is also important to note that Python is capable of conditional chaining. The if statement can be followed by one or multiple elif statements and it can also be followed by a simple else statement.


Loops

In Python, there exist two ways to loop or iterate: for loops and while loops. In this case we can start with a simple example where we use the range function.

for item in range(1, 11):
    print(item)
Enter fullscreen mode Exit fullscreen mode

In this example, the range() function represents our starting and stopping conditions for the loop. This is because the range() function returns a list data structure (in JavaScript you would refer to this structure as an array). If we move forward with this knowledge, we can reframe how we visualize this problem:

for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    print(item)
Enter fullscreen mode Exit fullscreen mode
  1. The function range(1, 11) returns a list.
  2. The list points to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
  3. For every item in that list, we try to print() it.

It is also important to consider control flow statements, which can be used to alter the order in which our code is evaluated and executed. Two common statements are the continue and break statement. Let's integrate one of these into our loop.

for item in range(1, 11):
    if item % 2 == 0: # if the item is even
        continue      # continue to next iteration
    else:
        print(item)   # else print the item
Enter fullscreen mode Exit fullscreen mode

In this case, we use the continue statement to proceed to the next iteration but only if the current item is an even number. Otherwise, we hit our else block and we would print the number! The continue statement, as well as the break statement, are sometimes optional. If you are worried about infinite loops, consider implementing these statements. On that note, let's take a look at a while loop!

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break
Enter fullscreen mode Exit fullscreen mode

In this case, we have technically declared a loop which could iterate infinitely. However, in this case, we have appropriately included a base case. Whenever the count variable is greater than or equal to 5, we exit the entire loop via the break statement.

If we didn't have the break statement in this example, we would create an infinite loop. It's possible for us to restructure or otherwise redesign our code so that a break statement isn't necessary. If we wanted to accomplish the same thing we could redesign our code like this:

count = 0
while (count < 5):
    print(count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

In the end we achieved the same results, we just had to rethink our approach. Python offers many ways for you to navigate problems, so it is generally possible to achieve the same result in a number of different ways.


Functions

Ah, reuseable code, my beloved. Python describes functions as "a convenient way to divide your code into useful blocks, allowed us to order our code, make it more readable, reuse it, and save more time". With that in mind, let's jump into how we can make some reusable code!

def describe_me(name = None, age = None, hobbies = None):
    # code for the function would be here!
Enter fullscreen mode Exit fullscreen mode

In the example above, we use the def keyword to indicate that we are defining a new function. The function is going to be called describe_me and it can take three arguments:

  1. String
  2. Number (float or integer)
  3. List of hobbies

Notice that when we define these three parameters, we have also assigned them to the value of None. What we are actually doing here is we are setting the default value to None so that way if no argument is provided, then our code will still attempt to execute. Let's continue expanding this function in our example below.

def describe_me(name = None, age = None, hobbies = None):
    if (name and age):
        print('My name is %s and I am %d years old.' %(name, age))
    elif (name):
        print('My name is %s.' %(name))
Enter fullscreen mode Exit fullscreen mode

Great, now we have established two condtional expressions to see what data we are working with. Our first conditional checks to see if an argument was served for both the name parameter and the age parameter; if this resolves to True then a message will be printed to the console. If a name parameter was provided, but no age, then an alternative message would be printed.

What we have so far works, but we still aren't addressing how the hobbies parameter is being used. Let's see what it would look like if we added a loop to iterate over the hobbies collection.

def describe_me(name = None, age = None, hobbies = None):
    if (name and age):
        print('My name is %s and I am %d years old.' %(name, age))
    elif (name):
        print('My name is %s.' %(name))

    if (hobbies and (type(hobbies) is list)):
        for hobby in hobbies:
            if (type(hobby) is str):
                print('%s is a hobby of mine.' %hobby)

describe_me('Jolly Roger', 36, ['Sailing', 2, 'Treasure-hunting', 3, 4, True])
Enter fullscreen mode Exit fullscreen mode

We expanded our code quite a bit here, but what is it doing exactly? Now we are checking whether or not the hobbies parameter received an argument, and we are also checking to ensure that the parameter was a list. If this first check resolves to True then we attempt to execute everything inside of the code-block, which should output the following message:

# OUTPUT => 'My name is Jolly Roger and I am 36 years old.'
            'Sailing is a hobby of mine.'
            'Treasure-hunting is a hobby of mine.'
Enter fullscreen mode Exit fullscreen mode

Classes

Classes are essentially a template that you can reuse to create new object instances. If you are unfamiliar with the concept of Classes, then that might sound really confusing but we are going to expand upon this premise.

class Car:
    year = 0
    make = ''
    model = ''
Enter fullscreen mode Exit fullscreen mode

Let's start out by defining what a Car class object has, in this case it has several variables that are initialized to the type of data that we want to store inside of them. So with this basic template, how can we create a new object that is an instance of the Car class?

my_car = Car()

my_car.year = 2007
my_car.make = 'Toyota'
my_car.model = 'Camry'
Enter fullscreen mode Exit fullscreen mode

We started by creating a variable my_car that is equal to a new instance of the Car class. After creating the new object, we reassign the variables inside of it to our desired values. However, our current problem is that we have to print the value of each variable individually.

print(my_car)        # => <__main__.Car object at 0x7f9940979f10>

print(my_car.year)   # => 2007
print(my_car.make)   # => Toyota
print(my_car.model)  # => Camry
Enter fullscreen mode Exit fullscreen mode

Let's finish this off by adding some extra functionality to our Car class. We will add a new method to the class which, upon invocation, will print the year, make, and model of our instance.

class Car:
    year = 0
    make = ''
    model = ''
    def describe_me(self):
        print(self.year)
        print(self.make)
        print(self.model)
Enter fullscreen mode Exit fullscreen mode

Great, so now we have added this functionality to our Car class. So what does this mean for us? Now we can create many instances of an object that follow our Car template! It is important to note that there are a few different ways that you can approach defining a class, so don't feel like you are too limited here!


Conclusion

I hope that this introduction has informed you of the differences between Python and other languages. I am still learning a lot about JavaScript and full-stack development, so unfortunately I haven't spent as much time with Python. However, I think it is a good thing to explore options for your toolkit as a developer!

If you would like to learn more about Python, you can check the documentation in order to research concepts in-depth. If you are looking for a beginner friendly tutorial, then I strongly recommend checking out the Learn Python organization website.

Top comments (1)

Collapse
 
sandrockjustin profile image
sandrockj

I wanted to follow up that in this post, I didn't discuss non-primitive data types other than the list data structure. If you would like to learn more about this, there is a great article by DataCamp and there is another great article by GeeksforGeeks.

I intend to cover these topics more in the future, but I am currently preoccupied with other matters. Thank you for reading through my post, and if you have any suggestions please let me know.