Python was released in 1991 by Guido van Rossum. It is an interpreted high level language for general purpose programming.
Python features a dynamic type system and automatic memory management. It supports also supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has large and comprehensive standard library.
Unlike other programming languages like C, Java, C++ it is easy to learn and use. It is more expressive and understandable and readable, object-oriented, Extensible, and most importantly it open source.
Before we get started please ensure that you have Python installed in your PC or Mac. To install python follow this official website link.
Currently, there are two main versions of python, 2.7.x and 3.6.x
In general, Python 2.7.x has more supported libraries than Python 3.x.x. But if you are starting to learn python you may go for version 3.6.x. You may download any of them according to your need. This tutorial uses Python 3.6.2.
Make sure you add python to path while installation. This will enable you to call python commands from the Command Prompt.
Now that you have installed Python on your PC next step will be to select a code editor or IDE. There are various code editors out there, but I will suggest you download Visual Studio Code as it is open source and one of the most customizable and smart code editors in the market. The installation process will be different for different OS. You can download and install it according to your OS.
Python is known for its crisp language structure and elegant codes. Let’s see this by writing our first code. Let’s start the python IDLE.
python
. python
for Python 2.7 and/ or py -3
for Python 3.python
or python3
depending on your installation.Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>>
Your version may be different depending on which version you installed
Now that you are here we may run some code
>>> print("Hello World")
This should be your output after you execute the code
Hello World
In general, variables are the container for data. They are declared in python as VariableName = data. A variable name can be anything except reserved words.
There are few rules that can be followed while deciding a variable name
These are the mandatory rules to declare a variable. There are also some conventions to decide a variable name like CamelCases. One thing that should be kept in mind while deciding a variable name is that the variable name is easily readable for example x=2,y=3 are not a good choice as variable name as num1=2 and num2 = 3 are.
Python has many built-in data types like integers,string, float,list,dictionary,tuples, and set.
We can use them in our context by declaring them using a variable name. For. e.g..list1 = []
They can be manipulated by using:
Let’s see this by referring some examples.
Numbers in python can be integer, float, Boolean or complex numbers. Some examples are:
Some basics operations which you have already gone through in elementary school
>>> 5 + 8 #Addition 13 >>> 9 - 6 #Subtraction 3 >>> 8 * 9 #Multiplication 72 >>> 8 / 9 #Division 0.8888888888888888 >>> 8 % 2 #Modulus(returns the remainder) 0 >>> 5**2 #raise to the power 25 >>> num1 = 9 >>> num2 = 4 >>> sum = num1 + num2 >>> sum 13
Basics operations that can be done in python are
Please note that unlike C/C++, python uses **, double asterisk operator for power
Now let’s recall our high school memories by using some basic algebra. They returns Boolean values. i.e (True or False)
>>> 2 == 3 # Equality check False >>> 2 >= 3 False >>> 3 <= 2 False >>> 1 == 1 True >>> 2 != 3 True >>> 45 > 1 True >>> 1 < 3 True
Please note that to check equality we use ‘==’ double equal sign and to assign we use ‘=’ single equal to.
There are many inbuilt functions provided by python to manipulate the numbers. Let’s see them one by one.
>>> float(2) #changes an integer into float 2.0 >>> int(3.44) #truncates the part after the period and returns integer 3 >>> (2.3).is_integer() #Checks is a float is finite False >>> (2.0).is_integer() True
Strings are used in python for recording text information such as an address. Python Strings are basically a sequence, i.e. python keeps track of each and every element of the string as a sequence.
>>> "hello" + " world" 'hello world' >>> "ab" * 5 'ababababab' >>> a = "hello" #String Slicing >>> a[1] 'e' >>> a[0] 'h' >>> multiline_string = """ Lorem ipsum """ >>> multiline_string ' Lorem ipsum ' >>> not_escaped_string = "didn't" >>> not_escaped_string "didn't"
>>> escaped_string = 'didn\'t' >>> escaped_string "didn't" >>> escaped_string.capitalize() "Didn't" >>> escaped_string.center(12) " didn't " >>> escaped_string.count('d') 2 >>> escaped_string.find('d') 0 >>> escaped_string.find('did') 0 >>> escaped_string.format("%12s") "didn't" >>> escaped_string.index('d') 0 >>> escaped_string.find('id') 1 >>> escaped_string.isalpha() #because it also contains "'" False >>> escaped_string.replace('d','a') "aian't"
Lists are the builtin python sequence. Consider it just like in array of other languages like C,C++ or Java. Now lets dive into some examples to get to know more about lists.
Python lists can be created in two ways:
>>> a = [] >>> b = list() >>> print(type(a), type(b)) <class 'list'> <class 'list'> >>> a [] >>> b []
>>> list1 = [1,2,3] >>> list1.reverse() >>> list1 [3, 2, 1] >>> list1.sort() # sorts the list in ascending order >>> list1 [1, 2, 3] >>> list1.append(4) # appends an object at last of the list >>> list1 [1, 2, 3, 4] >>> list1.clear() # clears the objects in list >>> list1 [] >>> list1.append(1) >>> list1.append(2) >>> list1.insert(3,0) # inserts an element at a particular index >>> list1 [1, 2, 0]
Dictionary is the types of an associative array in python. They are similar to hash-map in Java. Let’s see few examples to understand it better.
Like python lists they can also be declared in two ways.
>>> dict1 = {'key': 'value'} >>> dict1 {'key': 'value'} >>> dict1['key'] 'value' >>> dict1.keys() # returns the keys in the dictionary object dict_keys(['key'])
Tuples are just like python lists unlike lists they have less inbuilt functions and are immutable. Let’s see a few examples:
Like python lists they can also be declared in two ways:
>>> tuples = () >>> tuples.count(2) 0 >>> tuples = (1,2,3) >>> tuples (1, 2, 3) >>> tuples = (1,'a',2) >>> tuples (1, 'a', 2)
Python has two loops
For loop is a finite loop in which you predetermine the number of times the loop will run. Let’s write a program to print the first 5 natural numbers to make you understand better.
>>> for i in range(1,6): print(i) 1 2 3 4 5 >>>
Well, now you may be wondering what is range() and why we gave arguments as 1,6. This is because the range() function returns value from the starting argument to the second last argument.
While loop is used when you don’t know the number of times the loop will be executed.
>>> i = 1 >>> while(i<=5): print(i) i += 1 1 2 3 4 5 >>>
Loops in general have three parts:
Python is very helpful in pointing out the error. There are many types of errors in python. Let’s go through few of them.
>>> print(1) ^ SyntaxError: unexpected indent >>> if i < 0 if i < 0 ^ SyntaxError: invalid syntax
>>> int('a') Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> int('a') ValueError: invalid literal for int() with base 10: 'a'
Passing an invalid object type in a function generally gives this error
>>> sum(1,2) Traceback (most recent call last): File "<pyshell#53>", line 1, in <module> sum(1,2) TypeError: 'int' object is not iterable
Errors in python can be handled by putting the code inside a try/except block.
>>> try: int('a') except ValueError: print('Program ran successfully') Program ran successfully >>>
You can see in the above example that we did get a ValueError but with the try/except block, we have successfully handled.
Python has a great collection of packages and libraries. You can import many pre-built libraries to extend the language capabilities. Let’s see few libraries.
>>> import math >>> math.sqrt(4) 2.0 >>> import datetime >>> datetime.datetime.now() datetime.datetime(2018, 12, 3, 18, 31, 54, 54054) >>> import random >>> print(random.randint(3,10)) 3 >>> print(random.randint(3,10)) 4 >>> print(random.randint(3,10)) 4 >>> print(random.randint(3,10)) 8
You can plenty of tutorials and blog available online.
The place that truly helped me was MIT’s course, Introduction to Computer Science and Programming, which covers various computer science concepts along with Python. The course can be found at. The Harvard and MIT non-profit online initiative (Edx.org) offers the course in two parts. They are challenging and provide an excellent approach to problem-solving. Both parts are graded.
But the best part to learn python is – Project driven learning approach. You can find project driven beginner course related to python here at PyBlog. These courses are updated monthly to keep up with changes in Python.
Another source of free learning materials comes from the Python Software Foundation:
Now that you have learned the basics of Python. Let’s Practice. Open your code editor and copy paste the code and save the file as practice.py.
############################################################################### ######## Change the variables till all the statements evaluate to True ######## ############################################################################### variable1 = variable2 = variable3 = variable4 = variable5 = variable6 = ############################################################################### ##################### Don't Change anything Below this ######################## ############################################################################### # test1 Strings print(type(variable1) == type('')) print(len(variable1) < 9) print(variable1[0] == "a") # test2 Integers print(type(variable2) is int) print(type(variable3) is float) print(variable2 < variable3) # test3 Dictionary print(type(variable6) is dict) # test4 List print(len(variable4) == 5) print(type(variable4) is list) # test5 tuple print(type(variable5) is tuple) print(len(variable5) == 2)
In Python, the print() function is a fundamental tool for displaying output. While printing simple…
Python is a versatile programming language known for its simplicity and flexibility. When working on…
PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…
PDF (Portable Document Format) files are widely used for document exchange due to their consistent…
Python is a high-level programming language known for its simplicity and ease of use. However,…
Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…
This website uses cookies.
View Comments
I will appreciate if I receive a newsletter from you in the future.