Hello World

Introduction to Python

alt text

What is the Python Programming Language?

Python is a high-level, interpreted programming language. It was first released in 1991 and has since become a popular language for web development, data science, and scientific computing. Python is known for its simplicity, readability, and flexibility, making it a great choice for beginners and experienced developers alike. It has a large and active community of users and developers, and a wealth of libraries and frameworks that make it easy to build complex applications quickly.

There are many things that are important to know when learning the Python programming language. Here are a few key points:

  • Python is a high-level, interpreted language. This means that it is easy to learn and read, but it may not run as fast as a lower-level language like C or C++.

  • Python is dynamically-typed, which means that you don't need to specify the data type of a variable when you declare it.

  • Python uses indentation to define code blocks, rather than curly braces like many other languages.

  • Python has a large standard library, which means that many common programming tasks, such as connecting to a web server or reading and writing files, can be accomplished with minimal code.

  • Python has a large and active community, which makes it a great choice for developing open-source projects.

  • Python is widely used in scientific computing, data analysis, artificial intelligence, and web development.

  • There are two main versions of Python in widespread use today: Python 2 and Python 3. They are similar, but there are a few key differences between the two, so it's important to use the right version for your project.

Python Installation

There are a few ways to install Python, depending on your operating system and whether you want to install the latest version or a specific version. Here are some general steps to follow:

  • Go to the official Python website (https://www.python.org/) and click on the "Downloads" link.
  • On the downloads page, you will see a list of the latest stable releases of Python. Choose the version you want to install by clicking on the corresponding download link.
  • If you are running Windows, a Python installer will be downloaded to your computer. Run the installer and follow the prompts to install Python, make sure to select the option to add Python to your PATH, so you can run Python from the command line.
  • If you are running macOS or Linux, you can also download the Python installer, but there are other options available as well. For example, you can use a package manager (such as Homebrew or apt-get) to install Python. Alternatively, you can build and install Python from source code.

Once Python is installed, you can check the version by running the following command in a terminal or command prompt:

python --version

This will print the version of Python that is installed on your system.

What is a Variables?

A variable in Python is a symbolic name that serves as a reference or pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. However, the data is still contained within the object.

In Python, a variable is a named location in memory that stores a value. Variables are used to store data values in programs. When you create a variable, you specify a name for the variable and a value to store in the variable. You can then use the variable name in your program to refer to the value stored in the variable.

For example, you might create a variable named x and assign it the value 10. You can then use the variable x in your program to refer to the value 10.

# In this example, the variable x is created and assigned the value 10. 
# You can then use the variable x in your program like this:
variable = 1

# You can also assign a new value to a variable using 
# the assignment operator (=). For example:
variable = 2

# A variable with a type hint
variable_with_type: int = 1

print(variable_with_type) # print the result of our variable

Variable Rules in Python

  • A variable must start with a letter or the underscore character.

  • A variable cannot start with a number.

  • A variable can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • Variables are case-sensitive (age, Age and AGE are three different variables)

Data Types

For short, a data type describes a set of possible values and operations that can be performed on a variable

In Python, a data type is a category for values. Every value in Python has a data type, which determines the kind of operations that can be performed on that value and the way the value can be stored in memory.

There are several built-in data types in Python, including:

  • Numbers: Python has three types of numbers: integers (int), floating-point numbers (float), and complex numbers (complex). Integers are whole numbers, while floating-point numbers have decimal points. Complex numbers have a real and imaginary part.

  • Strings: A string is a sequence of characters, represented by either single quotes (') or double quotes ("). Strings can contain letters, numbers, and special characters.

  • Lists: A list is an ordered collection of values that can be of any data type. Lists are written as a series of values separated by commas and enclosed in square brackets.

  • Tuples: A tuple is similar to a list, but it is immutable, meaning that its values cannot be modified once it is created. Tuples are written as a series of values separated by commas and enclosed in parentheses.

  • Sets: A set is an unordered collection of unique values. Sets are written as a series of values separated by commas and enclosed in curly braces.

  • Dictionaries: A dictionary is a collection of key-value pairs. The keys must be unique and are used to retrieve the corresponding values. Dictionaries are written as a series of key-value pairs separated by commas and enclosed in curly braces.

In addition to these built-in data types, you can also define your own data types in Python using classes (more of this in an advanced topic)

Data Structures

  • In computer science, a data structure is a way of organizing and storing data in a computer so that it can be accessed and modified efficiently. Python has a number of built-in data structures, which can be used to store and organize data in an efficient manner.

  • Python's basic data structures include list, set, tuples, and dictionary. Each data structure is distinct in its own way. Data structures are "containers" that organize and categorize data. The mutability and order of the data structures differs from one data structure to the other.

  • Some of the most common data structures in Python include:

  • Lists: Lists are ordered collections of objects. They can store elements of different data types, and are implemented as arrays in Python. Lists are mutable, which means you can change their contents after they have been created.

  • Tuples: Tuples are also ordered collections of objects, but they are immutable, which means you cannot change their contents after they have been created. Tuples are often used to store data that should not be modified, such as records in a database.

  • Dictionaries: Dictionaries are unordered collections of key-value pairs. They are implemented using hash tables in Python, and are very efficient for looking up values based on their keys.

  • Sets: Sets are unordered collections of unique elements. They are useful for storing data that does not need to be in a particular order, and for removing duplicates from a list.

  • Strings: Strings are sequences of characters. They are immutable, which means you cannot change the contents of a string after it has been created. Strings are often used to store and manipulate text data.

Numbers

Python has three built-in numeric data types: integers, floating-point numbers, and complex numbers. In this section, you'll learn about integers and floating-point numbers, which are the two most commonly used number types. You'll learn about complex numbers in a later section.

number = 1
decimal_number1 = .5
decimal_number2 = 10.5

# you can use the underscores to make the numbers more visible when coding
# The underscores will not be added to the output
salary = 21_500_000

pi = 3.142
r = 5

# simple arithmetic operation using python number type
area = pi * r ** r
print(area)

String

A string is a collection of characters wrapped in a single or double quote. Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

first_name = "Marvelous"
last_name = "Akporowho"

# String formating patterns (Different ways to format your python strings)
full_name1 = first_name + " " + last_name
full_name2 = f'{first_name} {last_name}'
full_name3 = '{} {}'.format(first_name, last_name)

print(full_name1) # print the value of full_name1
print(full_name2) # print the value of full_name2
print(full_name3) # print the value of full_name3

Boolean

Python boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions

isMarried = True

print(type(isMarried))

if(not isMarried):
    print("John is not Married")
else:
    print("John is married")

Constants

In Python, a constant is a variable whose value remains unchanged throughout the program. Constants are usually defined in all capital letters so that they can be easily identified.

In Python, there is no built-in support for constants. However, you can define constants in your program by assigning a value to a variable and then not changing the value of the variable.

Here is an example of how to define and use constants in Python:

"""
Constants -> Python doesn't support constants, 
but we use the uppercase letters to show 
that it is a constant
"""

WEBSITE_HOST = 'https://solomonmarvel.com'

print(WEBSITE_HOST)


# code example

PI = 3.14159265

def calculate_area(radius):
  return PI * radius * radius

radius = 10
area = calculate_area(radius)
print(f"The area of a circle with radius {radius} is {area}")

Python Comments

Comments in Python is the inclusion of short descriptions along with the code to increase its readability. A developer uses them to write his or her thought process while writing the code. It explains the basic logic behind why a particular line of code was written

# This is a single line comment in python

"""
  This is a doc type/multi line comment
  in python
"""

Type Conversion

Type conversion is the process of converting a data type into another data type. Implicit type conversion is performed by a Python interpreter only. Explicit type conversion is performed by the user by explicitly using type conversion functions in the program code. Explicit type conversion is also known as typecasting

x: int = 20
y = str(x)
z = int(y)
a = float(z)

name = "10"
other_name = int(name)
print(type(a))

Control Flow in Python

A program's control flow is the order in which the program's code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls. Python has three types of control structures: Sequential - default mode. Selection - used for decisions and branching.

If statement in python

Image result for if statement in python In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.

# example 1: Make a guess game
guess = 5
if(int(guess) == 7):
    print('You won')
    

# example 2: if statement example 2
if 2>5 and 2>1:
    print("One of this condition is correct")


# examle 3: if elif else conditionals
name = "Marvelos"

if name == "Marvelous":
    print(name)
elif name == "John":
    print('name is not marv')
else:
    print('The name is neither Marvelous nor John')

    
# if statement short hand (tenary operator)    
condition = True if 5 > 5 else False

For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

# for loop control flow - example 1
for i in range(2):
    if i == 0:
        continue
    elif i%2 == 0:
        print (f'{i} is an even number')
    else:
        print(f'{i} is an odd number')

name = "Joy"
result = "Name is Joy" if name == "Joy" else "Name is not Joy"
print(result)

For loop break keyword

'break' in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. A typical scenario of using the Break in Python is when an external condition triggers the loop's termination.

# Using the continue keyword in a loop
for i in range(50):
    if(i == 25):
        break
    print(i)

For loop continue keyword

'continue' in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to skip a certain item and move to the next in a loop, 'continue' will help you achieve that.

# Using the continue keyword in a loop
for i in range(50):
    if(i == 25):
        continue
    print(i)

While loop in python

A while loop will run a piece of code while a condition is True. It will keep executing the desired set of code statements until that condition is no longer True. A while loop will always first check the condition before running. If the condition evaluates to True then the loop will run the code within the loop's body.

# While loop

max = 5
count = 1
while count < max:
    print("We are live")
    count += 1