Getting Started with Python

Python is a high-level, interpreted programming language, known for its straightforward and easily understandable syntax. Designed to facilitate the intuitive expressions, Python empowers developers to quickly bring their prototypes to life. This attribute suits particularly well for machine learning and data science, where ongoing experiments and fine-tuning processes are important, making it as a de facto “lingua franca” in the fields.



Basic Building Blocks of a Python Program

A Python program derives its structure and functionality from essential components that collectively contribute to its design:

  1. Statements: These are instructions that the Python interpreter executes. They can be simple commands like printing a message to the console or more complex logic involving control flow.
  2. Expressions: Combinations of variables, operators, and function calls that evaluate to a single value. They are used within statements to perform calculations, comparisons, and other operations.
  3. Variables: Named container that you can access to a data value. When you assign a value to a variable, Python creates an object that holds the data. The variable name then stores a reference (memory address) pointing to that object.
  4. Comments: Lines of text that are ignored by the Python interpreter, but provide explanations and notes within the code for human readers. Comments improve code readability and maintainability. You can add a comment by placing # in front of your message at anywhere of your file; any following texts will be ignored at execution.
  5. Functions: These are reusable blocks of code designed to perform specific tasks. Functions can be defined with parameters to accept input and return output values, enabling modular and efficient code.
  6. Control Flow: Control flow statements dictate the order in which program’s instructions are executed. These statements, such as if-else conditions and loops, manage the flow of execution, ensuring the program behaves as intended.


Let’s delve deeper into each of these components.

In Python programming, a statement is a unit of code that the Python interpreter can execute. For example, consider the following statement. This is a simple statement that outputs "Hello, Python!" to the console when executed.

print("Hello, Python!")
## Hello, Python!


The statement has a function, print(). The print() function is a built-in function in Python used to output text or values to the console. It takes one or more arguments and displays them as output.

In this example, the print() function takes a literal, "Hello, Python!". In programming, a literal refers to a data value itself in the source code. In the code line shown above, the string literal represents the specific sequence of characters, "Hello, Python!", enclosed in double quotes.

Literals can be directly employed as demonstrated above, or they can alternatively be assigned to a variable for later use. For example:

my_string = "Hello, Python!"
print(my_string)
## Hello, Python!


In this example, the string literal "Hello, Python!" is assigned to a variable named "my_string". Then, the print() function is called with the variable as its argument. When the program runs, it refers to the variable and outputs the text "Hello, Python!" to the console.

When you assign the literal to the variable, Python creates a data object with its memory address. Then the variable holds the associated memory address of the literal object. During execution, Python calls the variable and the variable refers to the memory address to retrieve the data value.

In Python, variable assignment can be done with the assignment operator, =. It assigns the literal on the right-hand side to a variable name on the left-hand side. Unlike some other programming languages, such as Java or TypeScript, you don’t need to explicitly declare the data type of the variable, and the Python interpreter infers it dynamically. All you have to do is just to assign a value using = operator1.

Collectively, these statements can be grouped together in a code block called functions. Functions are reusable block of statements that perform a specific tasks. They take inputs (arguments), execute the underlying statements, and can possibly return output values. For example:

def greetings(str):
    output_string = "Hello, " + str + "!"
    print(output_string)
    
    return output_string


In the example above, the function named greetings takes a single argument, str, which is expected to be a string value. Then in the function body, output_string = "Hello, " + str + "!" creates a new variable output_string, encompassing the argument by two string literals. Next, print(output_string) prints out the output_string. Lastly, it returns the value of the output_string variable from the function. This allows you to capture the greeting message outside the function.

By organizing the three statements under a function, you can call it whenever needed. For example:

my_string = greetings("Andrew")
## Hello, Andrew!


Since the function is not void, meaning it returns some value, you can assign this value to a new variable as shown above. In the provided example, the returned value is assigned to a variable named my_string, and you can subsequently invoke it whenever required.

print(my_string)
## Hello, Andrew!


Inside or outside a function, you can add some flow controls for statements, allowing executions based on certain conditions. For example:

def greetings(str):
  
    if str == "Andrew":
        str = "nerdatandrew"
        
    output_string = "Hello, " + str + "!"
    print(output_string)
    
    return output_string


names = ["Andrew", "Bob", "Charlie"]
my_list = []

for name in names:
    my_list.append(greetings(name))
## Hello, nerdatandrew!
## Hello, Bob!
## Hello, Charlie!
    
print(my_list)
## ['Hello, nerdatandrew!', 'Hello, Bob!', 'Hello, Charlie!']


In the modified greetings function, an if statement checks if the argument is equal to the string "Andrew". If it is, reassign a new literal, "nerdatandrew", to the argument, str. This is a simple example of a flow control.

The flow control is not confined to within a function; the for loop above is another example of flow control. It iterates over each element, name, in the names list to call the greetings function. Then for each element, the returning value from the function is appended to an empty list, my_list.

In Python, a class is a blueprint for creating objects. Objects are instances of classes and classes define attributes (data) and methods (functions) that the objects can have. For example:

class MyClass:
    def __init__(self, name):
        self.name = name

    def greetings(self):
        print(f"Hello, Python! This is {self.name}!")

# Create a new instance of my_name and assign it to the variable my_name 
my_name = MyClass("Andrew") 
type(my_name)
## <class '__main__.MyClass'>
# Call the greetings method on the my_name instance
my_name.greetings()
## Hello, Python! This is Andrew!


In the example above, a Python class is defined with two methods: __init__ and greetings. The __init__ method is a special method in Python classes and serves as the constructor. It takes two parameters: self, which represents the instance of the class, and name. Inside the constructor, the name parameter is assigned to the instance variable self.name. The greetings method is defined within the class and prints a message using the self.name attribute.

A Python module is a file containing related Python functions, classes, and variables. Modules help in breaking down large problems into smaller, manageable pieces, making code organization and reuse more straightforward.

Then a package is a way of organizing related modules into a directory hierarchy. It contains a special file named __init__.py that indicates the directory should be treated as a package. Packages allow you to group related modules together, providing a hierarchical structure to organize and manage your code.

my_package/
├── __init__.py
├── module1.py
└── module2.py


Lastly, a library is a collection of modules and packages that can be used to perform specific tasks or provide functionality in a program. It provides ready-to-use functions, classes, and modules to your colleagues or Python users’ community.



Python Data Types


In computer programming languages, data types define the type of data a variable can hold and the operations that can be performed on that data. They act like “labels” or “categories” that tell the program how to interpret and utilize the information. Depending on which data types involved in, a program behaves differently. So, it is always important to be aware of the specific data type you are working with!

Python has the following data types:

  • None: Singleton object that represents the absence of a value.
  • Numbers: Integers (whole numbers), floats (decimals), and Booleans (True or False values).
  • Strings: Sequence of characters enclosed in quotes.
  • Collections: Lists (ordered sequences), dictionaries (key-value pairs), tuples (immutable lists), and sets (unique elements).

These data types can be categorized as either mutable or immutable. Mutable types are those that can be modified after creation. On the other hand, immutable types cannot be altered once created. Examples of mutable data types include lists, dictionaries, and sets. For example:

my_list = [1, 1, 2, 3]
another_list = my_list

my_list[3] = 4

print(my_list)
## [1, 1, 2, 4]
print(another_list)
## [1, 1, 2, 4]


In the example above, the two variables, my_list and another_list, both reference the same list object. So, when we modify the list using my_list[3]=4 2 3, the change is reflected in both my_list and another_list.

On the other hand, integers, floats, strings, and tuples are immutable data types, meaning that variables defined as such data types cannot be modified once it is created. For example:

x = 11 # Assigning an integer value
y = x # Creating a new reference to the same integer object

x = 23 # Modifying the value of x

print(x) # Output: 23
## 23
print(y) # Output: 11
## 11


When we do x = 23, it doesn’t modify the existing integer variable x; instead, it reassigns 23 to x. The original object with the value 11 is not modified, but is still referenced by y.



Pythonic Way of Writing Code

Indentation

In programming, indentation refers to the spacing or tabbing at the beginning of a line of code to indicate its grouping and structure. Python uses indentation to define the scope of control flow statements and the bodies of functions, classes, and other code blocks.

While it is possible to use a tab for each scoping level, Google’s Python guideline recommends to use four spaces, instead of a tab. Also, when there is a parameter at the first line of a code block, it is a good practice to aligning other parameters. For example:

foo = long_function_name(parameter_one, parameter_two, 
                         parameter_three, parameter_four)


On the other hand, if there is no parameters at the first line of a code block, you should add four more spaces to represent a deeper level of code block scope. For example:

def long_function_name(
        parameter_one, parameter_two, parameter_three,
        parameter_four):
    print(parameter_one)
)

foo = long_function_name(
    parameter_one, parameter_two,
    parameter_Three, parameter_four
)


Naming Conventions

Python naming conventions are essential guidelines for writing clean, readable, and maintainable code. Consistent naming practices improve code clarity for both yourself and other Python programmers working on the same project. Here’s a breakdown of the key conventions:

Variable and Function Names

  • Lowercase with underscores: Use lowercase letters with underscores to separate words. This is called the snake case, and is the mose common style for variable and function names in Python.
  • Avoid single-letter names: While technically allowed, using single-letter variables names, such as x, y, or i, can make code less readable, particularly for complex operations. Opt for more descriptive names that reveal the purpose of the variable.

Class, Constant, Modules, and Package Names

  • PascalCase: Use PascalCase, where the first letter of each word is uppercase, for class names.
  • SCREAMING_SNAKE_CASE: Use SCREAMING_SNAKE_CASE for constants4. Similar to snake case, each word is separated by underscore, but use uppercase letters for constant values.
  • snake_case: Use snake_Case for module and package names.

Additional Tips

Choose names that clearly convey the purpose of a variable, function, class, or module. This practice enhances code readability and maintainability. Additionally, aim for consistency in your naming style across your project. A uniform coding style contributes to an easier-to-navigate codebase.

import this
## The Zen of Python, by Tim Peters
## 
## Beautiful is better than ugly.
## Explicit is better than implicit.
## Simple is better than complex.
## Complex is better than complicated.
## Flat is better than nested.
## Sparse is better than dense.
## Readability counts.
## Special cases aren't special enough to break the rules.
## Although practicality beats purity.
## Errors should never pass silently.
## Unless explicitly silenced.
## In the face of ambiguity, refuse the temptation to guess.
## There should be one-- and preferably only one --obvious way to do it.
## Although that way may not be obvious at first unless you're Dutch.
## Now is better than never.
## Although never is often better than *right* now.
## If the implementation is hard to explain, it's a bad idea.
## If the implementation is easy to explain, it may be a good idea.
## Namespaces are one honking great idea -- let's do more of those!

  1. In Java programming language, to assign a value to a variable, you first need to declare the data type of the variable before using it. For example, to assign an integer value 5 to a variable x in Java, you must add the type information int x = 5.↩︎

  2. Replace the fourth element of the list as 4.↩︎

  3. Python uses zero-based indexing. So, my_list[3] refers to the 4th element in the list.↩︎

  4. Constants are variables whose values are meant to be fixed throughout the program.↩︎

Post a Comment

0 Comments