Learn all about Python's syntax in 6 minutes
Tags: webdev, python, machinelearning, programming
Published: 2021-01-25 16:49:23

Python is a high-level, interpreted and general purpose language with a relaxed syntax influenced heavily by English Language and Mathematics.

Python is used in almost every industry and scientific fields. The most popular use cases are: Data Science.
• Machine Learning.
• Web Development.
• Computer Vision and Image Processing.
• Game Development.
• Medicine and Pharmacology.
• Biology and Bioinformatics.
• Neuroscience and Psychology.
• Robotics
• GUI Development

This article covers the basic syntax and language rules to follow when writing a python program.

##COMMENTS

- You use the hash symbol for single line comments and single or double quotes for multi-line comments

```python
#This is a comment
'''
This is a 
multiline comment
'''
```

## VARIABLES

- Variable names are case sensitive (name and NAME are different variables)
  - Must start with a letter or an underscore
  - Can have numbers but must not start with one
 - Python is loosely-typed (you don’t specify the type when declaring a variable.

```python
 x = 1           # int
 y = 2.5         # float
 name = 'John'   # str
 is_cool = True #boolean

x, y, name, is_cool = (3, 7.5, 'Anna', True) #multiple assignment
# Casting
x = str(x) #int casted to string
y = int(y) #float casted to integer
Print() statement: This outputs the result of an expression in the console.
print(type(y), y) #prints int, 2 to the console
```

## FUNCTIONS

- 	In python, functions are defined with the def keyword. 
- 	Indentation is used instead of curly braces. 
-	 A colon is placed after the parameters. 
- 	No semi-colons.

```python
def getSum(num1, num2):
    total = num1 + num2
    return total
print(getSum(10, 3)) #prints 13
getSum = lambda num1, num2: num1 + num2 #lamba functions are very similar to arrow fns in JS
```

## STRINGS

- Strings in python are surrounded by either single or double quotation marks
- F-Strings enable you easily concatenate two different types without having to cast it first 

```python
name = 'Kingsley'
age = 21

# Concatenate
print('Hello, my name is ' + name + ' and I am ' + str(age)) #you must cast age int into a string
# F-Strings (3.6+)
print(f'Hello, my name is {name} and I am {age}') #with this you don’t need str() helper

#STRING METHODS
s = 'helloworld'

# Capitalize string
s.capitalize()

# Make all uppercase
s.upper()

# Make all lower
s.lower()

# Swap case
s.swapcase()

# Get length
len(s)

# Replace
s.replace('world', 'everyone')

# Count
sub = 'h'
s.count(sub)

# Starts with
s.startswith('hello')

# Ends with
s.endswith('d')

# Split into a list
s.split()

# Find position
s.find('r')

# Is all alphanumeric
s.isalnum()

# Is all alphabetic
s.isalpha()

# Is all numeric
s.isnumeric()
```

## LISTS
-	These are data collections which are ordered, changeable and can have duplicate members


```python
numbers = [1, 2, 3, 4, 5]
fruits_list = ['Apples', 'Oranges', 'Grapes', 'Pears']
# Get a value
print(fruits[1])

#METHODS
# Append to list
fruits.append('Mangos')

# Remove from list
fruits.remove('Grapes')

# Insert into position
fruits.insert(2, 'Strawberries')

# Change value
fruits[0] = 'Blueberries'

# Remove with pop
fruits.pop(2)

# Reverse list
fruits.reverse()

# Sort list
fruits.sort()

# Reverse sort
fruits.sort(reverse=True)
```

## TUPLES
-	These are data collections which are  ordered, unchangeable and can have duplicate members.

```python
# Create tuple
fruits_tuple = ('Apples', 'Oranges', 'Grapes')
# Get value
print(fruits[1]) 
# unchangeable values
fruits[0] = 'Pears' 

# Deletes tuple
del fruits2

## SETS
-	These are data collections which are unordered and doesn’t allow duplicate members
fruits_set = {'Apples', 'Oranges', 'Mango'}
# Add to set
fruits_set.add('Grape')

# Remove from set
fruits_set.remove('Grape')

# Add duplicate
fruits_set.add('Apples')

# Clear set
fruits_set.clear()

# Delete
del fruits_set
 
# Check if in set
print('Apples' in fruits_set)
```

## DICTIONARY
- These are data collections which are unordered, changeable and indexed. Similar syntax to objects in Javascript.
```python
# Get value
print(person['first_name'])
print(person.get('last_name'))
# Get value
print(person['first_name'])
print(person.get('last_name'))
# Add key/value
person['phone'] = '111-222-3333'
# Get dict keys
print(person.keys())

# Get dict items
print(person.items())

# Copy dict, like spread in javascript
person2 = person.copy()
person2['city'] = 'Boston'
#remove a person
del(person['age'])
person.pop('phone')

# Clear
person.clear()

# Get length
print(len(person2))

# List of dict, like array of objects in javascript
people = [
    {'name': 'Martha', 'age': 30},
    {'name': 'Kevin', 'age': 25}
]
```

## LOOPS
- Loops are mechanisms for iterating over a list of items while performing a consistent action on each of them
students = ['Emma', 'Sandy', 'James', 'Ethan']

```python
# Simple for loop
for pupil in students:
  print(f'Current Pupil: {pupil}')

# Break
for pupil in students:
    if person == 'Sara':
    break
   print(f'Current Pupil: {pupil}')

# Continue
for pupil in students:
  if person == 'Sara':
    continue
  print(f'Current Pupil: {pupil}')

# range
for i in range(len(students)):
  print(students[i]) # prints a pupil and increments to the next


# While loops execute a set of statements as long as a condition is true.

count = 0
while count < 10:
  print(f'Count: {count}')
  count += 1
```

## CONDITIONALS
- If/else expressions are used to execute a set of instructions based on whether a statement is true or false. 
```python
x = 15
y = 14
if x > y:
  print(f'{x} is greater than {y}')
#if/else
if x > y:
  print(f'{x} is greater than {y}')
else:
  print(f'{y} is greater than {x}')  
# 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}')

# Logical operators (and, or, not) - Used to combine conditional statements

# and
if x > 4 and x <= 12:
    print(f'{x} is greater than 2 and less than or equal to 10')

# or
if x > 4 or x <= 12:
    print(f'{x} is greater than 2 or less than or equal to 10')

# not
if not(x == y):
  print(f'{x} is not equal to {y}')
```

## 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
```python
# Core modules
import datetime
from datetime import date
import time
from time import time

# Pip module
from camelcase import CamelCase

# Import custom module
import validator
from validator import validate_email

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

c = CamelCase()
# print(c.hump('hello there world'))

email = 'test#test.com'
if validate_email(email):
  print('Email is valid')
else:
  print('Email is bad')
```
## CLASSES.
A class is like a blueprint for creating objects. An object has properties and methods(functions) 
associated with it.

- Like with functions, all fields inside a class must be indented, and a colon must be placed after the class name
- Use def keyword to define a method
- self keyword is used to refer to the current class, just like this keyword in javascript 
```python
class User:

  # Constructor
  def __init__(self, name, email, age):
    self.name = name
    self.email = email
    self.age = age
    
    # Adding Encapsulation of variables... Encapsulation is the concept of making the variables non-accessible or accessible upto some extent from the child classes
    self._private = 1000 # Encapsulated variables are declares with '_' in the constructor.

  def greeting(self):
      return f'My name is {self.name} and I am {self.age}'

  def has_birthday(self):
      self.age += 1
 
 #function for encap variable
  def print_encap(self):
      print(self._private)

# Extend class
class Customer(User):
  # Constructor
  def __init__(self, name, email, age):
      User.__init__(self, name, email, age) #Called proper parent class constructor to make this as proper child inehriting all methods.
      self.name = name
      self.email = email
      self.age = age
      self.balance = 0

  def set_balance(self, balance):
      self.balance = balance

  def greeting(self):
      return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'

#  Init user object
brad = User('Brad Traversy', 'brad@gmail.com', 37)
# Init customer object
janet = Customer('Janet Johnson', 'janet@yahoo.com', 25)

janet.set_balance(500)
print(janet.greeting())

brad.has_birthday()
print(brad.greeting())

#Encapsulation -->
brad.print_encap()
brad._private = 800 #Changing for brad
brad.print_encap()

# Method inherited from parent
janet.print_encap() #Changing the variable for brad doesn't affect janets variable --> Encapsulation
janet._private = 600
janet.print_encap()

#Similary changing janet's doesn't affect brad's variable.
brad.print_encap()

class User:

  # Constructor
  def __init__(self, name, email, age):
    self.name = name
    self.email = email
    self.age = age
  
  def greeting(self):
      return f'My name is {self.name} and I am {self.age}'

  def has_birthday(self):
      self.age += 1
 
 #function for encap variable
  def print_encap(self):
      print(self._private)
      
      # Extend class
class Customer(User):
  # Constructor
  def __init__(self, name, email, age):
      User.__init__(self, name, email, age) #Called proper parent class constructor to make this as 	proper child inheriting all methods.
      self.name = name
      self.email = email
      self.age = age
      self.balance = 0

  def set_balance(self, balance):
      self.balance = balance

  def greeting(self):
      return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
    
    #  Initialize user object
	Kingsley = User('Kingsley Ubah', 'ubah@gmail.com', 21)
	# Init customer object
	cara = Customer('Cara Mason', 'cara@yahoo.com', 25)

	cara.set_balance(500)
	print(cara.greeting())

	kingsley.has_birthday()
	print(kingsley.greeting())

	#Encapsulation -->
    kingsley.print_encap()
    kingsley._private = 800 #Changing for kingsley
    kingsley.print_encap()

    # Method inherited from parent
    cara.print_encap() #Changing the variable for kingsley doesn't affect cara's variable --> 				Encapsulation
    cara._private = 600
    cara.print_encap()

    #Similary changing cara's doesn't affect kingsley's variable.
    cara.print_encap()
```

## FILES
-  Python has functions for creating, reading, updating, and deleting files.

``` python
# Open a file, file is stored in same directory
myFile = open('myfile.txt', 'w')

# Get some info
print('Name: ', myFile.name) #gets the file name
print('Is Closed : ', myFile.closed) #returns a Boolean of either true or false 
print('Opening Mode: ', myFile.mode) #outputs the mode

# Write to file
myFile.write('I love Python')
myFile.write(' and JavaScript')
myFile.close() # closes file

# Append to file
myFile = open('myfile.txt', 'a')
myFile.write(' I also like PHP')
myFile.close()

# Read from file
myFile = open('myfile.txt', 'r+')
text = myFile.read(100) #reads the first 100 characters from file
print(text)
```
## JSON
- JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary
``` python
# Import built-in json object
import json

#  User JSON
userJSON = '{"first_name": "Kingsley", "last_name": "Ubah", "age": 21}'

# Parse to dict
user = json.loads(userJSON)

 print(user)
 print(user['first_name'])

car = {'make': 'Ford', 'model': 'Mustang', 'year': 1970}
# Parse to JSON
carJSON = json.dumps(car)

print(carJSON)
```

With this, we have come to the end of this lesson. If you liked the article and won’t mind seeing more of this, kindly share and follow. Also, you can reach me on [twitter]( https://www.twitter.com/ubahthebuilder "me").

_P/S_: If you are on the look-out for someone who can create top notch content for your blog or website, I am available. Kindly head over to my gig on [Fiverr]( https:// www.fiverr.com/s2/f09ab8dadf "My gig") and make an order or reach me on [twitter]( https://www.twitter.com/ubahthebuilder "me") for a chat.