Already familiar with Programming? Learn Python Syntax in 5 Minutes.

Published Aug 16, 2017
Already familiar with Programming? Learn Python Syntax in 5 Minutes.

If you’re reading this, you’re most likely a programmer who has written code in Java, C#, JavaScript, or some other programming language. With that said, you may not be familiar with Python and would like to get familiar with the syntax in the shortest possible time. Right? Cool! This is just the post for you.

In this article, we will be using Python 3.

Python is an object-oriented programming language. It is dynamically typed — you don't have to specify the datatype of a variable while declaring it like you do in Java. In fact, you don't even have to declare a variable with let or const, unlike in JavaScript.

Integers

public int numberOfCars = 34; 		# Java
const numberOfCars = 34;  		# JavaScript
number_of_cars = 34  			# Python

As you can see, variable names are lowercase with words separated by underscores. This is the convention in Python for variable and function names. Mixed case is only allowed when it's already the prevailing style. Also, in Python, you shouldn't end statements with a semicolon.

As with other programming languages, Python variables support all arithmetic operations like addition (+), subtraction (-), multiplication (*), division (/), floor division(//), modulus(%) and exponent (**). Python also allows you to convert variables to integers or float with their respective built-in functions.

pi = 3.14159
hours = 24

int(pi) = 3
float(hours) = 24.0

Strings

Strings in Python can be defined using single quote('), double quotes("), or 3X quotes(""") for multi-line strings. Some string methods include

'hello'.capitalize() == 'Hello' # Capitalizes first letter of the string
'holaalaa'.count('a') == 4  # Returns how many times a substring occurs in the string

'holaalaa'.find('a') == 3  # Returns the index of the first occurence of the substring in the string
'holaalaa'.replace('a', 'e') == 'holeelee'  # Replaces all occurences of the first argument in the string with the second argument

'1234'.isdigit() == True  # Useful when converting to int. Returns True if the string contains only digits, and False otherwise.
'hello'.isalpha() == True  # Returns True if all characters in string are alphabets and False otherwise.

"some, useful, value".split(',') == ['some', ' useful', ' value']  # Returns an array with the string split at the specified point into elements of the array
len('holaalaa') == 8  # Returns length of string

Find more string methods here

You can do some other things with strings like

alpha = 'a'
beta = 'b'

# Using the string Format function
print('The first letter is {0} and the second letter {1}'.format(alpha, beta)) == 'The first letter is a and the second letter b'

# Using string interpolation
print(f'The first letter is {alpha} and the second letter {beta}') == 'The first letter is a and the second letter b'

Booleans

Booleans in Python are True and False with capital T and F, respectively — some other languages use lowercase true and false. Also, None in Python can be equated to null in other languages.

python_article = True
java_article = False
int(python_article) == 1  # True returns the value 1 when passed into int()
int(java_article) == 0  # False returns the value 0 when passed into int()
str(python_article) == "True"  # Returns the boolean as a string

If Statements

Python uses indentation instead of curly braces for any code blocks. This includes if statements, loops and functions. The beginning statement of each code block ends with a colon.

text = "Python"
number = 7
if text or number:
  print("This is Python")  
else:
  print("This is something else")
    
Prints  # This is Python

As you can see, any string that is not an empty string has a truthy value. The same goes for integers greater than zero and non-empty lists. As such, truthy values are considered true in "if" statements. Also, Python uses or instead of || and and instead of && as logical operators. You can also add the not keyword to reverse the logical state so the "else" block will run instead.

The "elif" statement below which uses the is keyword is considered false since the variables on either side point to different objects.

value = True

if not value:
  print("Value is False")
elif value is None:
  print("Value is None")
else:
  print("Value is True")
    
Prints  # Value is True

Writing ternary statements is as simple as writing the "if" statement on one line, like so:

valuables = ['gold', 'diamonds']
print("Rich") if valuables else ("Poor")  # Since the list is not empty, valuables are truthy
Prints # Rich

Lists

Lists in Python works like arrays in Java and JavaScript. Most operations are similar. Lists can be sliced and indexed.

student_names = ['Mark', 'John', 'James']  
student_names[0] == 'Mark'  # Returns first element in the list
student_names[-1] == 'James'  # Returns last element in the list
student_names[-2] == 'John' # Returns second to the last element in the list
student_names[1:3] == ['John', 'James']  # Slices the list and returns a shallow copy

Some list operations can only be carried out with list functions. Attempting to add a new element to a list using index >= length of array will throw an error.

student_names = ['Mark', 'John', 'James']
student_names[3] = "David"  # Throws an error
student_names.append("David")  # Add to the end of the list
student_names == ['Mark', 'John', 'James', 'David']

student_names.insert(1, 'Paul')  # Inserts string at the specified position
student_names == ['Mark', 'Paul', 'John', 'James', 'David']

student_names.remove('John')  # Removes the object from the list
student_names == ['Mark', 'Paul', 'James', 'David']

del student_names[3]  # Deletes the object in position 3
student_names == ['Mark', 'Paul', 'James']

'Paul' in student_names == True  # Returns true if object is found in list
len(student_names) == 3  # Returns the length of the list

You can learn more about Python Lists here.

Loops

Python for loop works like the forEach in JavaScript. It can be written like:

for student in student_names:
  print(student)

This loops through the entire list or iterable object and carries out the function for each element in the iterable. What if you only want to loop through a section of the list? One way is to loop through a shallow copy of the list.

student_names == ['Mark', 'Paul', 'John', 'James', 'David']
for student in student_names[1:4]
  print student
    
# Prints    
Paul
John
James

You can also use the range function to create an iterable on the fly.

x = 0
for index in range(10):  # Creates a  list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  x = index * 10
    if index == 5:
    	break
    print(x)
    
# Prints
0
10
20
30
40

for index in range(3, 8):  # Creates a list [3, 4, 5, 6, 7]
  x = index * 10
    if index == 5:
    	continue
    print(x)

# Prints
30
40
60
70

We use the keywords break to break out of the first loop and continue to skip an action at a particular point in the second loop.

While loops also use break and continue in a similar manner like in other languages that you may know.

Dictionaries

Dictionaries are very useful when you need to store structured data. Like objects in other programming languages, Python dictionaries allow you to save key-value pairs in one place. We have nested dictionaries when a key has a dictionary as its value. We can retrieve the keys and values in a dictionary.

student = {'first_name': 'Mark', 'last_name': 'Jones', 'age': 13, 'sport': 'football'}
student['first_name'] == 'Mark'  # Returns the value whose key is specified

student['last_name'] = 'James'  # Changes the specified key to the new value
student == {'first_name': 'Mark', 'last_name': 'James', 'age': 13, 'sport': 'football'}

del student['sport']  # Deletes the key-value pair of the specified key
student == {'first_name': 'Mark', 'last_name': 'James', 'age': 13}

student.keys() == ['first_name', 'last_name', 'age']  # Returns a list of all the keys in the dictionary
student.values() == ['Mark', 'James', 13]  # Returns a list of all the values in the dictionary

Function

As we already know, a function is a block of organized and reusable code that is used to perform a certain action. There are many built-in functions in Python, a few of which we've seen earlier. A few of them include:

str(32) == "32"
int("32") == 32
input("How old are you? ")  # input() lets you request an input from a user and returns the value

Find a list of Python Built-In Functions here.
To define your own function in Python, use the def keyword.

def get_data():
  return data

Like in JavaScript, you can specify default arguments for your function when defining them, so that it becomes optional to pass in the specified argument.

def get_student_data(student_name, student_id=035):
  data = {name: student_name, id: student_id}
    return data

In the case above, it's compulsory to pass in student_name when you call this function but it's optional to pass in student_id. If you pass in the student_id argument, the function will use the value. However, if you fail to pass in student_id, it will use the default argument specified when the function was defined.

You can use *args (arguments) and **kwargs (keyword arguments) to let your functions take an arbitrary number of arguments. While *args takes in an array of positional elements, **kwargs takes in an object of keyword arguments.

def get_student_data(name)  # 1 positional argument
def get_student_data(name, id=35)  # 1 positional, 1 keyword argument

def get_student_data(*args, **kwargs):
    for argument in args:
        print(argument)
    for keyword in kwargs:
        print(keyword, ":", kwargs[keyword])

get_student_data("John", 13, id=35, school="Cambridge")

# Prints
John
13
id : 35
school : Cambridge

Classes

Classes in Python are defined using the keyword class. Classes may define a special method called __init__() to be automatically invoked for newly created class instances.

class Student:
  school = "Cambridge"  # Class variable shared by all instances
    
  def __init__(self, name):
    	self.name = name  # Instance variable unique to each instance
        
    def get_student_name(self):
    	print(self.name)
        
jonah = Student('Jonah')  # Creating an instance of a class
jonah.get_student_name()  ==  'Jonah'

A class can inherit from another class called the Base class. Multiple Inheritance is also supported in Python

class HighSchoolStudent(Student):
  school = "Cambridge High School"  # Overrides the class variable of the base class
    
class NewClass(BaseClass1, BaseClass2, BaseClass3)  # Shows multiple inheritance

Exceptions

Exceptions in Python are handled using the try-except block. The raise statement allows you to force an exception to occur and a finally clause can contain actions that will execute under all circumstances whether there are exceptions or not.

try:
    raise TypeError("Why did you raise an Error?")
except TypeError as err:
    print("Error:", err)
else:						# This block will run if there's no exception
    print("No error was raised")
finally:
    print("We raised an error because we can")
    
# Prints
Error: Why did you raise an Error?
We raised an error because we can

To keep this article short, we will end here. This is by no means an exhaustive tutorial on Python but rather, a short article to get you acquainted with the language. This way, you can easily read, understand, and write Python code yourself. The Python documentation has all of the other information you'll need. If you run into any issues, visit StackOverflow. Python has a great online community and you'll want to leverage that as you learn the language.

Useful Resources

Discover and read more posts from Ukwuoma Ignatius
get started