This article was published as a part of the Data Science Blogathon.
Every time I started to learn a new programming language, I was stuck with books and courses explaining the very basic concept of variables, loops, and functions over and over again. In this article, I will skip these parts and just show you how these things look like in Python so that you can code right away.
- The obligatory “hello world” – Example
- How to install and use Python on your system (very easy)
- Python basics (the core of the article)
- Python OOP (you might skip this)
- How to continue from here
1. “Hello world”
Well, not exactly hello world. We ask the user for his name and greet him in person.
name = input("What is your name? ") print("Hello " + name)
input() takes an argument to prompt at the screen and returns the key input, while print() prints something on the screen. No need to declare a “main” function or include any libraries. Get used to simple when programming in Python.
Setting up Python is pretty straightforward. If you are using Linux Python should already be included with your system. Just try
to check it along with the version.
If Python is not already installed, go to https://www.python.org/downloads/ and download Python for your OS.
To run Python scripts simply type
You might edit your scripts with any text editor, but if you want some more comfort, I would recommend the community (free) edition of pycharm. Make sure you click the correct link (on the right) for the community edition.
Another excellent way to learn python is to use Jupyter Notebook. Think of that as an interactive parser on steroids. It takes a bit to set up and get used to it though, so I won’t cover that here. Leave a comment if you would like me to write an article about Jupyter Notebook.
3. Python basics
Now we are ready to get our feet wet. I’ll show you a (nonsense) code snippet which shows the very basic elements of Python. You can use it as a reference if you are for instance wondering “How do I define a function again?“. I’ll go into the details of each segment right after the snippet.
# This is a comment # some variables num_var = 1 str_var = "Hallo" list_var = [1, "2", 3.5, 3+5] arr_bool = not True and 3 != 4 # control structures if num_var == 1: print("num_var = 1") elif num_var != 2 and not num_var > 7: print("num_var is not 2") else: num_var = 0 # loop - prints the elements of list_var 3 times. for i in range(3): for j in list_var: print(j) while num_var < 2: num_var += 1 # function definition def root(x, y=2): return x**(1 / y) print(root(2)) # 1.414... print(root(8,3)) # 2.0 # array operations my_list = [1, 2, 3, 4, 5] print(my_list) # 1 print(my_list[2:4]) # [3,4]
So, let’s start with comments. Just use an #. Everything after the # will be considered a comment.
Next are variables. You do not need to declare them in any way, Python will automatically decide which type to use. The snippet shows int/float, an array (called list in Python lingo), and boolean. Just for completeness, there are also some more advanced types like complex numbers, sets, and dictionaries which I will not cover here.
Typical operators on variables are the basic +,-,/,* and more advanced % (modulo division), // (integer division), ** (power function). Boolean functions use words like “and”, “or”, “not”. The logical comparisons are ==, !=, <, >, <= and >=.
Next is a simple conditional “if”. What you will notice there are no brackets, which is a very unusual sight. How does Python know which part belongs to what? It works by using indentation instead of brackets. The code that will be executed if the condition is fulfilled starts after the “:” and ends after the indented block. So it is very important to keep the proper level of indentation! Again: Indentation replaces brackets.
If can have an elif (else if) and an else part.
Loops: You may loop over a so-called “iterable”. Don’t bother the technical term, basically, you can execute a statement x times by using
for i in range(x)
Please note that i will start with “0” and ends with x-1.
What is pretty cool though is that you can also use a list instead. Python makes life really easy here. The snippet shows a loop that prints the items of the list 3 times.
The while loop is pretty self-explaining.
Let’s move on to function declaration:
def root(x, y=2):
defines a function with two arguments x and y (with a default value of 2) and returns the yth root of x. You call the function by simply using root().
The last part of the basics shows the usage of lists. If you want to access a single element of a list, use square brackets and the index number. Just remember to start counting at 0. You can also access a part of the list instead. This is a bit counter-intuitive since listname[a:b] returns a list of elements starting with the ath element and ends with the element _before_ the bth element. This often leads to some confusion and hard to find bugs.
And that’s it with fundamental Python basics – you are now ready to write your first scripts and experiment a little bit with Python. Stay tuned for object-oriented programming and some hints on where to learn more.
4. Object-oriented programming
If you are in OOP then yes, Python can do this as well. Here is again some code snippet:
# Class definition class Pet: # Class variable sound = "makes some noise" # class constructor def __init__(self, name, animal): self.name = name + " the " + animal # class method def make_noise(self): return self.name + " " + self.sound # Create an object peter = Pet('Peter', 'turtle') print(peter.name) # prints "Peter the turtle" print(peter.make_noise()) # "Peter the turtle makes some noise" # Child classes class Dog(Pet): sound = "barks" # calling the super class def __init__(self, name): super().__init__(name, "dog") spike = Dog("Spike") print(spike.make_noise()) # Spike the dog barks
Here we defined a class named Pet, created a subclass Dog which inherits from Pet, and showed some class methods and variables.
But let’s start with
This is about the same syntax as we already have seen from function definitions. If you use an argument as in
this class is defined as a subclass, stating its parent class as an argument.
Any code you use indented is treated as code belonging to the class (remember, the indentation replaces the brackets). So “sound” is a variable available only within the class aka a predicate.
We skip the constructor __init__ for a second and start with the class method make_noise(self). You might wonder what that “self” means. It references the object that called this method. So self.sound and self.name refers to the predicate’s sound and name.
The method __init__ is the constructor method. I assume you are familiar with basic OOP, so I just mention at this point that this method is called upon the creation of an object. The usage of self.name and name might be a little bit confusing, but just remember that self.name refers to the predicate stored with the object and name refers to the argument that was passed when calling the method.
You can create an object by object = class(parameters), in this case
peter = Pet('Peter', 'turtle')
This calls the constructor and returns the new object.
To access the predicates, call object.predicate, like
Note that there is no distinction between private and public predicates like e.g. in C++.
Calling a method works similarly to an object.method(parameters), see
Now let’s create a child class:
inherits the predicates and methods by its parent class. You can overwrite any predicates and methods of course. To call the superclass methods you use a “super()” like:
That’s a short intro to the OOP features of Python to get you going. Of course, there are some more features like overloading, static methods, multiple inheritances, but that would be at least one article on its own.
5. That’s all, folks!
Congratulations! You now know enough basics to write scripts in Python. If you want to know more, there are literally thousands of articles, tutorials, and courses available. While I have my favorites, I’d absolutely recommend you to check out the official Python website, https://wiki.python.org/moin/BeginnersGuide lists a lot of up-to-date links where you further information.
Guys (and gals), this is the very first article I wrote (and I am not a native speaker as you surely noticed by now), so I would appreciate any comment on style, content, and otherwise. Thank you!
And most important: Have fun coding!
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.You can also read this article on our Mobile APP