Skip to content

30 Days of Python – Day 2: Basic Syntax & Data Types

In Day 1 we already learned some basic syntax, we’re going to look into some more basic stuff. From the title we can determine that we will look at variables and data types. Also touching how to comment our code, in my opinion it’s one of the most important things. Some times we don’t have the time to do extensive documentation so commenting complex part of our code is important, for us to understand what we were thinking years ago or for someone new to understand how we were reasoning on a particular day.

Comments

We have two ways of commenting in Python, single-line and multi-line comments. Most programming language have these options. The single-line comments can also be in-line comments.

To create single-line or in-line comments we must use the pound symbol (#).

For multi-line comments we can either use single or double quotes. But we need to use three of them.

Here is an example of all the comment types.

# This is a single-line comment

'''
This is a multi line-comment
'''

"""
This is also a multi-line comment
"""

def check_python_version():
    print("Python Version:", sys.version) # In-line comment

Data Types

There are a lot of data types, as we can see in the documentation. From my research the most common are:

String

We all know how strings work. We can surround them by either single or double quotes. Python supports multi-line string variables. They work like comments, we can use three single or double quotes to force multi-line.

a = 'lorem ipsum'
b = "lorem ipsum"

multiline = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt felis justo, vel vulputate risus consectetur eu. 
Vestibulum a eros quis justo rhoncus condimentum porttitor vitae quam. Suspendisse sit amet odio in eros bibendum egestas 
quis ac purus. Donec eleifend ante et ex viverra fringilla. Phasellus ac finibus augue. Curabitur sollicitudin diam ipsum.
"""

multilineB = '''
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt felis justo, vel vulputate risus consectetur eu. 
Vestibulum a eros quis justo rhoncus condimentum porttitor vitae quam. Suspendisse sit amet odio in eros bibendum egestas 
quis ac purus. Donec eleifend ante et ex viverra fringilla. Phasellus ac finibus augue. Curabitur sollicitudin diam ipsum.
'''

print(a+"\n")
print(b+"\n")
print(multiline+"\n")
print(multilineB+"\n")

Numeric

We have three numeric types:

  • Int
  • Float
  • Complex

Int and Float are straight forward, Complex like it’s name gets a bit complex and confusing when starting.

A complex number is expressed in the form a + bj, where a is the real part, b is the imaginary part, and j (or J) represents the imaginary unit 

Python has a lot of immutable data types, this is one of them. The complex data type is mostly used in mathematical computations and complex algebra. There’s two ways of defining complex data type.

int = 10

float = 10.5

num1 = 3 + 4j

num2 = complex(3, 4)  # This is equivalent to 3 + 4j

Sequence Types

The types within this categories don’t really make sense to me. One of the functions literally creates a sequests of numbers and based on the parameters you can manipulate how they are generated while the others two are just a list (or array).

  • List
  • Tuple
  • Range

For me Lists are just another name for array, while lists are mutable. Tuples aren’t. With my Javascript background I can relate lists with an array using let to define the variable and tuple with an array defined using const.

Range is the only one that makes sense for me in this category. Range returns a sequence of numbers in a given range. I imagine that this is a very popular data type for using in a loop.

a = ["lorem", "ipsum", "dolor", "sit", "amet"] # List

b = ("lorem", "ipsum", "dolor", "sit", "amet") # Tuple

c = range(5)

d = range(0, 10, 2) # range(start, stop, step) Output: 0, 2, 4, 6, 8

Sets

For sets we have set and frozenset they work exactly the same, just that frozenset is immutable while set can be modified. In our code snippet you can see we try to add a new value to both. While set does let us add a new item frozenset doesn’t.
Sets whether it be one or the other don’t allow us to have duplicates.

You can also notice the order in which they output. The order isn’t how they were create with or alphabetical or anything that makes sense just by looking at it. Instead it’s based on a hash table that is created from the sets. By not really knowing the order they will be in it makes it impossible to rely on these for most cases. The most common use for sets is to eliminate duplicates from a list, converting a list into a set automatically deletes all duplicates. They are also used a lot in mathematical operations like union, intersections and differences.

x = {"lorem", "ipsum", "dolor"} # set

y = frozenset({"lorem", "ipsum", "dolor"}) # frozenset

print(x) # Output: {'dolor', 'lorem', 'ipsum'}

print(y) # Output: frozenset({'dolor', 'lorem', 'ipsum'})

x.add("sit")

print(x) # Output: {'sit', 'ipsum', 'dolor', 'lorem'}

y.add("sit") # AttributeError: 'frozenset' object has no attribute 'add'

Boolean

Booleans in Python are as straightforward as they come—just two values: True and False. Think of them as the simplest on/off switch in your code, used to represent conditions and control the flow of your program. Whether it’s a result of a comparison, like checking if one value equals another, or determining the outcome of a logical operation, booleans are what tell your program which path to take. Much like sets, booleans are fundamental building blocks in Python, ensuring that your decisions and conditionals work exactly as intended without any extra fuss.

They can be used in things like:

  • Conditional statements
  • Logical operations
  • Conversion from other types
  • Ternary expressions

# Conditional Statements
x = 1
y = 2

if x < y:
    print("x is less than y")
else:
    print("x is not less than y")
# Output: x is less than y

# Logical Operations
a = True
b = False
print(a and b)  # False, because both need to be True for 'and'
print(a or b)   # True, because at least one is True for 'or'
print(not a)    # False, inverts the value of a

# Conversion from other types
print(bool(1))         # True, since non-zero numbers are True
print(bool(0))         # False, zero is considered False
print(bool("Hello"))   # True, non-empty strings are True
print(bool(""))        # False, empty strings are False
print(bool([1,2,3]))   # True, non-empty lists are True
print(bool([]))        # False, empty lists are False

# Ternary Expression
result = "Even" if x == 2 else "Odd"
print(result)  # "Even"

Conclusions

I mentioned that we would be doing a small project for each day. To my consideration we haven’t gotten too much into Python to actual do so here, yesterday we over extended and had to do a bit of research to achieve the mini-project we set for ourselves. What I will be doing is putting everything I show as an example in a Github Repository and create a folder for each day. That way we can see it all in one place and maybe it will be useful for future reference.

Thank you for getting this far and hope to join me for day 3!

Published inTutorials

Be First to Comment

Leave a Reply

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