Oct 13, 2022

How to check the installed python version?

Check the python version your machine currently using by typing the following commands in your terminal.

bash-5.1$ python --version
Python 3.9.12

Check the python version via the python script.


 #import sys module in python sys module contain tuple of strings containing all the built in modules and constants
import sys

print(sys.version) #get the python version

Check which version you are using if you have multiple python versions installed.


You can check what version of python you are using by typing python in the terminal.

bash-5.1$ python
Python 3.9.12 (main, Apr  5 2022, 06:56:58) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Check the python interpreter location using the terminal.


To check the python interpreter location type command which python command. 

(base) bash-5.1$ which python
/home/username/anaconda3/bin/python

Oct 6, 2022

Graphing with Python using Matplotlib

 Introduction


Matplotlib is a graphing and plotting library that can be useful for creating different types of graphs and plots. Such as line charts, pie charts, scatter plots and 3D plots. Matplotlib can also be used for creating animated and interactive visualizations. It can also generate output in a variety of formats which includes PNG, SVG and PDF etc.

Installing Matplotlib


Matplotlib is not built into python. First, we need to install Matplotlib using the PIP package manager.
pip install matplotlib
If you are using Conda you can use the below command.
conda install matplotlib
You can refer to more about installation options on the Matplotlib installation page.

Plotting Simple Graph using Matplotlib


First, we need to import pyplot from Matplotlib library.  After that line, we give 2 python lists as arguments to plot() function specifying Y values and X values for the graph. then we set the label for both the x and y axis and the title. Finally, we call the show() function that displays our plot in a window.
#importing pyplot from matplotlib library
import matplotlib.pyplot as pyplot

# plot the graph using given values
pyplot.plot(
	[1, 2, 3, 4], # Y values
	[0.5, 1.0, 1.5, 2.0] # X values
)

# setting x and y axis labels
pyplot.xlabel('x-axis-label') 
pyplot.ylabel('y-axis-label')

# setting the title
pyplot.title('This is the title')

# display the chart in a window
pyplot.show()
Simple graph using matplotlib
 simple graph using matplotlib

Plotting Multiple Graphs Same Plane.


When plotting multiple graphs we need to add different styles, and colours, and more importantly, we need to add a legend to identify each graph clearly. In the below code sample, we add a legend using legend() method and pass arguments for legend background colour, location and title. we also add a descriptive label for each graph, change the colour and set the style of the one graph to a dashed line.
    
import matplotlib.pyplot as pyplot

# plot the graph 1
pyplot.plot(
	[0, 1, 2, 3], # Y values
	[1, 3, 5, 7], # X values
	label = 'y = 2x + 1', # set the label
	color = 'blue' # set the color
)

# plot the graph 2
pyplot.plot(
	[0, 1, 2, 3], # Y values
	[3, 6, 9, 12], # X values
	ls = '--', # set the line style
	label = 'y = 3x + 3', # set the label 
	color = '#995789' # set color color
)
# setting x and y axis labels
pyplot.xlabel('x-axis-label') 
pyplot.ylabel('y-axis-label')

# setting the title
pyplot.title('This is the title')

# setting the legend
pyplot.legend(
	facecolor = 'gray', # legend background
	title = 'legend', # legend title
	loc = 'upper left' # legend location
)

# setting the grid line
pyplot.grid(True)

# display the chart in a window
pyplot.show()
multiple graphs same plane
multiple graphs in the same plane

Plotting Bar Chart


We use the matplotlib pyplot bar() function to draw bar graphs. In the below examples, we pass the x-coordinates, heights of each bar,  bar width, and colours of each bar.

import matplotlib.pyplot as plt

languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']

# setting the bar chart
plt.bar(
	languages, # x coordinates 
	Salary, # heights of the bars
	width = 0.7, # width of the bars
	color = bar_colors # bar colors
)

plt.xlabel('Language')
plt.ylabel('Salary')
plt.title('Median Developer Salary By Language')

plt.show()

bar plot matplotlib
Bar chart matplotlib




Horizontal Bar Charts


You can create the above graph horizontal by using barh() matplotlib pyplot function instead of bar() function. The below code demonstrates it.

import matplotlib.pyplot as plt

languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']

# setting the bar chart
plt.barh(
	languages, # y coordinates 
	Salary, # width of the bars
	height = 0.7, # height of the bars
	color = bar_colors # bar colors
)

plt.xlabel('Salary')
plt.ylabel('Language')
plt.title('Median Developer Salary By Language')

plt.show()
horizontal bar graph using matplotlib
Horizontal bar graph matplotlib


Line Graphs using Matplotlib


In the below line graph example, we pass the argument 'bo-' to the function. in this argument 'bo-' first character 'b' indicates the colour of the line and second character 'o' indicates the marker of each point being plotted and the third character  '-' indicates the line style of the graph. In our case, it sets to a blue solid line with circle markers.

import matplotlib.pyplot as plt

month = ['January', 'February', 'March', 'April', 'May', 'June']
profit = [10000, 28000, 13400, 14000, 24400, 21000]

# setting titles and axes headings.
plt.title('Profit in year 2022')
plt.xlabel('Month')
plt.ylabel('Profit')

plt.plot(
	month, # setting x values 
	profit, # setting y values
	'bo-' # style of the graph(color, marker, line style)
)

plt.show()
Line graph using Matplotlib
Line Graph Matplotlib

Scatter plot


we use Matplotlib scatter() function to draw a scatter plot. below code sample demonstrates a scatter plot.

import matplotlib.pyplot as plt

iq = [
	[43, 45, 57, 20, 30, 75, 29, 60, 27, 80], # Age
	[22, 46, 43, 23, 45, 76, 44, 56, 41, 62] # IQ score
]

maths = [
	[29, 70, 20, 57, 30, 44, 60, 25, 32, 62], # Age
	[40, 23, 90, 55, 80, 39, 74, 65, 87, 48] # Maths score
]

# plot iq data
plt.scatter(
	x = iq[0], 
	y = iq[1],
	color='darkorange',
	marker='o',
	label='IQ'
)

# plot maths data
plt.scatter(
	x = maths[0], 
	y = maths[1],
	color='green',
	marker='^',
	label='Mathematics'
)

plt.xlabel('Age')
plt.ylabel('Score')
plt.title('Marks Two Subjects')
plt.legend()

plt.show()

Scatter plot using matplotlib
Scatter Plot

Pie chart


Matplotlib pyplot pie() function was used to draw below the pie chart. 

import matplotlib.pyplot as plt

language = ['Python', 'Rust', 'Java', 'C#', 'Javascript']
precentage = [33.50, 15.30, 22.30, 12.45, 16.45]

plt.pie(
	precentage,
	labels = language,
	autopct = '%1.2f%%', # format the numeric values in wedges
	counterclock = False, # wedges plot direction
	startangle = 90 # starting angle 
)

plt.title('Language Popularity')

plt.show()
Pie chart using matplotlib
Pie chart


Conclusion


In this article, we show you how to draw simple graphs using the Matplotlib library. Matplotlib is a very flexible option for creating graphs in python. 

References

Oct 2, 2022

Your First Rust Program - Hello World!

 Introduction 


Rust is a robust, reliable, productive language(check rust language benchmarks). The language has all the tools to write program efficiently and It also has a well written userfriendly documentation. In this tutorial, we will write our first Rust programme on a Linux machine and Introduce some syntax rules in Rust language.

Installing Rust in Linux.


We can install Rust in Linux easily. To download and install Rust you just need to copy and paste the below command and press enter key then it will download and install Rust into your machine using a tool called rustup. rustup is a command line tool for rust installer and version management.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
terminal:
bash-5.1$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
info: downloading installer

Welcome to Rust!

This will download and install the official compiler for the Rust
programming language, and its package manager, Cargo.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  /home/user/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  /home/user/.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at:

  /home/user/.cargo/bin

This path will then be added to your PATH environment variable by
modifying the profile files located at:

  /home/user/.profile
  /home/user/.bash_profile
  /home/user/.bashrc

You can uninstall at any time with rustup self uninstall and
these changes will be reverted.

Current installation options:


   default host triple: x86_64-unknown-linux-gnu
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

when executing this command it will prompt you to enter installation options with a list of three options like below. 

terminal:
1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>1

info: profile set to 'default'
info: default host triple is x86_64-unknown-linux-gnu
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2022-09-22, rust version 1.64.0 (a55dd71d5 2022-09-19)
info: downloading component 'cargo'
  6.4 MiB /   6.4 MiB (100 %) 809.6 KiB/s in  7s ETA:  0s
info: downloading component 'clippy'
  2.8 MiB /   2.8 MiB (100 %) 1023.7 KiB/s in  3s ETA:  0s
info: downloading component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   1.1 MiB/s in 17s ETA:  0s
info: downloading component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   1.2 MiB/s in 25s ETA:  0s 
info: downloading component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   1.2 MiB/s in  1m  1s ETA:  0s
info: downloading component 'rustfmt'
  4.3 MiB /   4.3 MiB (100 %)   1.2 MiB/s in  4s ETA:  0s
info: installing component 'cargo'
  6.4 MiB /   6.4 MiB (100 %)   6.4 MiB/s in  1s ETA:  0s
info: installing component 'clippy'
info: installing component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %) 424.0 KiB/s in 41s ETA:  0s
info: installing component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   3.2 MiB/s in 11s ETA:  0s
  6 IO-ops /   6 IO-ops (100 %)   0 IOPS in 15s ETA: Unknown
info: installing component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   4.7 MiB/s in 19s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-unknown-linux-gnu'

  stable-x86_64-unknown-linux-gnu installed - rustc 1.64.0 (a55dd71d5 2022-09-19)


Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, run:
source "$HOME/.cargo/env"

choose the default option for your installation, and then it will download the necessary components and show you the message Rust is installed. After that enter the following command to set the environment variable.
source "$HOME/.cargo/env"
now type rustc --version and cargo --version commands on your terminal to check whether Rust has been installed successfully. In this commands rustc stands for Rust compiler and cargo is a Rust package manager.

Writing Your First Rust Program


For writing our program we use VS Code IDE. we assume you already installed the VS code. In vs code first, go to the extensions and install the rust-analyzer extension which includes the support for Rust programming language. Then create a file called hello_world.rs in a directory and write or paste the below code.
fn main() {
    println!("Hello world!");
}

Running Your Program


Rust source file compilation and execution steps
Rust compilation and execution steps

To run the program first you need to compile your program using the Rust compiler, to do that navigate to the directory which contains hello_world.rs then you need to run the below command in your terminal. 

bash-5.1$ rustc hello_world.rs

After the compilation process is over you can see a new file created in the directory named hello_world This is a binary file created by the compilation process. then you can execute the program in Linux by running the below command.

bash-5.1$ ./hello_world
Hello world!

Dissecting Your First Rust Program


in our hello world rust program first, you see an outer block of the program as fn main(){}. fn is the keyword used in Rust to declare a function and the main is the name of the function followed by pair of opening and closing parentheses and then pair of curly brackets which specify the main function body.

This main function is the starting point of our program. In Rust function main holds a special place like java and C++ Because It’s the first thing to run in a Rust program.

Inside the main function body, there is a single line println!("Hello world!"); that prints the output to the terminal  Hello world!.  In this line println! is called a Rust macro. We’ll discuss Rust macro in another lesson. We pass a string hello world! To Rust macro as the argument.
Rust statement end by typing a (;) semicolon at the end. In Rust, we indicate the end of the statements by typing a semicolon(;) 

Reference: