DEV Community

loading...
Cover image for Python Basics, Python 101

Python Basics, Python 101

EstherWanjiru
・6 min read

Python

"Hello World!! Would be a perfect way to usher the world in to the now well known programming language," Guido van Rossum thought to himself in the 90's.

And in 1991, Python was created as a simple, straight-forward yet a high-level language that is dynamically typed and targets on readability of code It's main purpose is to let you work quickly and integrate systems effectively. Python involves essential and object-oriented programming with wide-ranging and great typical library that has regular memory.

Advantages of Python

1. Easy to Read, Learn and Write
Python has an English-like syntax. This makes it easier to read and understand the code. It is really easy to pick up and learn, that is why a lot of people recommend Python to beginners. You need less lines of code to perform the same task as compared to other major languages.

2. Improved Productivity
Python is a very productive language. Due to the simplicity of Python, developers can focus on solving the problem. You only write less code and get more things done.

3. Interpreted Language
Python is an interpreted language which means that it directly executes the code line by line. In case of any error, it stops further execution and reports back the error which has occurred.

Python shows only one error even if the program has multiple errors. This makes debugging easier.

4. Dynamically Typed
Python doesn’t know the type of variable until we run the code. It automatically assigns the data type during execution. The programmer doesn’t need to worry about declaring variables and their data types.

5. Free and Open-Source
Python comes under the OSI approved open-source license. This makes it free to use and distribute. You can download the source code, modify it and even distribute your version of Python. This is useful for organizations that want to modify some specific behavior and use their version for development.

Installation

Download the latest version of Python for your operating system here: https://www.python.org/downloads/. You can read more about setting up a python development using VS Code from this tutorial: https://www.pythontutorial.net/getting-started/setup-visual-studio-code-for-python/ by pythontutorial.net.

Let's get Started!

  1. Create a folder ie name it First Python Project where all python files will be saved. Then launch the file in Visual Studio Code by using Git Bash by simply right-clicking on the folder and select Git Bash Here. In Git Bash, type code ., it redirects the folder to Visual Studio Code which is the editor of choice in this case.

  2. Create a python file. A python program has an extension of .py For example you have index as the name of the python file, you will save it as index.py.

  3. In our file, let's write our first line of code ie. "Hello World.". We will write

print ("Hello World!")
Enter fullscreen mode Exit fullscreen mode

The print() is a built-in function that displays a message on the screen. In this case, it’ll show the message "Hello, World!".

Execution

When running the file in the terminal, you have to start by writing the python version on your computer which you can quickly confirm by writing

(python --version)
Enter fullscreen mode Exit fullscreen mode

and it will display it below. Now that we have the version, in my case it's Python3, so I'll write Python3 file_name(in my case it's index).py ie.

python3 index.py
Enter fullscreen mode Exit fullscreen mode

Comments

Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Comments starts with a #, and Python will ignore them.

# single line comment

'''
multi line comment
multi line comment
'''
Enter fullscreen mode Exit fullscreen mode

Aritmetic Operators

Operators are used to perform operations on variables and values.

print(2 + 2)  # 4 (addition)
print(2 - 1)  # 1 (subtraction)
print(3 * 3)  # 9 (multiplication)
print(8 / 2)  # 4 (division)
print(2 ** 8)  # 256 (exponent)
print(3 % 2)  # 1 (remainder of the division)
print(11 // 2)  # 5 (floor division)
Enter fullscreen mode Exit fullscreen mode

Variables

Variables are containers for storing data values. Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

x = 85
y = "Ess"
print(x)
print(y)
Enter fullscreen mode Exit fullscreen mode

NB Variables do not need to be declared with any particular type, and can even change type after they have been set.

Data Types

Reference: https://bit.ly/3iC9JuA

In programming, a data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories:

Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:

a = 16
print(type(a))
Enter fullscreen mode Exit fullscreen mode

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'my love' is the same as "my love".
Enter fullscreen mode Exit fullscreen mode

You can display a string literal with the print() function:

Lists

Lists are used to store multiple items in a single variable. A list is one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. They are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.
Lists are created using square brackets:

#Example
#Create a List:

this_list = ["apple", "banana", "cherry"]
print(this_list)
Enter fullscreen mode Exit fullscreen mode

Tuples

Tuples are used to store multiple items in a single variable. A tuple is also one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

#Example
#Create a Tuple:

simple_outfit = ("polo", "jeans", "sneakers")
print(simple_outfit)
Enter fullscreen mode Exit fullscreen mode

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Dictionaries

Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

#Example
#Create and print a dictionary:

accessory = {
  "item": "Watch",
  "model": "Fjord",
  "year": 2019
}
print(accessory)
Enter fullscreen mode Exit fullscreen mode

Sets

Sets store multiple items in a single variable. A set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is both unordered and unindexed. Sets are written with curly brackets.

Example
Create a Set:

thisset = {"denim", "poncho", "barret"}
Enter fullscreen mode Exit fullscreen mode

Booleans

Booleans represent one of two values: True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:

Example
print(1992 > 1991)
print(1992 == 1991)
print(1992 < 1991)
Enter fullscreen mode Exit fullscreen mode

Arrays

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
Enter fullscreen mode Exit fullscreen mode

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. The function then returns data as a result.
In Python a function is defined using the def keyword:

Example
def my_function():
  print("Hello from a function")
Enter fullscreen mode Exit fullscreen mode

Classes

To create a class, use the keyword class:

Example
Create a class named MyClass, with a property named x:

class MyClass:
  x = 5
Enter fullscreen mode Exit fullscreen mode

To understand the meaning of classes and use them in real life applications, we have to understand the built-in init() function.

All classes have a function called init(), which is always executed when the class is being initiated.

Use the init() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Ess", 30)

print(p1.name)
print(p1.age)
Enter fullscreen mode Exit fullscreen mode

I find w3schools very easy to explain and follow through, therefore i looped in a few definitions and examples from there to make it easy following through. I highly recommend this: https://www.w3schools.com/python/default.asp to study a concept or two.

It would be awesome getting feedback from a reader or three ;)

Discussion (0)