Python - A beginner-friendly programming language


Python - A beginner-friendly programming language
Comparison between Python, Java, and JavaScript
It is no secret that Python is the most demanded programming language, especially among the developer community. And the reason is its user-friendliness.
Yeah yeah, I know that it is the most important aspect of any application and matters to the users a lot but hey, that doesn’t mean that the ones who develop the apps don’t want ease in their life as well. Python provides this ease to the developers day to day life with its easy syntax and extensive library selection.
Now you have the idea that Python is the most beloved programming language of developers and is easy to learn because of its easy syntax. It should be obvious why it is recommended to the new developers or learners. The best thing about starting your programming journey in Python is that you don’t have to switch to another language if you develop an interest in any specific field. It is used in many fields of Software Engineering. Or, as we say,
It is becoming the all-in-one language that programmers always dreamed of…
Okay! Enough talking, let’s get to some coding because that’s what we love anyway, right?
If you are just starting your journey in the programming world, you need to know some basics i.e., the ABC of programming. So here we are comparing some of the basic concepts of Python with Java (an object-oriented programming language) and JavaScript JS
(a weekly typed programming language).
Variables:
Declaring / Initializing Variables in Python
Unlike multiple other languages, there is no variable declaration in Python. You just assign a value to a variable you want to use in the program.
# variable_name = value
num = 1 # a varaible num is being declared and an integer value is stored in it
st = 'abc' # a varaible str is being declared and a string value is stored in it
flo = 1.0 # a variable flo is being declared and a float value is stored in it
bol = True # a variable bool is being declared and a boolean value is stored in it
The Python interpreter automatically gets the type of the value you assign to the variable.
You can check the type of any variable by passing the variable to a build-in function called type()
# type(variable_name)
type(num) # should return <type 'int'>
type(st) # should return <type 'str'>
type(flo) # should return <type 'float'>
type(bol) # should return <type 'bool'>
Declaring / Initializing Variables in Java
One big disadvantage of Java over Python is that Java is an object-oriented programming language and it doesn’t support functional programming so even for declaring a single variable it will take at least two extra lines to declare a main class and method. Also, it is a strongly typed programming language so you will have to mention the type of a variable at declaration.
In the below code, you can see that we have declared the variables with their respective types by mentioning the type before the variables.
For initializing the variables we have used the syntax that we used for Python code and the reason is that they were already declared before. But the declaration and initialization can be done together as well.
int num = 10;
Finally for checking the type of any variable in Java ((Object)variable_name).getClass().getName())
can be used.
The system.out.println()
is the method for printing the types just as we use print()
in Python.
You might also note that we have used an ;
at the end of each line. This ;
(a semi-colon) is called a terminator in programming languages. While it can be used in Python it is not required.
public class Variables {
public static void main(String args[]) {
// variable declaration
// type variable_name;
int num;
String st;
Float flo;
Boolean bol;
// variable initialization
// variable_name = value
num = 1;
st = "abc";
flo = 1.0f;
bol = true;
// checking variables type
// ((Object)variable_name).getClass().getName()
System.out.println(((Object)num).getClass().getName());
System.out.println(((Object)st).getClass().getName());
System.out.println(((Object)flo).getClass().getName());
System.out.println(((Object)bol).getClass().getName());
}
}
Declaring / Initializing Variables in JavaScript
JavaScript just like Python is also a weekly typed programming language which means you don’t have to explicitly mention the type of the variable you are defining.
In JS three keywords are used for variable declaration.
var
const
let
var
has been used in JS since 1995, and both let
and const
were added to JS in 2015. So if you are planning to deploy your code in older browsers, use var
keyword.
// var | let variable_name
var var1;
let var2;
We can create variables using keywords or without any keywords. For demo purposes here a new variable 3 is initialized without being declared using any keyword.
Also, observe the way const
keyword is used to declare and initialize PI
variable at the same time.
// variable_name = value
var1 = 1;
var2 = 'two';
var3 = false;
console.log(var1);
console.log(var2);
console.log(var3);
// const variable_name = value;
const PI = 3.141592653589793238;
console.log(PI);
Now, let's check the type of each variable.
// typeof variable_name
console.log(typeof var1);
console.log(typeof var2);
console.log(typeof var3);
console.log(typeof PI);
Using const
should be common practice for declaring the variables but if the value of the variable that is being declared needs to be changed we should use let
instead. Also, both let
and const
keywords declare block-scoped variables. This means that a variable declared using var
can be used outside its block while the variable declared using let
or const
can’t.
One thing to keep in mind here is that variables declared using let
can’t be redeclared, and variables declared through const
cannot be re-assigned and it must be assigned a value at the time of declaration i.e., the below code will throw an error.
const var1;
var1 = 10;
Data Structures
Python Data Structures
Data structures are the containers to organize data in groups. Basic Python data structures are,
list
tuples
sets
dictionary
List:
The list is the simplest data structure in Python. As the name suggests it can store the list. You can keep the list of integers, characters, strings, booleans, floats, or all of them.
You can also create a multi-dimensional list which allows you to create lists of multiple lists.
# an empty list
list1 = []
# a simple list
list2 = [1, 2, 3, 4, 5]
# a list containing different data-type
list3 = [1, 'two', False, 4.0, 5]
# multi-dimentional list
list4 = [[1, 2, 3, 4, 5],
[1, 'two', False, 4.0, 5]]
Tuple:
Tuples are just like lists and you can perform almost all basic operations of them that you can perform on the list except for one big difference. Tuples are immutable which means you can’t change the value of the tuple.
# an empty tuple
tuple1 = ()
# a simple tuple
tuple2 = (1, 2, 3, 4, 5)
# a tuple containing different data-type
tuple3 = (1, 'two', False, 4.0, 5)
# multi-dimentional tuple
tuple4 = ((1, 2, 3, 4, 5),
(1, 'two', False, 4.0, 5))
Sets:
A Set is a data structure that is used to store distinct values together. Just like set operations in the set theory of algebra, the sets in Python are best to be used for union, and intersection operations. Sets value can’t be accessed through indexing like list and tuple, so a value at a particular index can also not be updated, but sets are generally mutable. Which means you can modify them.
# an empty set
set1 = set()
# a simple set
set2 = {1, 2, 3, 4, 5}
# a set containing different data-type
set3 = [1, 'two', False, 4.0, 5]
The reason that I’ve created an empty set using set()
method not {}
is that empty curly braces {}
will create an empty dictionary not set.
Dictionary:
A dictionary is another commonly used data structure, especially in the data science world. Dictionary stores data in key-value pairs and is best suitable for cases where you need to find one piece of information with respect to another. For example, storing countries and their capitals.
# an empty dictionary
dict1 = {}
# a simple dictionary
dict2 = {'one': 1, 'two': 2, 'three': 3}
# a dictionary containing different data-type
dict3 = {'one': 1, 2: 'two', True: 'three'}
# multi-dimentional dictionary
dict4 = {1: {'one': 1, 'two': 2, 'three': 3},
'two': {'one': 1, 2: 'two', True: 'three'}}
Java Data Structures
Java also has many data structures. In this article, we are looking into the following data structures that Java offers.
array
linked list
Array:
An array is the simplest data structure that Java offers. But if you are thinking that it is same as lists in Python you are mistaken. An array can only contain values with the same data types i.e. if you have integers and string values you can either store all integers or all strings in one array. Storing different types in one array is not possible. And if the data type is not your concern then you can type-cast integers to string for storing them in the same array.
public class ArrayDataStructure {
public static void main(String args[]) {
int arr1[]; // array declaration
arr1 = new int[5]; // memory allocation
// one dimentional array
int arr2[] = new int[]{1, 2, 3, 4, 5};
for(int i=0; i < arr1.length; i++){
System.out.println(arr2[i]);
}
// multi-dimentionl array
int arr3[][] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10}};
for(int i=0; i < arr3.length; i++) {
for(int j=0; j< arr3[i].length; j++) {
System.out.println(arr3[i][j]);
}
}
}
}
Linked List:
A linked list is as its name suggests a list in which all elements are linked to each other. There are four types of linked-list.
Singly linked lists.
Doubly linked lists.
Circular linked lists.
Circular doubly linked lists.
A singly linked list is the one in which each node is connected to a node after it. The last node is not connected to any element.
A doubly linked list is one in which each node is connected to two adjacent nodes except for the root and last node. The root node doesn’t have a parent node and the last node doesn’t have a child node.
A circular linked list is just like a singly linked list except that the last node is connected to the first node.
And a doubly circular linked list as you might have already guessed is just like a doubly linked list except that the last node is connected to the first one and the first node is connected to the last node.
I am going into much detail as this article is for Python not linked list but you might have got the idea of linked list.
import java.util.LinkedList;
public class LinkedListDataStructure {
public static void main(String args[]) {
// a linked list of string stype
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i=0; i<5; i++) {
list.add(i);
}
System.out.println(list);
}
}
JavaScript Data Structures
JavaScript also has both primitive and non-primitive data structures. But as we have previously discussed primitive (built-in) data structures we will be discussing only these for JS as well.
JavaScript primitive data structures include.
array
object
Array:
Array in JavaScript is just like a list in Python. You can store any value regardless of its data type. And it also offers two dimensional (2D) array, like a 2D list in Python.
// an empty array
arr1 = [];
// a simple array
arr2 = [1, 2, 3, 4, 5];
// a array containing different data-type
arr3 = [1, 'two', false, 4.0, 5];
// multi-dimentional array
arr4 = [[1, 2, 3, 4, 5],
[1, 'two', false, 4.0, 5]];
// printing values
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
Object:
Object in JavaScript is the same as Dictionary in Python i.e. it stores data in key-value pairs. Objects can also store objects, the same as dictionaries can store dictionaries in Python.
// an empty object
obj1 = {}
// a simple object
obj2 = {'one': 1, 'two': 2, 'three': 3}
// a object containing different data-type
obj3 = {'one': 1, 2: 'two', True: 'three'}
// multi-dimentional object
obj4 = {1: {'one': 1, 'two': 2, 'three': 3},
'two': {'one': 1, 2: 'two', True: 'three'}}
// printing values
console.log(obj1);
console.log(obj2);
console.log(obj3);
console.log(obj4);
Control Flow
The control flow is the flow of the program or simply the direction of program execution. In programming languages, there are three control flows,
Sequential
Selection
Repetition
Python Control Flow
Sequential
This is the default flow of the program which is from left to right, and top to bottom.
var = 'Hello World' # this will execute first and assign variable var a string value
var = var + '!' # then this will be executed will will append a string to previous string and update the variable
print(var)
Selection
This is the flow that is based on certain conditions such as if a student gets 80% or above then he/she will be granted a 50% scholarship and if the student gets 90% or above he/she will be granted a 100% scholarship.
percentage = 89
if 80 > percentage >= 90:
print('You have got a full scholarship!')
elif percentage >= 80:
print('You have got a 50% scholarship!')
else:
print('The minimum grade for scholarship in 80%.')
Repetition
It is the flow of the program which executes a block of code again and again. This is generally done through loops. Could be done through recursion as well, but that’s an advanced topic.
The loops we generally used are,
for loop
while loop
var = [1, 2, 3, 4, 5]
# for loop
for num in var:
print(num)
# while loop
i = 0
while i < 5:
print(var[i])
i += 1
The difference between the for and while loops is that the for loop runs finite times, but the while loop runs infinite times until a condition gets false and in certain cases, it needs to be stopped using break
statement.
Java Control Flow
Sequential
In Java, sequential code can be written as follows.
public class Sequential {
public static void main(String args[]) {
String var = "Hello World"; // this will execute first and assign variable var a string value
var = var + '!'; // then this will be executed will will append a string to previous string and update the variable
System.out.println(var);
}
}
Selection
There are two ways of writing selection code in Java. One is using the if - else if - else block. And second is using a switch-case block.
Let's consider the above-mentioned scenario but now Grades are also being displayed for the students who got scholarships.
public class Selection {
public static void main(String args[]) {
int percentage = 89;
// if-elseif-else block
if (percentage < 80 && percentage >= 90) {
System.out.println("You have got a full scholarship!");
} else if (percentage >= 80) {
System.out.println("You have got a 50% scholarship!");
} else {
System.out.println("The minimum grade for scholarship in 80%.");
}
String grade = "A";
//switch-case block
switch(grade) {
case "A+":
System.out.println("You have got A+ grade!");
break;
case "A":
System.out.println("You have got A grade!");
break;
default:
System.out.println("The minimum grade for scholarship in A grade.");
}
}
}
Repetition
In Java, four kinds of loops are generally used.
for loop
for-each loop
while loop
do-while loop
public class Repetition {
public static void main(String args[]) {
int var[] = {1, 2, 3, 4, 5};
// for loop
for (int i=0; i<5; i++) {
System.out.println(var[i]);
}
// for-each loop
for (int v: var) {
System.out.println(v);
}
// while loop
int j = 0;
while (j < 5) {
System.out.println(var[j]);
j++;
}
// do-while loop
int k = 0;
do {
System.out.println(var[k]);
k++;
} while (k < 5);
}
}
The difference between for and for-each loop is that for loop takes a variable, a condition, and an (increment or decrement) operator for(variable; condition; operator)
. Whereas for-each loop takes a variable and an iterator for (variable: iterator)
. While both are for loops the for loop can run infinite numer of times if the condition is never met while the for-each loop can only run a finite number of times.
The difference between the while and do-while loop is that the while loop will run only after checking if the condition is true. But the do-while loop will run one time and then check if the condition is true.
JavaScript Control Flow
Sequential
In JavaScript, the sequential code can be written as follows.
var var1 = 'Hello World'; // this will execute first and assign variable var a string value
var1 = var1 + '!'; // then this will be executed will will append a string to previous string and update the variable
console.log(var1);
Selection
There are two ways to write selection code in JavaScript. if- else if- else block, or using switch- case block.
I am using the same scenario that is used for Java code here.
var percentage = 89
if (80 > percentage >= 90) {
console.log('You have got a full scholarship!');
} else if (percentage >= 80) {
console.log('You have got a 50% scholarship!');
} else {
console.log('The minimum grade for scholarship in 80%.');
}
var grade = "A";
//switch-case block
switch(grade) {
case "A+":
console.log("You have got A+ grade!");
break;
case "A":
console.log("You have got A grade!");
break;
default:
console.log("The minimum grade for scholarship in A grade.");
}
Repetition
Repetition in JavaScript can be achieved most commonly by using for, while, and do-while blocks. There is a forEach
method in JS but it is not like the one in Java. It is more of a method than a loop that’s why it isn’t mentioned in the code below.
There is one more way of repetition which is using methods. Recursion can be used to run a loop. And it can be implemented in all of these three languages.
const var1 = [1, 2, 3, 4, 5];
// for loop
for (var i=0; i<5; i++) {
console.log(var1[i]);
}
// while loop
var j = 0;
while (j < 5) {
console.log(var1[j]);
j++;
}
// do-while loop
var k = 0;
do {
console.log(var1[k]);
k++;
} while (k < 5);
Syntax
Python Syntax
Python is famous for its easy-to-understand English-like syntax. A simple for loop for printing “Hello World!” five times could be written as follows.
In the below code, we can see that it is easy to read and understand the i
is the variable used here for iterating over for loop. And the range is 5 which means it will iterate 5 times, from 0-4. And print()
as anyone can guess will print the string written inside the print()
function
For simplicity, we often use _
when we don't want to use the variable like in the code below. But just to avoid confusion we have used i
here.
for i in range(5):
print("Hello World!")
Java Syntax
Java is an object-oriented programming language. It means that creating a main class (a class with a main method) is something that needs to be done before anything else.
Then it also has a restriction to use curly/round braces. And oh that semicolon! If you forget to use it, not even a single line will work as it is a terminator so if it is not there the JVM (interpreter) will think you are working on a single line. And it will throw a ; expected
error.
public class Syntax {
public static void main(String args[]) {
for (int i=0; i<5; i++) {
System.out.println("Hello World!");
}
}
}
JavaScript Syntax
JavaScript is not an object-oriented language. So doesn’t need any main class like Java. But there are some things like curly/round braces that one has to use while working in JavaScript.
But there is one thing, this ;
semicolon that works as a terminator. Unlike Java it is not required in JavaScript and JS code can be written without using ;
You can see here that we haven’t used a terminator in the console.log()
statement and this will work just fine. This is because ;
in JavaScript as it is just optional.
for (var i=0; i<5; i++) {
console.log("Hello World!")
}
Conclusion
Python is an easy-to-learn, easy-to-use programming language due to its English-like syntax which makes the code easy to read and write. It also forces the use of indentation which makes its code easier to understand as compared to many programming languages like C, Java, and JavaScript which let the programmer use curly braces for defining code blocks.
There are also many reasons that Python is preferred over other programming languages one of these also being its extensive library of packages (libraries) and community which is growing day by day.
Subscribe to my newsletter
Read articles from Samar Jaffri directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Samar Jaffri
Samar Jaffri
A passionate ML Engineer, loves to learn, code and share insights with the 🌍