DEV Community

Cover image for Ultimate Python Guide
Amulah
Amulah

Posted on

Ultimate Python Guide

Overview

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language that was created by Guido van Rossum.

Applications for Python

  1. Web Development(Django &Flask)
  2. Game Development(Blender,Unity3d,UDK)
  3. Machine Learning and Artificial Intelligence(Sklearn, )
  4. Data Science and Data Visualization(Pandas, Plotly, Dash)
  5. Web Scraping Applications (Beautifulsoap,ScrapySelinium,Splash)

Getting Python

The source code, binaries, documentation etc., is available on the official website of Python Link

Python IDEs and Code Editors¶

Pycharm : Link
VS Code : Link
Anacoda : Link

We will first look at the basic syntax and language rules to follow when writing a python program; We will use Jupyter notebook
1. Comment
You use the hash symbol for single line comments and single or double quotes for multi-line comments

_#This is a single line comment_
Enter fullscreen mode Exit fullscreen mode

2. Variables
Variable names must start with a letter or an underscore but not numbers and are case sensitive.

x = 1           # int
y = 2.5         # float
name = 'Amal'   # string
is_cool = True  #boolean
manynames= ['Magdaline','Mary','Jane'] #list 
mytuple= (1,2,3) #tupples
d={'email':'lm@hs.com','password':123} # Dictionary 
s = {1, 2.3}  # set 
Enter fullscreen mode Exit fullscreen mode

3. String Formatting

name = 'Lilian'
age = 20
# Concatenate (print Lilian age )
print('Hello, my name is ' + name + ' and I am ' + str(age)) #you must cast age int into a string

Output: Hello, my name is Lilian and I am 20
Enter fullscreen mode Exit fullscreen mode

4. Dictionary
These are data collections which are unordered, changeable and indexed.

person={'name': 'Diana', 'age': 20,'city':'Nairobi'}
# Get value
print(person.get('name'))
Diana
# Add key/value
person['phone'] = '072-999-3333'
person
{'name': 'Diana', 'age': 20, 'phone': '072-999-3333'}
# Get dict keys
print(person.keys())
dict_keys(['name', 'age', 'phone'])
# Get dict items
print(person.items())
dict_items([('name', 'Diana'), ('age', 20), ('phone', '072-999-3333')])
## Copy dict
person2 = person.copy()
person2['city'] = 'Boston'
person2
{'name': 'Diana', 'age': 20, 'phone': '072-999-3333', 'city': 'Boston'}
#remove a person age 
del(person['age'])
person
{'name': 'Diana', 'phone': '072-999-3333'}
person.pop('phone')
'072-999-3333'
# Get length
print(len(person2))
4
# List of dict, like array of objects in javascript
people = [
    {'name': 'Diana', 'age': 20},
    {'name': 'James', 'age': 25}
]
people
[{'name': 'Diana', 'age': 20}, {'name': 'James', 'age': 25}]
Enter fullscreen mode Exit fullscreen mode

5. CONDITIONALS
If/else expressions are used to execute a set of instructions based on whether a statement is true or false.

x = 15
y = 14
if x > y:
  print(f'{x} is greater than {y}')
else:
  print(f'{y} is greater than {x}') 
15 is greater than 14
# elif
if x > y:
  print(f'{x} is greater than {y}')
elif x == y:
  print(f'{x} is equal to {y}')  
else:
  print(f'{y} is greater than {x}')
15 is greater than 14
Enter fullscreen mode Exit fullscreen mode

6. Functions
Functions are defined with the def keyword.
Indentation is used instead of curly braces.
A colon is placed after the parameters.

#function to  square a number
def square(num):
    #return num**2
    print(num**2)

square(10)
100
Enter fullscreen mode Exit fullscreen mode

7. MODULES
A module is a file containing a set of functions to include in your application. There are core python modules which are part of the Python environment, modules you can install using the pip package manager as well as custom modules

# Core modules
import datetime
from datetime import date
import time
from time import time

# Pip module
import pandas as pd
import numpy as np

# Import custom module

# today = datetime.date.today()
today = date.today()
timestamp = time()

today
datetime.date(2022, 2, 19)
Enter fullscreen mode Exit fullscreen mode

Example 1 : Making a basic calculator

# This function adds two numbers
def add(x, y):
    return x + y
# This function subtracts two numbers
def subtract(x, y):
    return x - y
# This function multiplies two numbers
def multiply(x, y):
    return x * y
# This function divides two numbers
def divide(x, y):
    return x / y
Enter fullscreen mode Exit fullscreen mode

Example 2: Function That Generates a Fibonacci Sequence

def fibonacciSequence():
    numberOfTerms = int(input("Hi, enter number of terms to for the Sequence: "))

    # Defining the first two terms that are mandatory    
    # Normally, 0 and 1 are the first and second terms of the series, hence:

    firstNum = 0
    secondNum = 1
    count = 0
    # Ensuring the user enters valid inputs, i.e., Fibonacci sequence starts from 0
    if (numberOfTerms <= 0):
        print("Invalid entry, please enter value more than 0")

    elif(numberOfTerms == 1):
            print("Generating Fibonacci Sequence upto ", numberOfTerms, ": ")
            print(firstNum)

    # For all other cases, i.e., when NumberOfTerms > 1
    else:
        print("Generating Fibonacci sequence upto ", numberOfTerms, ": ")
        while count < numberOfTerms:
            print(firstNum)
            nthNumber = firstNum + secondNum

        #  Swapping the values for firstNum and secondNum
            firstNum = secondNum
            secondNum = nthNumber
            count += 1

# Call the function
fibonacciSequence()
Enter fullscreen mode Exit fullscreen mode

Results for first 10 fibonacci Sequence:

first 10 fibonacci Sequence

Top comments (0)