Skip to main content

Python in 5 Minutes


This blog is for:

- Anyone who wishes to learn Python quickly so they can jump into making programs as quickly as possible.

- An amateur Python programmer who has just learnt the language and is unsure about its syntactical subtleties. Consider this as your online Handbook for reference.


In my opinion, you should hardly take any time to learn the python syntax, if you haven't yet started. Of course, you should spend time getting accustomed to it, but the language is so awesome that it'll get a hold of you, before you get a hold of it.

Now, I'm assuming that you're remotely aware of what functions, loops, variables and print/input statements are in some other language. If you satisfy this requirement, you're all set! If you don't, I've still tried to explain concepts in general and hope that you understand them if you're a complete new-comer.

Okay, let's begin!

I've grouped the Python language syntax into 6 sections which I think are the most widely used statements and you'll hardly ever need anything else apart from these. Here are they:

1. Variable Declarations
2. Print and Input Commands
3. Loops
4. Decision Making statements
5. Function Definition
6. Classes

Variable Declarations

Basic Variables

A quantity whose value is susceptible to change. Be it an integer, a floating point number, or a string or a character, here's how you store a variable:   
a = 5
       
No semicolons, no datatype. Python automatically decides the datatype of the variable depending on the data.

Lists

Let's say we want to store a group of variables together. Here's how that'll happen:

list = []
# or
list1 = ['a', 'b', 'c']

One additional thing to note here: # is used whenever you need to comment out a line of code. Maybe you need a line to better explain your code to someone, or yourself, so you write something that can be referred to next to the said line.

To refer to a number inside list1, you need to:

list1[1]
Output: 'b'

Here, 0, 1, 2 are the indexes of the list1 variable.

Arrays

A list stores a set of variables, but an array stores a set of same datatype of variables. Basically, we can have:

list = [1, "two", 3.0]

                           
But this won't hold for arrays. Arrays are more strict; well, they are basically arrays. It's just that lists are much cooler. To explicitly declare an array (like the C language's array), we have to make use of a module in Python. At the top of your code, write:

from array import array

And at the line where you have to declare an array, simply call the array function:

arr = array(1)

Tuples

Tuples are lists which cannot be changed later in the program. Consider them as const lists. Tuples are defined by parantheses. So to declare, you try this:

atuple = (1, "Two", 3.0, 4)

Dictionary

Dictionaries are basically a way to store a collection of data in the format of key-value pairs. Let's say I have to store some specifications of a mobile phone. I'll make a dictionary that will have values for all its keys:

mobile = {
     'Brand': 'Vivo',
     'RAM': '4 GB',
     'Storage': '64 GB'
}

Here, we have made a dictionary for a particular data. In other languages, you might be used to call it struct or Object, but this is different from those mainly because it is indexed. You can loop through this dictionary accessing values.

for i in mobile:
     print(i)
/* Outputs the keys: Brand RAM Storage */
for i in mobile:
    print(mobile[i])
/* Outputs the values: Vivo 4 GB 64 GB */

There are many other ways to output dictionary keys and values in Python, but it's more than okay to just stick to one of them. If you're completely new to Python and didn't understand the above code, just skip this for now and come back after reading the Loops section.

That's it! You're done with one section already!

Input/Output Lines

This section is so effortless, I should have started with this, but what would you have taken as the input if you didn't know what was a variable?! Python has built-in input and output functions defined, and which are the easiest in syntax; typical Python! Here's how you print an output:

print("Don't be another Hello World!")

That's it. And here's the input syntax. You have declared a variable, and you want the user to specify the value of it. So you simply ask for the input, and just like in the previous section, you assign it to a variable. Watch these two methods of input:

some_number = input()

Alternatively, if you're aiming for a good guiding application for the user, you can also say,

some_number=input("Enter a number:")

Remember: Input is always taken as strings in python. So if in the above case, the user must have entered 53, the value in the variable some_number wouldn't be 53, but '53'. There's a difference. If the value is a string, it is just like a name in the variable. Now if you want to perform calculations in this, it won't be possible since it's not a number! So how do we do that?

Shouldn't we ask python to convert this input into a number?
Okay.

j = int(input())

Wait, how do we know that it'll only be an integer? What if it's a decimal?

j = float(input())

I think you get the point here. Because if you do, then Congratulations! You've just learnt the concept of Type Conversion. We don't need to bother ourselves with other forms of Type Conversions right now, but certainly this link will help you get into more details. Not much important as of now, though. You can move on to the next section.

Loops

A loop, simply put, is what iterates over a sequence of code. Before starting loops, understand that unlike other languages, Python doesn't use {}, which define the scope. Scope is basically a boundary upto which a variable might be accessed. Instead, Python uses indentations. Okay, so "Indentations indicate scope in Python".

1. For Loop:

Here is the code syntax for a for loop:


for i in list1:
     print(i)

I've used example variables from the previous sections here. Here, list1 is:

list1 = ['a', 'b', 'c']

list1 is a list variable here from the previous examples.
Let me explain what actually happens here behind the scenes.

1. i is the variable that takes the first value of the list/array, aka, iterable

2. The loop body is executed with the value of i.

3. The iterable then calls a _next_() function which gets the next element of the list

4. Step 2 is repeated, until there is no next value remaining in the list.

5. The list raises a stopIterationException which is caught by the for loop to terminate itself.

(Special thanks to Kumar Kartikay for sharing this detailed explanation)

Notice carefully that the print() statement is indented after the for loop declaration. All the statements directly below this line will be treated as in the scope of the for loop. As soon as the alignment of new line shifts back to align with the for loop declaration, the scope of for loop ends. So,



for i in list1:
   print("2")
print("1")

Here, '1' will be printed only 1 time, whereas '2' will be printed 3 times.

2. While loop

Now that you know the working of the for loop, this shouldn't be that tough.

i=0
while i < list1.length:
     print("2")
print("1")

Decision Making Statements

If-else


if i > 5:
   /* Do something */
else:
   /* Do something else */

I believe I don't need to explain anything here since I've already given an explanation for scope above, and it's the same in this case.

Switch

Hmm, this is interesting. Unlike other languages, Python doesn't exactly have a switch statement. So it makes use of dictionary, and it's predefined methods to implement this.

switcher = {
   "Jan": 1
   "Feb": 2,
   "March": 3
}
switcher.get(any_variable, "No Month")

Remember the default case in switch statement? The second argument in the switcher.get() function is just that. The switcher.get() function is not a special Python function. It is just one of the amazing functions for a dictionary defined in Python.
The .get() function looks for the argument specified as the key in the dictionary, and returns the value. If it doesn't find any, it returns the second argument. Simple isn't it?

Functions

We use functions in Python for the same reasons we use it in other languages. Nothing has changed here. You want to group a set of code lines so your code looks restructured, or you're using the same set of code multiple times for different values, you use functions.

The definition of a function is:

def your_function_name (parameters):

      /* Does some function */

def is the keyword here, and parameters will have all the argument values that are required for the function code. I think for the basics, only so much is needed. You can always learn higher stuff like anonymous functions, etc here
Functions are called the same way as in other languages: Just call the function_name, and list out parameters needed in parantheses.

Classes

Alright, we've reached the last section of this blog! I promise you, once you get this section, you can program almost anything in Python. You would have mastered the complete basics!

So we know what classes are. They are a model for our objects. Suppose in the previous example of a dictionary, I didn't just want to store data of one mobile phone, but many such mobile phones. So I would construct a model for a 'Mobile'. And then, I'll reuse that model to put in the specifications of different mobile phones. There, you just learnt what classes are!

Of course, classes are used for much more than what I've said in this example, but this will explain you the meaning of the line: "Classes are blueprints of an Object." It is important to note that making Classes isn't granting us the freedom to construct multiple dictionaries. But it is allowing us to make Objects, which can have their own custom functions defined for them, and we can run those functions only through those Objects.

Unfortunately, I won't be able to explain all the concepts of Classes due to my promise of keeping this concise, so I'll have to assume that you know those. In case you don't, you can browse through this page. These concepts, known as Object Oriented Programming Concepts, are sometimes hard to master, and they take time. Sadly, even that page will just browse through the concepts and may not go into much detail. If you want to lay a strong foundation in this, I'd advice you to read a book on it.

Anyway, so let's start defining a class.

class Mobile:
     brand = 'Vivo'
     storage = '64 GB'

We defined a class named "Mobile', and listed the specifications. This is how you define a class.
Now independently, it has no use. We need to make an object out of this simple model.
So we define a variable, and intialise:

my_phone = Mobile()

That's it. 'my_phone' is an object containing brand and storage values. However, this isn't what was promised. We are looking for something more dynamic! Here, I give you the constructor function:
class Mobile:
      def __init__(self, brand, storage):
          self.brand = brand
          self.storage = storage
/* Declare object */
phone1 = Mobile('Vivo', '64 GB')
phone2 = Mobile('Oppo', '16 GB')

Too many new things have been added here. First up, you might remember using the constructor function in other languages. The __init__ function is just that. When you initialise a class as an object, this function automatically gets executed. The self is used to refer to itself, and all the other parameters will be specified as arguments at the time of initialisation. This produces the same effect as the previous example, the only difference is that we can add as many mobile phone specifications that we want!

With that, we conclude our basics of Python, and I can personally assure you that almost all the programs can be made with the stuff given above.

Tips for the future: Be amazing at googling. If you remember the switch case example, I pulled out a .get() function out of nowhere. And that's not just one function, there are so many other pre-defined functions that save you a lot of trouble from writing manual code. You just need to understand what you need to do, and search for it.

For example, I want to find a substring 'KV' in a big string, which is, "GKFDNKVEFDS". I could write how to do it, but let me save some of my time and think what I should google. I need to find a substring in a string. So let's feed in "find substring python", and you get a result for the find() function in Python. That's what you'll use.

P.S: I've always wanted to explain googling to those starting programming, because the whole world screams at you to google your doubts as a beginner but no one tells you how to! Maybe some other day, I would explain this in much more detail.

Special thanks to Prashant Sengar and Kumar Kartikey for giving valuable insights over various subtleties.

       

Comments

Popular posts from this blog

Namaste JavaScript Quick Notes

Note:  Akshay Saini's Namaste JavaScript is probably the best course for JavaScript developers out there. These are my personal notes that I made while watching the course; they serve more of as an online quick reference for my understanding and revision, and I hope it benefits anyone reading it too! Everything in JS happens inside an Execution Context. Before a JS code is run, memory is allocated and variables are set as undefined   , and functions are set as their exact code in the scope within the Execution Context. The global execution context hosts all the global variables and function definitions. An Execution Context has 2 components: Memory, that stores variables and functions; and Code, that reads and executes the code. Call Stack maintains the order of execution contexts. Since JS is single threaded and asynchronous, at one point of time, only one function is executed which is at the top of the call stack. For each function, an execution context is created before executi

i3wm essentials - I (Brightness)

So you have started using i3 and somehow managed to open your browser and almost resumed your normal work.  But wait, the brightness is too much isn't it? Or is it too low? The mousepad used to work fine, but now all of a sudden tapping does not equal click?!  Don't worry.  This blog series will tell you all about the essential setup commands and common shortcuts that I use to navigate my work in i3, and how you can too. Changing the brightness So you just started i3 and you just can't take this brightness setting. You go for your function keys, and damn! They aren't working. Quick fix: Run the following command if you need to change the brightness ASAP. xrandr -q | grep ' connected' | head -n 1 | cut -d ' ' -f1 This will give an ouput that's the name of your monitor.  Use that monitor name here and change the values of brightness to suit your needs. xrandr --output <monitor-name> --brightness 0.7 Now that your eyes are comfortable, let me show

An introduction to APIs

API is an acronym for Application Programming Interface. Let's start with first defining some basic terms: Browser: These are browsers. To visit any website on the internet, you need a browser. Server: Hmm, this is tough. In simple words, server is a computer. Yes, just like the laptop, or PC at your home. The only difference is that it does not have a screen. Of course, there are other differences in technical specifications, but at its core, the server is just, simply, a computer. That's it. So why is it called a server? Because it serves . When you go to a website like google.com , your computer connects to the internet and gets you your search result. But your computer's internet connection has to get that result from somewhere, right? If the google search result is giving you some answers, the answers have to come from somewhere. What is that place? The answer to that some place is: a server. When you click on the search button on google, or hit enter after typing, &q