An informal introduction to Python programming language
What is Python Programming Language?
Python is a high-level, general-purpose programming language that was first released in 1991 by Guido van Rossum. It is known for its simplicity and ease of use, making it a popular choice for beginners and experienced developers alike. Python is also a versatile language that can be used for a wide range of tasks, including web development, data analysis, machine learning, scientific computing, and more.
How to install python in your machine?
Installing Python in your machine is as simple as you would install other software in your machine, to do so you must first download the official latest version of the software from here. After downloading it install it in your system and follow the instructions, after installing the software you can check it by typing a few lines of command in Windows or Mac.
Windows
Type 'CMD' or 'Windows PowerShell' in the Windows search box near the Start menu and open it, then type 'Python --version' and press Enter. You'll get the Python version as the output, so you've successfully installed the Python programming language in your machine. Hurray!
Mac
Open the Terminal window on the Mac for Mac user, to do this open the Applications folder in Finder, double-click the Utilities folder and then double-click 'terminal.app', then type 'Python --version' and press Return. You'll get the Python version as the output, so you've successfully installed the Python programming language in your Mac machine. Hurray!
We're going ahead and taking a look, what can we do with it and how?
First you can run simple code or arithmetic operations in Python REPL (read-evaluate-print-loop), to do this open 'Windows PowerShell' in Windows system or 'terminal.app' in Mac and then type Python and press 'Enter' or 'Return'. REPL will start and you can perform some tasks here or you can run a few blocks of code here, keep in mind that everything you do here is unstable, which means that all work will be lost when the terminal closes. It is used to check certain blocks of code.
Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in your code.
# this is the first comment
x = 5 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
Using Python as calculator.
The Python REPL interpreter acts as a simple calculator, you want to know how? Just type an expression and it will write you a value. The expression syntax is straightforward: operators +, -, * and /or Most work like other languages (e.g., Pascal or C); Parentheses (()) can be used for grouping. Let's do it, it's very simple and easy.
>>> 5+15
20
>>> 25 + 32*8
281
# division always returns a floating point number
>>> (65 - 9*6)/4
2.75
>>> 168/7
24.0
>>>
If you don't know what 'int' and 'float' are, let me briefly explain to you. An integer or 'int' is a positive or negative absolute number including 0. Some examples of 'int' are 0, 6, 23, -63 etc. While floating point number or 'float' is a positive or negative number with a decimal point. Some examples of 'floats' are 0.23, 6.58, 23.01, -63.80 etc.
Division (/) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use %:
>>> 23/6 # classic division returns a float
3.8333333333333335
>>> 23//6 # floor division discards the fractional part
3
>>> 23%6 # the % operator returns the remainder of the division
5
>>> 3*6 + 5 # floored quotient * divisor + remainder
23
>>>
In Python we can calculate the power of the number using the ** operator.
>>> 9**2 # square of 9
81
>>> 13**8 # 13 to the power of 8
815730721
>>>
The '=' operator is used to assign a value to the variable. Afterwards, no results are displayed before the next interactive prompt:
>>> num1 = 8
>>> num2 = 7
>>> num1 * num2
56
>>>
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>> num3 # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num3' is not defined. Did you mean: 'num1'?
>>>
Full support for floating point operands with mixed type operands in Python, here is an example of converting integer operands to floating points.
>>> 89 * 4.62 -29
382.18
>>>
In Python interactive mode, the last printed variable is assigned to the '_' operator. This means that if you're using Python as a desk calculator, it's easy to perform continuous calculations. Here are some examples.
>>> val1 = 250 *32
>>> val2 = 56.25
>>> val1 * val2
450000.0
>>> val2 + _
450056.25
>>> round(_, 1)
450056.2
>>>
Python also supports complex numbers and uses the suffix 'j' or 'J' to indicate the imagery part (e.g. 5 +9j).
Strings in Python
In Python, strings can be expressed in several ways, they can be attached to a single quote ('...') or double quote ("..."), both will have the same result. Backslash '\' can be used to avoid quotes. Here's an example:
>>> 'John Doe' # single quotes
'John Doe'
>>> 'shouldn\'t' # use \' to escape the single quote...
"shouldn't"
>>> "shouldn't" # ...or use double quotes instead
"shouldn't"
>>> '"Yes", he said.'
'"Yes", he said'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," he said.'
'"Isn\'t," he said.'
>>>
In the interactive interpreter, the output strings is enclosed in the quotes and the special characters are escaped using backslash. While it can sometimes look different from the input (attached citations can change), the two strings are equal. String is associated with double quotes if the string contains a single quote and no double citation, otherwise it is attached to a single quote. The print() function generates a more readable output by excluding attached citations and printing fugitive and special characters:
>>> '"Isn\'t," he said.'
'"Isn\'t," he said.'
>>> print('"Isn\'t," he said.')
"Isn't," he said.
>>> s = 'This is first line.\n This is second line.' # \n means newline
>>> s # without print(), \n is included in the output
'This is first line.\nThis is second line.'
>>> print(s) # with print(), \n produces a new line
This is first line.
This is second line.
>>>
If you don't want the character to be presented as special characters by using '\', you can use raw strings by adding 'r' before the first quote:
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
>>>
There is one aspect in the raw string, a raw string cannot end with the character '\', because it throws an error.
>>> print(r'C:\file\name\')
File "<stdin>", line 1
print(r'C:\file\name\')
^
SyntaxError: unterminated string literal (detected at line 1)
>>>
In Python, string literals can span multiple lines. One way to do this is by triple quotes """...""" Or ''''...''''.
# using double quotes
>>> """abc
... xyz"""
'abc\nxyz'
>>>
# or using single quotes
>>> '''abc
... xyz'''
'abc\nxyz'
>>>
Allows string concatenation using the + operator in Python and can be repeated with *.
# 3 times 'o', followed by 'ps'
>>> 'o' * 3 + 'ps'
'ooops'
>>>
Two or more strings next to each other are automatically concatenated in Python.
>>> 'py' 'thon'
'python'
>>> 'py' "thon"
'python'
>>>
This feature is particularly useful when you want to break long strings:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
>>>
This only works with two literals though, not with variables or expressions:
>>> prefix = 'ooo'
>>> prefix 'ps'
File "<stdin>", line 1
prefix 'ps'
^^^^
SyntaxError: invalid syntax
>>> ('o' * 3) 'ps'
File "<stdin>", line 1
('o' * 3) 'ps'
^^^^
SyntaxError: invalid syntax
>>>
If you want to concatenate variables or a variable and a literal, use + operator:
>>> prefix = 'ooo'
... prefix + 'ps'
'ooops'
>>>
In Python, the string can be indexed with its first character to index 0 and so on. The indices can have a negative number if you want to count from the right. Here are some examples:
>>> word = 'Gamosoftstudio'
# counting from left to right
>>> word[0] # character in position 0
'G'
>>> word[7] # character in position 7
't'
# counting from right to left
>>> word[-1] # last character
'o'
>>> word[-7] # seventh-last character
't'
>>>
Slicing is also supported in Python, in the index we get the individual character from that position, while slicing allows you to get substring.
>>> word = 'Gamosoftstudio'
>>> word[0:4] # characters from position 0 (included) to 4 (excluded)
'Gamo'
>>> word[4:8] # characters from position 4 (included) to 8 (excluded)
'soft'
>>>
We can also leave the first indices default to the size of 0 and the second indices to the sliced size. And we can do it the other way too, by assigning some number to the first indices and leaving the second indices blank so that by default it takes the final index of the string.
>>> word = 'Gamosoftstudio'
>>> word[:8] # character from the beginning to position 8 (excluded)
'Gamosoft'
>>> word[8:] # characters from position 8 (included) to the end
'studio'
>>> word[-6:] # characters from the sixth-last (included) to the end
'studio'
>>>
This is a way to remember how slicing works, the index of characters with the extreme left character is 0 and the length of the final character on the right is 'n'.
| G | a | m | o | s | o | f | t | s | t | u | d | i | o |
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
If we're trying to reach a length that doesn't exist in the string it throws an error, let's take a look here:
>>> word = 'Gamosoftstudio'
>>> word[23]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
Python strings cannot be changed using the index operator, they are immutable. Therefore, assigning to the index position results in an error.
>>> word = 'Gamosoftstudio'
>>> word[0] = 'P'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
The Python built-in function len() provides the length of a string, here's an example:
>>> word = 'Gamosoftstudio'
>>> len(word)
14
>>>
Lists in Python
Python also supports lists, which can be written by comma-separated values (items) between square brackets. List can contain different types of data but usually we see only same type of data. In the list we can update the index values and it is very simple. Let's look at some examples here.
>>> squares = [1, 4, 11, 16, 25]
# square of 3 should be 9 but it is written as 11 in the list.
# Updating the square of value 3 at the index 2.
>>> squares[2] = 3 ** 2
# Now print the updated squares list.
>>> squares
[1, 4, 9, 16, 25]
>>>
We can also add two or more lists, you can do this using the + operator:
>>> squares = [1, 4, 11, 16, 25]
# Now print the updated squares list.
>>> squares + [36, 49, 64, 81]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
You can add new items to the list using append() and also delete an item using remove(), here's how we can:
>>> squares = [1, 4, 11, 16, 25]
# adding item to the list
>>> squares.append(6 ** 2)
>>> squares
[1, 4, 9, 16, 25, 36]
# remove items from the list by providing values
>>> squares.remove(36)
>>> squares
[1, 4, 9, 16, 25]
# or removing items from the list by providing an index number
>>> squares.remove(squares[4])
>>> squares
[1, 4, 9, 16]
>>>
We can change or delete more than one item in the list at once or clear the list completely.
>>> letters = ['g', 'a', 'm', 'o', 's', 'o', 'f', 't', 's', 't', 'u', 'd', 'i', 'o']
# replace some values
>>> letters[4:8] = ['S', 'O', 'F', 'T']
>>> letters
['g', 'a', 'm', 'o', 'S', 'O', 'F', 'T', 's', 't', 'u', 'd', 'i', 'o']
# now remove them
>>> letters[4:8] = []
>>> letters
['g', 'a', 'm', 'o', 's', 't', 'u', 'd', 'i', 'o']
# clear the list by replacing all the elements with an empty list
>>> letters = []
>>> letters
[]
>>>
The built-in len() function provides the length of the list.
>>> letters = ['g', 'a', 'm', 'o', 's', 'o', 'f', 't', 's', 't', 'u', 'd', 'i', 'o']
>>> len(letters)
14
>>>
We can also create a list that includes other lists, i.e. nest list is possible in Python. Here's how we can do it:
>>> x = ['P', 'y', 't', 'h', 'o', 'n']
>>> y = [1, 2, 3]
>>> z = [x, y]
>>> z
[['P', 'y', 't', 'h', 'o', 'n'], [1, 2, 3]]
>>> z[0]
['P', 'y', 't', 'h', 'o', 'n']
>>> z[0][2]
't'
>>> z[1]
[1, 2, 3]
>>> z[1][0]
1
>>>
Here we have learned some operators, functions and their use, we will start the more complex use of Python in the next tutorial. We are moving step-by-step so that you can understand the concepts properly. If you have any questions related to this tutorial, you can simply ask me at the social media link below. I will be very happy to answer your questions.
If you find this blog useful, please consider buying me a coffee. 