Categories
Python

Statements, Comments, and Python Blocks

Hey guys, this is the fourth tutorial of the Python for Beginners Series. If you haven’t checked out our previous tutorials, you should go and check them for a better understanding. In this tutorial, we are going to discuss the statements and escape sequences. This tutorial is focused on statements so you will learn about statements in general and then comments, what are comments, how to write comments in Python, docstrings, escape sequences, and the python blocks.

So, without further ado, let’s start now.

Statements

Any instruction that you give to python to execute is a statement. You say

print("Hello World")

This is a print statement because you are printing some data, which in this case is a string.
Anything you write is a statement. You assign a value to a variable, that’s a declaration/assignment statement. Now some of you might have heard about if, else, for, while, etc… These all are statements.

Now statements can be of single-line or multi-line. Till now, you may have only used single line statements like print(“Hello World”) but there are multi-line statements as well.

Multi-Line Statements

You can extend a single statement to multiple lines. Try making a multi-line statement like this one.

a = "Coding
Ground"
print(a)

It will throw an error like

    a = "Coding
              ^
SyntaxError: EOL while scanning string literal

To extend the statement to multiple lines, all you have to do is put a backslash ( \ ) at the end of the statement. For example,

a = "Coding\
 Ground"
print(a)

And the output will be

Coding Ground

You can also put your statement under brackets for some data types and you won’t need to use backslash but it is not true for strings. For example

a = ['item1',
'item2']
print(a)

The output will be

['item1', 'item2']

It will work with tuples as well.

Now you might be wondering why should we even use it when we can just write it in one line. Well, it is done to make your code cleaner and increase its readability.

Comments

You must have noticed that in some code there is a text written beside it which describes what the code is for. That text is called a comment. There are two types of comments, single-line comments which are normal comments and multi-line comments which are also known as docstrings

Single Line Comments

These are written in a single line for example,

a = "Coding Ground" #Assigns value to variable a 

Single Line comments start with a hashtag. They are written to describe what the code is about, it’s working what the variable stores and so on. Comments are only for user understanding and are never executed with the code.

You can write as many comments as you would like and it’s a good practice to write comments so that others can understand your code without much hassle. Not only for other people, but it will also help you in reading your code after a long time.

Docstrings or Multi-Line Comments

There are times when you have to add a full documentation about a function or a class you create or sometimes, it’s just that you have to write multi-line comments, for that we use docstring.

Docstring is any text written under triple quotes like ”’ or “””. For example,

"""This is a 
docstring"""
'''This 
is 
also a
docstring'''

If you want to add a documentation of a function you can do this like

def codinground():
    """prints Coding Ground"""
    return ("Coding Ground")

Docstring for functions, classes, or modules is written right after their declaration before any other statement.

Now if you want to access the documentation of a function/class/module, all you have to do is call the attribute __doc__.

You can, in this case, do this by printing function.__doc__. For example,

print(codinground.__doc__)

It will print out whatever is written in the docstring of that function or module or class. It will be really helpful whether you are experienced or beginner in python.

The output in this case will be

prints Coding Ground

So, docstrings will help you write documentations in an efficient and a standard way for everyone to follow.

Now, this isn’t a norm but a personal preference that you should write docstrings when you are writing a function or a class or module and single-line comments when you are writing loops or variables.

You might be confused about functions, classes, or modules but don’t worry, we’ll be covering them in our future tutorials in this series. But if you are confused about variables, I recommend checking out our tutorial on Datatypes and Variables in Python

Coming over to our next topic which is Escape Sequences.

Escape Sequences

There are some characters in python which have a different meaning. These are called escape sequences and are written after the escape character backslash( \ ).

For example, if I told you to print out a string whose output is “Coding Ground”. How would you do it? simply using print(“”Coding Ground””) will throw a Syntax Error.

There are many such cases where we want our text to be under quotes or in a new line without actually writing it in another line etc., in these cases, we use escape sequences.

To print a text under quotes just put a backslash before the quotes.

print("\"Coding Ground\"")

The output of this will be “Coding Ground”. This is because the double quotes are written after the escape character backslash. If you try to put backslash without any other character, it will leave whitespace. The backslash defines that the character after after the escape character has a different meaning than the normal one.

TIP
If it’s just printing the text under double or single quotes you can just do it like this print(‘”Coding Ground”‘). What I have done is, I started the string with a single quote and wrote the word under double quote so python interpreter knows that ok, the main string is whatever text is under single quotes. So, it treats double quotes as an ordinary string character.
But this is not recommended

You can also use \n to make it the next line. I know this is not clear so let’s consider this example, You are making a menu for your program and you want to list multiple items in it.
Then you can do this by using the \n like

print("1. Item One\n2. Item Two\n3. Item Three")

The output of this will be

1. Item One
2. Item Two
3. Item Three

You can see that it is much more efficient than writing it in multiple lines.

Similarly, there are many such escape sequences, you can find a list of them below.

Escape SequenceMeaning
\newlineBackslash and newline ignored
\\Backslash (\)
\'Single quote (')
\"Double quote (")
\aASCII Bell (BEL)
\bASCII Backspace (BS)
\fASCII Formfeed (FF)
\nASCII Linefeed (LF)
\rASCII Carriage Return (CR)
\tASCII Horizontal Tab (TAB)
\vASCII Vertical Tab (VT)
\oooCharacter with octal value ooo
\xhhCharacter with hex value hh
List of Python supported Escape Sequences

These are all the escape sequences available in Python. Play with them and you will have a better understanding.

Python Blocks

In our previous example on docstring, we made a function and then wrote a docstring.
If you have noticed carefully then you must be wondering why we put a colon after the function definition and then we leave two spaces in the statement we wrote under that function?

This is because unlike other languages, which use curly braces {} to define a block, python uses colon and indentation which is usually two or four spaces.

According to Python’s Official Documentation,

block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block.

All conditional statements, functions, classes and modules use a python block.

Let us look at a if statement to make it more clear.

 a = 10
 if a == 10:
    print("This code executes under if block")
print("This executes anyway")

Since the condition is true, which is a is equal to 10, if block will run and the output will be

This code executes under if block
This executes anyway

If we tweak the value of variable a, suppose 1, then the if condition will become false and if block will not run and the output will simply be

This executes anyway

So basically, a block is a piece of code that executes as a unit whenever called.

Hopefully it should have given you some basic insight on loops as well.

We will discuss python blocks in detail when we cover control flow statements.

This is it for this tutorial, hope you like it. Tell me what you think of this tutorial in the comments section below. Also, if you have any doubts, comment down below and I’ll help you.

References

Categories
Python

DataTypes and Variables

Hey guys, this is the third tutorial of the Python for Beginners Series. If you haven’t checked out our previous tutorials, first go and read them (especially Tokens in Python) because we have discussed keywords and identifiers in those tutorials that you should know before learning about variables.

What are variables?

Variable is a name that points to a location where your data is stored. In simple language, the variable holds your data. You can assign a value to a variable using = sign with the variable on left and value on the right.
Consider this example,

age = 10

In this example, age is a variable that points to the memory location where the data i.e., 10 is stored. Now whenever you want to use 10, you can also use variable age.

For example, if you do this

print(age)

The output will be 10

Also, it is important to know that the data inside the variable can be changed whenever you need. For example, you could store a value 20 in the same variable.

age = 20

Now the variable age holds value 20. The old value 10 is now replaced by the new value 20.

You can store all sorts of data in a variable like

name = "Coding Ground"

the variable name holds the string value Coding Ground.

It is important to remember that variables do not store values they are the pointers. They give reference to the memory location where the data is stored.

Before we dive any deeper, let us discuss the different type of data supported in python.

DataTypes

A datatype is simply the attribute of data that tells the interpreter what type of data it is going to process.

There are multiple data types supported in Python. Also, you can check the type of data using the type() function.

Python Data Types

Numeric Data

The numeric data type includes integers, floating-point numbers, and complex numbers.
They are used as int, float, and complex. Consider the examples below,

Integers

These are the whole numbers which also include negative numbers. For example, 0,1,2,3,150, -200 etc are all integers. They don’t have a fraction part.

a = 10
print(type(a))

It will return

<class 'int'>

Floating Point Numbers

Floating Point numbers have a decimal part in them.

b = 10.2
print(type(b))

The output will be

<class 'float'>

Complex Numbers

These numbers are in the form of a + bj. They are as <real part> + <imaginary part>j

c = -1 + 5j
print(type(c))

The Output will be

<class 'complex'>

Now you see class because the data is an object or instance of a class.
For example, 10 is an instance of int class.

If you don’t understand it then don’t panic, We will be discussing classes and objects in future lectures.

Sequence

Sequences include lists, tuples and strings.
Basically every data type in which slicing can be done falls under this category.

Lists

Python lists contains elements within square brackets [ ].

a = ["Coding Ground",1,1.2,True]
print(type(a))

The Output would be

<class 'list'>

In the above example, the variable a holds a list of 4 elements, each of different data type.

Now each element of list has an index value and it starts from 0.

For example, the index value of the element “Coding Ground” in the above code will be 0.

We will discuss indexing and slicing in future tutorials.

Tuples

Tuples contain elements in round brackets or parenthesis ( ).

An example of a tuple would be

a = ("Coding Ground",1,1.2,True)
print(type(a))

The output would be

<class 'tuple'>

Now you might be wondering, what is the difference between list and tuple?

The answer is that Lists are mutable while tuples are not. That means you can change the elements of a list without replacing the whole variable value but you can not do that with tuple. You can not perform operations on them.

String

Anything within single or double quotes in Python is a string.

a = "Coding Ground"
print(type(a))

The output would be

<class 'str'>

Boolean

Boolean on values can only be either True or False.

a = True
print(type(a))

The Output will be

<class 'bool'>

Remember that True is a keyword and T is capital.

Mapping

There are 2 types of Data Types that fall under this category. These are Dictionary and Sets.

Dictionary

Dictionary is an unordered collection of key-value pairs. It uses curly braces.
If you’ve ever worked with JSON data then you must be familiar with Dictionary.

a = {'name' : "Coding Ground"}
print(type(a))

The Output will be

<class 'dict'>

Dictionaries provide a little more readability as compared to lists and tuples. This is because of the key-value pair. And this is the reason they are used when we have to work with a large amount of data.

Sets

Like dictionaries, Sets are also unordered collections with curly braces. But the difference is that they contain only unique values.

a = {1,2,3,4,5,1,2,3}
print(a)
print(type(a))

The output would be

{1, 2, 3, 4, 5}
<class 'set'>

Here, you can clearly see that we got only unique values as the output.

We cannot filter data from sets as sets are unordered pair. We can however use the classic set functions like union, intersection etc on two set values.

Now that we have discussed the data types, lets continue where we left the variables.

Type Casting or Type Conversion

Now that you have learnt about the different data types and how to assign a value to a variable. It is time to learn how you can convert the data type of some data stored in a variable.

Consider this example,

a = 10
print(a)
print(type(a))
a = float(a)
print(a)
print(type(a))

The output will be

10
<class 'int'>
10.0
<class 'float'>

As you can see we have just converted an integer value to a float one. But remember that you can not do this with all data. You can only do this with data having similar data type.

Now this is all common sense, I don’t need to explain this. If you are thinking how about converting complex to int or float, it won’t work because complex got j in it which isn’t used in any int value or float value.

But you can convert string into a list.

a = "Coding Ground"
a = list(a)
print(a)
print(type(a))

The output will be

['C', 'o', 'd', 'i', 'n', 'g', ' ', 'G', 'r', 'o', 'u', 'n', 'd']
<class 'list'>

So, guys, this is it for today. I hope you like it. If you have any problems or if anything is left unclear then tell us in the comment section below.

Happy Coding!

References

You can read more about additional data types at official python documentation

Categories
Python

Tokens in Python

Hey guys, this is the second tutorial of the Python for Beginners Series. If you haven’t read the first one i.e, Getting Started with Python yet then I suggest checking that out first. Also, this is going to be mostly theoretical with almost no coding involved but is very important.
Do not skip this if you don’t know about tokens in Python.

The Python Character Set

It is the set of valid characters that python understands. Python uses the Unicode character set.
It includes numbers from numbers like
Digits: 0-9,
Letters: a-z, A-Z
Operators: +,-,/,*,//,**
Punctuators like : (colon), (), {}, []
Whitespaces like space, tabs, etc

What are tokens?

Tokens are building blocks of a language. They are the smallest individual unit of a program. There are five types of tokens in Python and we are going to discuss them one by one.

Types of Tokens

So the five types of tokens supported in Python are Keywords, Identifiers, Literals, Punctuators, and Operators. Coming over to the first one we have

Keywords

Keywords are the pre-defined set of words in a language that perform their specific function. You cannot assign a new value or task to them other than the pre-defined one.

You cannot use them as a variable, class, function, object or any other identifier.

For example: if, elif, while, True, False, None, break etc

These have their special task that you cannot change. For example break will only end the loop you cannot make it start the loop. (We’ll be covering loops in future lectures).

Identifiers

Now identifiers are the names that you can assign a value to. An identifier can be anything for example,

a = 10

Here, a is a valid identifier name. Any name you give your variable, function, or class is an identifier of that particular thing. Now there are certain rules that you have to follow to define a valid identifier name.

Rules for valid identifier name

  • A valid identifier name can have letters, digits, and underscore sign.
  • It can start with an alphabet or underscore but can never start with a digit.
  • It can never be a keyword name.
  • An identifier name can be of variable length.
  • The only special symbol that can be used in identifier name is underscore( _ ).

One more thing that you should remember that python is case sensitive i.e.,

a = 10
A = 5

These two hold two different values. a holds the value 10 and A holds the value 5.

Examples of valid identifier names include: a, _a, a12, etc
Examples of invalid identifier names include: 1a, $a, elif, print.
If you don’t understand why they are valid/invalid, read the rules again.

Literals

Literals are the fixed or constant values. They can either be string, numeric or boolean.

For example, anything within single or double quotes is classified as a string and is literal because it is a fixed value i.e, “Coding Ground” is literal because it is a string.

Another example is, 10. It is a simple number but is a fixed value. It is constant and it will remain constant. You can perform operations like addition or subtraction but the value of these two characters 1 and 0 put together in a correct order gives them a value equal to ten and that cannot be changed.

Boolean only consist of 2 values, True and False. Remember that “T” of True is capital. Python is case sensitive and if you write True with small “t” like true it will hold a different meaning. It will act as another variable.

It might seem a bit confusing for now but you’ll definitely understand it in our future lectures on boolean and other data types.

Punctuators or Separators

Punctuators, also known as separators give a structure to code. They are [mostly] used to define blocks in a program. We will be covering code blocks in control flow statements when we discuss how to apply conditions in Python.
Some examples of punctuators include
single quotes – ‘ ‘ , double quote – ” ” , parenthesis – ( ), brackets – [ ], Braces – { },
colon – ( : ) , comma ( , ), etc.
Punctuators and operators go hand in hand are used everywhere. For example,

name = "coding ground"

Here, an assignment operator ( = ) and punctuator, (” “) is used.

And now for the last type of token is Operators

Operators

Operators are the symbols which are used to perform operations between operands.

Unary Operators: Operators having single operand.
Eg. +8, -7, etc
Binary Operators: Operators working on 2 operands.
Eg. 2+2, 4-3, 8*9, etc
Similarly, there are Ternary Operators that work on 3 operands and so on.
These are just basics and not so important to know but the operators listed below are very important

  • Arithmetic operators ( +, -, /, * etc)
  • Assignment operators ( = )
  • Comparison operators ( >, <, >=, <=, ==, !=)
  • Logical operators ( and, or, not)
  • Identity operators ( is, is not)
  • Membership operators ( in, not in)
  • Bitwise operators ( &, |, ^ etc)

There’s so much about operators that it cannot be written here as it will be out of the scope of this topic. A new detailed article on tokens will be there very soon.

Reference to Punctuators:
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/rzarg/punctuators.htm
https://download.mikroe.com/documents/compilers/mikroc/pic/help/punctuators.htm

Categories
Python

Getting Started with Python

Hey Guys, if you ever wanted to learn python but you don’t have any past experience then continue reading. This is the first tutorial of Python for Beginners series. In this tutorial we will cover the introduction of python following with its uses and applications. You will install and set up python on your computer and write your first program in Python.

Introduction to Python

Python is an interpreted*, high-level, object-oriented, and open-source language developed by  Guido van Rossum and first released in 1991. According to a survey conducted by Stackoverflow, Python is the most sought after programming language by developers.

Compiler – It converts the source code into a machine-dependent code completely all at once.
Interpreter – Python runs and checks the code line by line. So if an error is detected at suppose line 2, then it won’t run all the way to the end of the script. Unlike Java, which compiles the whole code at once.

Why Python?

  1. Python is an interpreted language, not a compiled language. Due to this, python is easy to debug.
  2. Python is a cross-platform language, it can run on a variety of platforms.
  3. Python is open-source and free.
  4. Python is best for Artificial Intelligence and Machine Learning.

Setting Up

Installing Python is extremely easy, it’s the same as you install any other software. Just go over to the official Python Website and download the latest version or click here.

Remember to check “Add Python 3.X to PATH“. It adds PIP to environment path variables.

PIP is a Python Package installer that helps in installing libraries and modules. You will need it one day or another, so it’s better to install it now.

Selecting the Python IDE(Integrated Development Environment)

Different people suggest different IDE, it all comes down to the personal preferences.

In this series we will be using the default python idle because a large number of people use that and it is generally advised to start with that.

What I recommend is IDLE or Sublime Text. These are more than enough or you can try VS Code. Though there are many other good IDE’s but I believe an IDE should be lightweight and fast because oftentimes you have to use a web browser to search for the problems. So these 3 are the best in terms of speed and efficiency.

Out of these I recommend Sublime Text because it has a large number of color schemes which look fantastic while coding and some people prefer a darker theme which is really great in Sublime.

Working with IDLE

Writing Your First Program

After installation open up Python Shell and write this code.

print("Hello World")

print() function tells Python to print/echo whatever data is in the parenthesis.

In python, string values are written under double quotes. We will be learning more about that in the future lessons.

Congratulations, you wrote your first program in python!

As an assignment, Try printing your name in python.

Working with Files

Most beginners make this mistake of continue writing their whole program in Python Shell. You shouldn’t do it unless you want to perform a quick task.

Now in your Python Shell click on File and select New File

Now type the same code in the file and save it. The default extension of python files is .py.

After Saving the file press F5 or click on Run and select Run Module.

It should look something like this. If this is what you got then congrats, you successfully learned how to use python files.