DEV Community

Cover image for Introduction To Modern Python
Muriithi Gakuru
Muriithi Gakuru

Posted on • Updated on

Introduction To Modern Python

What is Python

Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects. That's according to our good friend Wikipedia.
Python is best used for automation. It's uses extend to Web, Mobile and Game Development, Machine Learning and Data Science. This is because python can be ran on multiple platforms; windows, linus and mac os.

Getting Started

First things first.
We'll start by downloading a python interpreter for our machine by navigating to here. Funny story, I had written down how to configure your development environment and installation process but decided it wasn't comprehensive enough and would make this lengthy. Please refer here then come back for an in depth introduction.

Writing your first program

We'll start with the ceremonial starter program, Hello World.
You should be able to work on the command prompt REPL(Read–eval–print loop) environment
This is what I mean.

Image description
If you can get that on cmd then we're ready to go, Hurray!

Hello World

Type a print statement to print.

print('Hello World')
# This is a comment
Enter fullscreen mode Exit fullscreen mode

Python is simple like that.

Comments

# This is a single line comment
"""
    This is a multi-line comment
"""
Enter fullscreen mode Exit fullscreen mode

Variable declaration

We declare variables to reuse them later right? Python requires us to assign a value to the variable. You don't need a type identifier since python detects it right away.

my_name = "Muriithi Gakuru"
Enter fullscreen mode Exit fullscreen mode

The snake case is more preferred. This is done by joining variables with an undercase as done above.

Variable types in python

Strings - Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello world' is the same as "hello world"

Numbers - There are three numeric types in python;

  • Integer - is a whole number, positive or negative, without decimals.
a = 251
Enter fullscreen mode Exit fullscreen mode
  • Float - is a number, negative or positive containing one or more decimal points.
b = 19.5
Enter fullscreen mode Exit fullscreen mode
  • Complex - these are written with a "j" as the imaginary part.
c = 15j
Enter fullscreen mode Exit fullscreen mode
  • Booleans - These store an output of either True or False.

Lists

Python lists are used to store data in array format. Different data types can be stored in the same list.

my_list = ['name', 210, 'age', 33.5]
Enter fullscreen mode Exit fullscreen mode

You can call a list's contents using their indices
my_list[0] will give an output of the string 'name' at index 0.
You can use the slicing operation [:] to get an item or a range of items. Example:

name = [120, 'savor', 32.4, 'title']
# if we want to access items from index 1 to the end of the list 
print(name[1:]
Enter fullscreen mode Exit fullscreen mode

this will give an out put of a list;
['savor',32.4, 'title']
if we want to access all items in the list non-inclusive of the last item, we add a negative sign to the slice.

print(name[:-1]
Enter fullscreen mode Exit fullscreen mode

this will give an out put of a list;
[120, 'savor', 32.4]

Tuples

Tuples store data much like lists only that values in a tuple are unchangeable. A tuple is ordered and enclosed in round brackets. They are mostly used to store sensitive data that should not be reassigned later in the program such as user information.

my_tuple = ("Ken", 23)
print(my_tuple)
Enter fullscreen mode Exit fullscreen mode

Sets

They are used to store multiple items in a single variable. Sets contain unique items and there cannot be any duplicates or else they will be eliminated.
Set contents are unchangeable but you can remove or add items to the set. They are enclosed by curly braces.

my_set = {"apple", "banana", "cherry"}
print(my_set)
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Dictionaries store data in key:value pairs. They are enclosed in curly braces. They do not allow duplicates since a value can only be accessed using a single, distinct key. dict is a keyword that refers to a dictionary.

my_dict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(my_dict)
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
# try these out
Enter fullscreen mode Exit fullscreen mode

Loops

Loops take care of indentation according to PEP8

  1. If - Else Python supports all logical operations in mathematics Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b
b = 13
c = 300
if c > b:
  print("c is greater than b")
else:
    print("The else clause was called")
Enter fullscreen mode Exit fullscreen mode
  1. While Loop This executes a list of statements provided the condition is true.
i = 1
while i < 6:
  print(i)
  i += 1
# Note: if i is not incremented, the loop will continue infinitely.
Enter fullscreen mode Exit fullscreen mode
  1. For Loop For loops are used for iterationg through a sequence. This may be a list, dictionary, set or tuple.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Enter fullscreen mode Exit fullscreen mode

This prints the contents of fruits one after the other.
You may also iterate through a string.

Functions

A function is a block of code that only runs when it's called.
Functions enable the resuse of repetitive parts of the program.
Below is a function to print a user's name.

def print_name():
    my_name = "Muriithi Gakuru"
    print('My name is ', my_name)

# functions are called by typing the function name and parentheses

print_name()
Enter fullscreen mode Exit fullscreen mode

A function can take an argument or two so as to receive data dynamically later in the program.

def print_name(my_name):
    print('My name is ', my_name)
# the argument is placed between the parentheses

# call the function by adding the argument in the function
print_name("Muriithi Gakuru")
Enter fullscreen mode Exit fullscreen mode

All these take practice to have them at your fingertips. These are the fundamentals of modern python. I hope you had fun in the journey of being a techie.
credits to w3schools and Unsplash
Cheers

Top comments (9)

Collapse
 
morphzg profile image
MorphZG • Edited

Just small correction. Function name does not not make a call. Instead it is just the reference. You make the call by adding parenthensis.

Try to create the list of functions and than call the function at position 1. List will contain only names. It will look like this:

list = [function1, function2, function3]
list[1]()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
muriithigakuru profile image
Muriithi Gakuru

Thank you for pointing that out. Indeed the function would'nt be called. Without the brackets we'll just get where the function is stored in memory but won't access the result.

Collapse
 
epsi profile image
E.R. Nurwijayadi

I wonder what you mean by modern python.
Is it py2 vs py3?

Is there even, an ancient python?

Collapse
 
muriithigakuru profile image
Muriithi Gakuru

PEP8 brings the notion of Modern Python. A standard way of making magic.

Collapse
 
adachime profile image
AdaChime

Wow! This is a really great piece.

Collapse
 
muriithigakuru profile image
Muriithi Gakuru

Thank you, Cheers.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.