RUST AND PYTHON CODING BASICS

FOR ABSOLUTE BEGINNERS

BY

TAM SEL

Rust Programming Language

Rust Installation

First Rust program

'If' statement

"if-else"

Using - "if in a let" - statement

Loops

While loop

For loop

Rust Ownership

Rust - References and Borrowing

Slice In Rust

Update Syntax

Method Syntax

Rust Enum

Match Operator

Introduction to Python

Features of python

Install pip

Executing first program

Python Keywords

Python built-in keywords

Comments in Python

Block Comments in Python

Create multiline comments

Python Numeric Types

Variables and DataTypes

Determine a Python variable's type

Python Arithmetic Operators

Python Identity Operators

Membership Operators in Python

Behavior of increment operators in Python

Logical and Bitwise NOT Operators

Logical Operators on String

if else Conditional Operator

RUST

BASICS

FOR ABSOLUTE BEGINNERS

BY

TAM SEL

Rust Programming Language

Our Rust programming language is explained in detail for both beginners and experts. The Rust programming language is intended to improve memory safety, but it is still being developed.

What is Rust?

o Rust is a system programming language created by "Graydon Hoare," a Mozilla employee, in 2006. This language, he said, is "safe, concurrent, and practical," and it supports the functional and imperative paradigms.

o Rust's syntax is comparable to that of the C++ programming language.

o Rust is free and open source software, which means that anybody can use it for free, and the source code is openly released so that others can enhance the product's design.

o In the stack overflow developer survey in 2016, 2017, and 2018, Rust was named one of the "most appreciated programming languages."

o There is no calloc or malloc-style memory management. Rust is in charge of memory management internally.

Rust is for

Your text will be rewritten by QuillBot. Start by typing or pasting something into this box, then hit the enter key.

Let's look:

Team of developers:  For the "team of developers," Rust shows to be really handy. Low-level programming code has defects that must be thoroughly tested by testers. In the case of Rust, however, the compiler refuses to compile the code if it includes flaws. By working in parallel with the compiler, the developer may concentrate on the logic of the programme rather than on the bugs.

Students:  o Many people can learn how to construct an operating system using Rust. The Rust team is attempting to make system principles more approachable to non-programmers, particularly those who are new to the field.

Companies:  Rust is used by both large and small businesses to complete diverse jobs. Command-line tools, web services, DevOps tooling, embedded devices, audio and video analysis and transcoding, cryptocurrency, bioinformatics, search engines, Internet of Things applications, machine learning, and even large portions of the Firefox web browser are among these activities.

Open source developers:  Rust is an open source language, which means that the source code is freely available. As a result, they can use the source code to improve Rust's design.

Features of Rust

Rust is a programming language for systems. Rust has the following characteristics:

Zero cost abstraction

Error messages

Move semantics

Threads without data races

Pattern matching

Guaranteed memory safety

Efficient C bindings

Safe memory space allocation

Minimal time

1. Zero cost abstraction

We can add abstractions to Rust programming without compromising its runtime performance. It increases the clarity and quality of the code without sacrificing runtime efficiency.

2. Error messages

When compared to GCC, the error messages in C++ programming are vastly improved. In terms of clarity, Rust takes it a step farther. In our programme, error messages are presented with (formatting, colours) and also propose misspellings.

3. Type inference

Rust has a Type inference feature, which means it automatically detects the type of an expression.

4. Move semantics

When a source object is a temporary object, Rust provides this functionality that allows a copy action to be replaced by a move operation.

5. Threads without data races

A data race occurs when two or more threads access the same memory address at the same time. Because of the ownership mechanism in Rust, threads can run without data races. Only the owners of separate objects are sent to various threads via the ownership mechanism, and two threads can never own the same variable with write access.

6. Pattern matching

The pattern matching feature is available in Rust. Pattern matching in Rust uses patterns in conjunction with the'match' expressions to provide the programmer additional control over the control flow of the programme. The following are some pattern combinations:

Literals

Arrays, enums, structs, or tuples

Variables

Wildcards

Placeholders

7. Guaranteed memory safety

Rust used the concept of ownership to ensure memory safety. Ownership is a compromise between C's memory control and Java's garbage collection. Variables own memory space in Rust applications, which is temporarily borrowed by other variables. This allows Rust to offer memory safety without relying on the garbage collector at compile time.

8. Efficient C bindings

The feature of 'Efficient C bindings' in Rust means that the Rust language can communicate with the C language in the same way that it communicates with itself. Rust provides a 'foreign function interface' for interacting with C APIs while also leveraging its ownership structure to ensure memory safety.

9. Safe memory space allocation

Memory management in Rust is manual, which means that the programmer has explicit control over where and when memory is allocated and released. In C, we use the malloc function to allocate memory and subsequently initialise it, while Rust refuses to do both with a single " operator. The smart pointer to int is returned by this operator. A smart pointer is a type of value that determines when an item is released. Smart pointers are "smart" because they can not only track the location of an object but also clean it up.

Rust Installation

Installing Rust is the first step. To begin, use rustup to download Rust, which is a command-line utility for managing all Rust versions and associated tools.

Rust Installation - Windows

o To instal Rust on Windows, go to https://www.rust-lang.org/install.html and follow the instructions. Rust will be installed after you've followed all of the instructions, and the following screen will appear:

o Rust's PATH variable is automatically added to your system PATH after installation.

o Run the following command after opening the command prompt:

$ rustc --version   

You should see the version number, commit hash, and commit date after running this command.

If you see this, it implies Rust has been successfully installed. Congratulations!!!

Rust Installation - Linux or macOS

Open a terminal and type the following command if you're using Linux or macOS:

$ curl https: //sh.rustup.rs -sSf | sh    

o The programme above downloads a script and initiates the rustup tool installation. This will update Rust to the most recent version. The following message will appear if the installation was successful:

Rust  installed now. 

o After your next login, this installation will automatically add Rust to your system path. If you wish to launch Rust right immediately without having to restart your terminal, type the following command in your shell to manually add the path to your system PATH:

$ source $HOME/.cargo/env  

A linker is required after installation. The error "a linker could not execute" will appear when you try to launch your Rust application. It means your machine doesn't have the linker installed. The correct compiler is always found by C compilers. Install a C compiler on your computer. Additionally, some Rust packages rely on C code and will require a C compiler.

Updating & Uninstalling

Update:  After you've installed Rust using "rustup," you should update to the latest version. To update to the newest version, use the following command:

$ rustup update  

Uninstall:  If you wish to uninstall Rust, use the shell to perform the following command:

$ rustup  self  uninstall  

First Rust program

Let's write a simple program in the Rust programming language. Open the notepad file now and type the following code:

fn  main()  

    println!( "Hello, world!" );  

Output:

Hello, world!

main():  In every Rust executable code, the main() function is always the first code. Curly braces are used to encapsulate the main() function. The main() function does not take any arguments and does not return any results.

println!:  It's a macro written in Rust. It does not contain '!' if it calls the method.

"Hello World":  It's a string that's supplied to println! as an argument, and it's printed to the console.

Procedure to createcompile - run the program

1. Open the notepad file and type the code there.

2. The file should be saved with the.rs extension.

3. Open command prompt

4. Sets the directory's path. Assume the project is on the D drive.

5. Using the rustc command, compile the above programme.

6. Finally, execute the programme with the filename.exe command.

'If' statement

The 'if' statement checks to see if the condition is true. The 'if' block is performed if condition is true; else, control skips the 'if' block.

Different ways to represent 'if' block:

if block

if-else block

if else-if ladder

nested if

Syntax of 'if':

if  condition  

 {  

              //block statements;   

}  

If the condition is true in the above syntax, the block statements are performed; otherwise, the block is skipped.

Flow Chart of "if statement"

For Example:

Let's look at an example of a 'if' statement.

fn  main()  

  let  a= 1 ;  

  if  a== 1   

  {  

      println!( "a is equal to 1" );  

   }  

Output:

a is equal to 1

The value of an in this example is 1. As a result of the 'if' condition being true, the string submitted as an argument to println! is printed on the console.

"if-else"

The 'if' block is executed if the condition is true, and the statements inside the 'otherwise' block are skipped. If the condition is false, the 'else' block is performed instead of the 'if' block, and the statements inside it are skipped.

Syntax of "if-else"

  if  condition  

{  

    //block statements   

}  

else   

{  

     //block statements   

 }  

Flow Chart of "if-else"

Let's look at a simple 'if-else' statement.

  fn  main()  

{  

   let  a= 3 ;  

   let  b= 4 ;  

   if  a>b  

  {  

     println!( "a is greater than b" );  

  }  

   else   

   {  

     println!( "a is smaller than b" );   

   }  

}  

Output:

a is smaller than b

The value of an is equal to 3 in this case, and the value of an is smaller than the value of b. As a result, the else block is executed, and the message "a is smaller than b" is displayed on the screen.

else-if

The 'else-if' expression is used when you wish to verify multiple conditions.

Syntax of else-if

  if  condition  1   

{  

   //block statements   

}  

else   if  condition  2   

{  

   //block statements   

}   

.  

.  

else {  

//block statements   

}  

Rust executes the block for the first true condition in the above syntax, and once it finds the first true condition, it does not execute the remainder of the blocks.finds the first true condition then it will not execute the rest of the blocks.

Flow Chart - "else if"

Let's look at an example of an else-if statement.

fn  main()  

  let  num= - 5 ;  

  if  num> 0   

 {  

   println!( "number is greater than 0" );  

 }  

  else   if  num< 0   

 {  

   println!( "number is less than 0 " );  

 }  

  else   

 {  

   println!( "number is not equal to 0" );  

 }  

Output:

number is less than 0

The value of num in this example is -5, and num is less than 0. As a result, if block is executed.

Nested if-else

Nested if-else is defined as an if-else statement that is contained within the body of another if or else block.

Syntax - Nested if-else

  if  condition  1     of

{  

    // block statements   

    if  condition  2   

{  

       //block statements   

}  

else   

{  

     //block statements   

}  

}  

else   

{  

    //block statements   

}  

Let's look at a simple nested if-else example.

fn  main()  

  let  a= 5 ;  

  let  b= 6 ;  

  if  a!=b  

 {  

    if  a>b  

   {  

     println!( "a is greater than b" );  

   }  

    else   

    {  

      println!( "a is less than b" );  

    }  

 }  

  else   

{  

      println!( "a is equal to b" );  

 }  

Output:

a is less than b

The value of an in this example is not equal to the value of b. As a result, control is contained within the 'if' block, and an is less than b. As a result, the 'else' block, which is contained within the 'if' block, gets executed.

Using - "if in a let" - statement

On the right hand side of the let statement, a 'if' expression is utilised, and the value of the 'if' expression is assigned to the 'let' statement.

Syntax - 'if in a let'

 Let variable_name=  if  condition{  

//code blocks   

}    

else {  

//code block   

}  

If the condition is true, the value of the 'if' expression is assigned to the variable, and if the condition is false, the value of the 'else' expression is assigned to the variable in the above syntax.

Example 1

Simple example.

fn  main()  

  let  a= if   true   

       {  

           1   

       }  

        else   

       {  

            2   

       };  

 println!( "value of a is: {}" , a);  

Output:

value of a is: 1

The condition is true in this case. As a result, the value of the 'if' expression is bound by the 'a' variable. Now we have a value that consists of one.

Let's look at another Simple example

fn  main()  

  let  b= if   false   

       {  

           9   

       }  

        else   

       {  

            "Rustlang"   

       };  

 println!( "value of a is: {}" , a);  

Output:

Some errors occurred:E0308

The 'if' block in this example evaluates to an integer value, whereas the 'otherwise' section evaluates to a string value. As a result, this programme generates an error since both blocks contain values of different types.

Loops

If we want to execute the block of statements more than once, then loops concept If we wish to run a block of statements multiple times, the loops idea comes into play. A loop runs the code inside the loop body until it reaches the end, then restarts from the beginning.

There are three types of loops in Rust:

loops

for loop

while loop

loop

The loop isn't conditional in any way. It's a keyword that tells Rust to keep executing the same block of code until you explicitly terminate the loop.

Syntax of loop

  loop {  

   //block statements   

}  

Block statements are run an infinite number of times in the above syntax.

Flow diagram of loop:

Let's look at a simple infinite loop example.

fn  main()  

  loop   

 {  

     println!( "Hello Rustlang" );  

}  

Output:

Hello Rustlang

Hello Rustlang

Hello Rustlang

Hello Rustlang

.

.

.

infinite times

"Hello Rustlang" is printed over and over again in this case until we manually interrupt the loop. In most cases, the "ctrl+c" command is used to exit the loop.

Termination from loops

To get out of the loop, use the 'Break' keyword. If the 'break' keyword is not provided, the loop will run indefinitely.

Simple example

fn  main()  

  let   mut  i= 1 ;  

  loop   

 {  

       println!( "Hello Rustlang" );  

        if  i== 7    

       {  

          break ;  

       }  

 i+= 1 ;  

 }}  

Output:

Hello Rustlang

Hello Rustlang

Hello Rustlang

Hello Rustlang

Hello Rustlang

Hello Rustlang

Hello Rustlang

I is a counter variable in the above example, and it is a mutable variable, implying that the counter variable can be altered for future usage.

While loop

A conditional loop is the 'while-loop.' The conditional loop is used when a programme wants to examine a condition. If the condition is true, the loop is executed; otherwise, the loop is terminated.

Syntax - 'while loop'

while  condition  

//block statements;   

The while loop evaluates the condition in the above syntax. Block statements are executed if the condition is true; else, the loop is terminated. This built-in construct in Rust can be used in conjunction with the 'loop', 'if', 'else', or 'break' statements.

Flow diagram - while loop

Simple example

  fn  main()  

{  

   let   mut  i= 1 ;  

   while  i<= 10   

{  

   print!( "{}" , i);  

   print!( " " );  

   i=i+ 1 ;  

}  

}  

Output:

1 2 3 4 5 6 7 8 9 10

‘i’ is a mutable variable in the following example, which means that its value can be changed. The while loop runs until the value of ‘i’ is either less than or equal to ten.

Example

  fn  main()  

{  

   let  array=[ 10 , 20 , 30 , 40 , 50 , 60 ];  

   let   mut  i= 0 ;  

   while  i< 6   

  {  

    print!( "{}" ,array[i]);  

    print!( " " );  

    i=i+ 1 ;  

  }  

}  

Output:

10 20 30 40 50 60

The elements of an array were iterated in the above example using a while loop.

Disadvantages - while loop:

If the index length is incorrect, the While loop can cause problems.

It's also slow because the compiler adds runtime code to conduct the conditional check on each loop iteration.

For loop

The for loop is a conditional loop, which means it will run for a specific number of times. The behaviour of the for loop in rust differs slightly from that of other languages. The for loop runs until the condition is met.

Syntax - for loop

for  var  in  expression  

{  

     //block statements   

}   

An expression can be transformed into an iterator that iterates through the elements of a data structure using the syntax above. An iterator is used to fetch value on each iteration. The loop ends when there are no more values to fetch.

Example.

  fn  main()  

{  

   for  i  in   1 .. 11   

  {  

    print!( "{} " ,i);  

  }   

}  

Output:

1 2 3 4 5 6 7 8 9 10

1..11 is an expression in the previous example, and the iterator will iterate over these values. Because the upper bound is exclusive, the loop will print values from 1 to 10.

Example.

  fn  main()  

{  

let   mut  result;  

for  i  in   1 .. 11   

{  

result= 2 *i;  

println!( "2*{}={}" ,i,result);  

}  

}  

Output:

2*1=2

2*2=4

2*3=6

2*4=8

2*5=10

2*6=12

2*7=14

2*8=16

2*9=18

2*10=20

The table of two is printed by the for loop in the example above.

Example.

fn  main()  

  let  fruits=[ "mango" , "apple" , "banana" , "litchi" , "watermelon" ];  

   for  a  in  fruits.iter()  

 {  

   print!( "{} " ,a);  

 }   

Output:

mango apple banana litchi watermelon

The iter() technique is used in the preceding example to retrieve each element of the fruits variable. The loop ends when it reaches the last element of an array.

Difference - the while loop - for loop:

The while loop will exhibit an error if the index length of an array is increased at runtime, however this will not happen in the case of the for loop. As a result, we may conclude that the for loop improves the code's safety and reduces the likelihood of problems.

Rust Ownership

Understanding Ownership

Ownership is a unique feature of the Rust programming language that ensures memory safety without the use of a garbage collector or pointers.

What is Ownership?

The term "ownership" refers to when a piece of code owns a resource. The code constructs an object that holds the resource. The object is destroyed and the resource is freed when the control reaches the conclusion of the block.

Important points - Ownership:

The "owner" of a variable can modify its owning value. The term "ownership" refers to when a piece of code owns a resource. The code constructs an object that holds the resource. The object is destroyed and the resource is freed when the control reaches the conclusion of the block.

In accordance with mutability

Ownership can be transferred from one variable to another.

In Rust, ownership is simply a matter of semantics.

In addition to safety, the ownership model ensures it.

Rules of Ownership

Every value in Rust has a variable linked with it, which is referred to as its owner.

Only one owner can be present at any given moment.

When the owner is removed from the scope, the value connected with them is lost.

Example of Ownership

In Rust, many variables can interact with one another. Consider the following scenario:

Assigning the value - of x to the - variable y:

let  x= 10 ;  

et y=x;  

x is bound to the value 10 in the example above. The variable y is then given the value of x. Instead of creating a replica of x, the value of x is moved to the variable y in this scenario. As a result, ownership of the variable x is transferred to the variable y, and the variable x is deleted. Rust throws an exception if we try to reuse the variable x. Let's look at an example to see how this works.

fn  main()  

let  x= 10 ;  

let  y=x;  

println!( "value of x :{}" ,x);  

The output of the above example is as follows:

Memory and Allocation

Data can be stored in either stack or heap memory in Rust.

Stack memory:  Data is always inserted in order in stack memory and deleted in the opposite order.

It works on the "last in, first out" concept, which means that the data that was inserted last is always erased first.

Stack memory is a type of memory that is well-organized. Because of the way it accesses memory, it is faster than heap memory.

If the size of the data is unknown at compile time, the content is stored in heap memory.

Heap memory:  Heap memory is a type of memory that is well-organized.

The operating system returns a pointer to an empty place in the heap memory. This is referred to as "allocating on the heap."

Data is always inserted in order in stack memory and deleted in the opposite order.

It works on the "last in, first out" concept, which means that the data that was inserted last is always erased first.

Stack memory is a type of memory that is well-organized. Because of the way it accesses memory, it is faster than heap memory.

If the size of the data is unknown at compile time, the content is stored in heap memory.

The pointer is stored in the stack, whereas the content is stored in the heap.

Let's see - simple example

  fn  main()  

{  

   let  v1=vec![ 1 , 2 , 3 ];  

   let  v2=v1;  

}  

Step 1:

Vector v1 is bound to the numbers 1,2 and 3 in the first statement of the programme.

A vector is made up of three parts: a memory pointer referring to the data stored in memory, the vector's length, and the vector's capacity.

As seen below, these components are stored in the stack, whereas data is kept in the heap memory:

Step 2:

The v1 vector is assigned to the vector v2 in the second statement of the programme.

We copy the reference, length, and capacity to the stack, but not the contents to the heap memory. Let's have a look at how the memory is represented:

This form of depiction, however, can be problematic.

When both v1 and v2 have exited the scope, they will both attempt to free memory.

This results in a double free memory situation, which leads to memory corruption.

Step 3:

To ensure memory safety, Rust avoids the step 2 condition.

Rust decides that the v1 vector is no longer valid and does not replicate the allocated memory.

As a result, it is unnecessary to free the memory of v1 because v1 has exited the scope.

Use of - Copy trait

The copy trait is a particular annotation that is applied to types that are stored on the stack, such as integers. If the types have the copy trait, the older variable can be used even after the assignment action.

Ownership and functions

When a variable is handed to a function, ownership is transferred to the called function's variable. Passing value has the same semantics as assigning a value to a variable.

Let's look at an example to help you understand:

  fn  main()  

{  

   let  s=String::from( "Rustlang" );  

  take_ownership(s);  

   let  ch= 'a' ;  

  moves_copy(ch);  

  println!( "{}" ,ch);  

}  

fn  take_ownership(str:String)  

{  

 println!( "{}" ,str);  

}  

fn  moves_copy(c:char)  

{  

  println!( "{}" ,c);  

}  

Output:

Rustlang

a

a

The string's' is bound to the value "Rustlang" in the preceding example, and the ownership of the's' variable is handed to the variable'str' using the take ownership() function.

The ownership of the 'ch' variable is handed to the variable 'c' through the moves copy() function, which binds with the value 'a.'

Because the type of the 'ch' variable is a "copy" trait, it can also be utilised later.

Returning - value and scope

When you return values from a function, you're also transferring ownership. Consider the following:

  fn  main()  

{  

   let  x= gives_ownership();  

  println!( "value of x is {}" ,x);  

 }  

fn  gives_ownership()->u32  

{  

      let  y= 100 ;  

     y  

}  

Output:

value of x is 100

The gives ownership() function returns the value of y, which in this case is 100, and ownership of the y variable is transferred to the x variable.

Rust - References and Borrowing

A reference is an address that is supplied as an argument to a function. Borrowing is the same as borrowing something and returning it after we are finished with it. Borrowing and references are mutually exclusive, meaning that when a reference is relinquished, the borrowing ceases as well.

Why Borrowing?

The concept of borrowing is utilised for the following reasons:

Borrowing permits many references to a single resource while maintaining the need of a "single owner."

In C, references are similar to pointers.

An object is a reference. There are two sorts of references: changeable and immutable references. Irreversible references are copied, while changeable references are relocated.

Let's look at an example to see how this works.

  fn  main()  

{  

  let  str=String::from( "Rustlang" );  

  let  len=calculate_length(&str);  

 println!( "length of the string {}" ,len);  

}  

fn  calculate_length(s:&String)->usize  

{  

  s.len()  

}  

Output:

length of the string 10

The calculate length() function has a reference to string str as a parameter in the example above, but it does not take ownership of it.

let  str=String::from( "Rustlang" );  

et len=calculate_length(&str);  

&str is a reference to variable str in the example above, but it does not own it. As a result, even if the reference goes out of scope, the value referred by it will not be lost.

fn  calculate_length(s:&String)->usize  

 s.len()  

Variable's' is valid in the aforementioned scenario until the control does not return to the main() function. When the variables are supplied to the function as a reference rather than actual values, we don't need to return the values to reclaim ownership.

Let's see if we can change the borrowed value.

  fn  main()  

{  

  let  x= 1 ;  

 value_changed(&x)  

}  

fn  value_changed(y:&i32)  

{  

 *y= 9 ;  

}  

Following is the output

Because &x is an immutable reference, it throws an error in the case above. As a result, we are unable to change the value of y.

Mutable Reference

Using a mutable reference, we may correct the aforementioned issue. Changeable references are those that can be changed. Let's look at an example to see how this works.

  fn  main()  

{  

  let   mut  x= 1 ;  

 value_changed(& mut  x);  

 println!( "After modifying, the value of x is {}" ,x);  

}  

fn  value_changed(y:& mut  i32)  

{  

 *y= 9 ;  

}  

Output:

After modifying, the value of x is 9

We construct a mutable reference, &mut x, in the preceding example, and the reference is directed by the &i32 type variable y. We may now adjust the value that the 'y' variable refers to. We assign a value of 9 to it, i.e. *y=9. As a result, the value x becomes 9 because both variables point to the same memory address.

Restrictions - of Mutable references

In a given scope, we can only have one mutable reference to a piece of data.

For example:

  let   mut  str=String::from( "Rustlang" );  

let  a= & mut  str;  

let  b= & mut  str;   

The compiler throws an error in the above scenario because it contains two mutable references, which are not allowed in the Rust language.

If we have an immutable reference in our application, then we can't have a changeable reference.

For example:

  let   mut  str=String::from( "Rustlang" );  

let  a= &str;  

let  b=&str;  

let  c=& mut  str;   

The compiler throws an error in the above scenario because we can't have a changeable reference while also having an immutable reference.

Slice In Rust

Slice is a data type that isn't owned by anyone.

Instead of referencing the entire collection, Slice refers to a contiguous memory allocation.

It allows you to access an array in a safe and efficient manner without having to replicate it.

Slice is derived from an existing variable rather than being constructed from scratch.

The length of a slice determines whether it is mutable or not. Slices only behave like arrays.

String slice

A string slice is a section of the string. The following is an example of a slice:

  let  str=String::from( "Rustlang tutorial" );  

let  Rustlang=&str[ 0 .. 10 ];  

let  tutorial=&str[ 11 , 18 ];  

Rather than taking the complete string, we'd like to take a segment of it.

The [start..end] syntax denotes a range that starts at the beginning and ends at the end.

As a result, we may create a slice by defining the range within brackets, such as [start..end], where'start' defines the element's starting position and 'end' is one place greater than the slice's ending location.

If we wish to include the string's end, we must use '..=' rather than '..'.

  let  str= String::from( "Rustlang tutorial" );  

let  Rustlang = &str[ 0 ..= 9 ];  

let  tutorial= &str[ 11 ..= 18 ] ;  

Diagrammatically representation:

If you want to start the index at zero, we can also remove the initial index. It appears to be as follows:

  let  str= String::from( "hello world" );  

let  hello = &str[ 0 .. 5 ];  

let  hello=&str[.. 5 ];  

We can also remove the first index if you want to start the index at zero. The following appears to be the case:

  let  str= String::from( "hello world" ) ;  

let  hello=&str[ 6 ..len];  

let  world = &str[ 6 ..];  

Let's see a - simple example

fn  main()   

let  str=String::from( "Rustlang tutorial" );  

let  Rustlang=&str[..= 9 ];  

println!( "first word of the given string is {}" ,Rustlang);  

Output:

first word of the given string is Rustlang

String slices are literals

String literals are only considered string slices since they are stored in binary. Let's have a look:

let  str =  "Hello Rustlang"  ;  

'&str' is the type of'str'. It's a slice that points to a certain binary point. '&str' is an immutable reference, and string literals are immutable.

String slices - as parameters

We can pass a string slice directly if we have one.

To make an API more broad and useful without losing its functionality, we give the string slice as an argument to the method instead of the reference.

  fn  main()  

{  

  let  str= String:: from( "Computer Science" );  

let  first_word=  first_word(&str[..]);  //first_word function finds the first word of the string.   

let  s= "Computer Science"  ;  //string literal   

let  first_word=first_word(&s[..]);  // first_word function finds the first word of the string.   

let  first_word=first_word(s) ;  //string slice is same as string literal. Therefore, it can also be        

                                                  written  in  this way also.                             

}  

Other slices

Slices can be used to treat an array.

They have the same behaviour as a string slice.

The type of the slice is [&i32]. They work in the same way as a string slice, with a reference as the first element and length as the second.

Consider a array:

let  arr = [ 100 , 200 , 300 , 400 , 500 ];   // array initialization   

et a = &arr[ 1 ..= 3 ];  // retrieving second,third and fourth element   

Let's see a simple example.

fn  main()  

let  arr = [ 100 , 200 , 300 , 400 , 500 , 600 ];  

let   mut  i= 0 ;  

let  a=&arr[ 1 ..= 3 ];  

let  len=a.len();  

println!( "Elements of 'a' array:" );  

while  i<len  

{  

 println!( "{}" ,a[i]);  

 i=i+ 1 ;  

}  

}  

Output:

Elements of 'a' array:

200

300

400

What is a structure?

A structure is a data type that is specified by the user and consists of variables of various data kinds.

The struct keyword is used before the structure name to define it.

The curly brackets enclose the structure members.

Structure members are defined with their name and type inside the curly brackets, and structure members are also known as fields.

The Syntax of - structure:-

  struct  Student  

{  

member-variable1;  

member-variable2;  

.  

.  

}  

The keyword struct is used to define structure in the above syntax. A structure is made up of variables of various types.

How to declare - the instance - of a structure

  let  user = Student{  

// key:value pairs;   

}  

A user is an instance of the Student structure in the above statement.

The structure name is followed by curly brackets to define it.

The curly brackets contain key:value pairs, with keys indicating the field names and values indicating the data to be stored in the key field.

Let's make an employee structure:

  struct  Employee{  

employee_name : String,  

employee_id: u64,  

employee_profile: String,  

active: bool,  

}  

An example of employee structure is as follows:

  let  employee = Employee{  

employee_name : String::from( "Akshay Gupta" ),  

employee_id:  12 ,  

employee_profile : String::from( "Computer Engineer" ),  

active :  true ,  

};  

How can I get to a certain Structure member variable?

Dot notation can be used to access a structure's individual member variable.

If we want to get at the employee name variable in an Employee structure, we can do so as follows:

employee.employee_name;  

  let   mut  employee = Employee{  

employee_name : String::from( "William" ),  

employee_id:  12 ,  

employee_profile : String::from( "Computer Engineer" ),  

active :  true ,  

};  

employee.employee_name = String :: from( "John" ); 

Within the function body, create an instance:

  fn  create_employee(name:String, profile:String)  

{  

Employee{  

employee_name:name,  

employee_id: 12 ,  

employee_profile:profile,  

active: true ,  

}  

}  

Employee structure is formed implicitly within the function body in the preceding example.

The function create employee() creates an instance of the Employee structure with the specified name and profile.

When the function's parameters and fields have the same name, use the Field Init Shorthand.

When both the variables and fields have the same name, Rust allows you to use field init shorthand.

Fields and variables do not need to be repeated.

  fn  create_employee(employee_name:String, employee_profile:String)  

{  

Employee{  

employee_name,  

employee_id: 12 ,  

employee_profile,  

active: true ,  

}  

}  

The names of the parameters and fields are the same in the example above. As a result, there is no need to write employee name:employee name; instead, employee name can be written directly.

Update Syntax

Using the Struct update syntax, create a new instance from existing ones.

We can use the struct update syntax when a new instance uses the majority of the values from an older instance. Consider the following two workers: employee1 and employee2.

First, build the employee1 instance of the Employee structure:

  let  employee1 = Employee{  

employee_name : String::from( "William" ),  

employee_id:  12 ,  

employee_profile : String::from( "Computer Engineer" ),  

active :  true ,  

};  

Second, create the employee2 instance. Some of the values in the employee2 instance are identical to those in the employee1 instance. The employee2 instance can be declared in two ways.

The first method is to declare the employee2 object without changing the syntax.

  let  employee2 = Employee{  

employee_name : String::from( "John" ),  

employee_id:  11 ,  

employee_profile : employee1.employee_profile,  

active : employee1.active,  

};  

The second method is to use syntax update to declare the employee2 instance.

  let  employee2 = Employee{  

employee_name : String::from( "John" ),  

employee_id:  11 ,  

..employee1  

};  

The '..' syntax indicates that the remaining fields are not explicitly set and have the same value as the fields in the current instance.

Let's look at a simple Structure example:

  struct  Triangle  

{  

base:f64,  

height:f64,  

}  

fn  main()  

{  

let  triangle= Triangle{base: 20.0 ,height: 30.0 };  

print!( "Area of a right angled triangle is {}" , area(&triangle));  

}  

fn  area(t:&Triangle)->f64  

{  

0.5  * t.base * t.height  

}  

Output:

Area of a right angled triangle is 300

The structure of a triangle is established in the preceding example, and it contains two variables, namely the base and height of a right-angled triangle.

Within the main() method, a Triangle instance is generated.

Method Syntax

Methods are similar to functions in that they begin with the fn keyword and then the name of the function.

Parameters and return values are also included in methods.

When a method is specified within a struct, however, the method syntax differs from that of a regular function.

Self, which represents the instance on which the function is called, is always the first parameter of such methods.

Defining methods

When the method is declared in the struct context, let's define it.

  struct  Square  

{  

a : u32,  

}  

impl  Square  

{  

fn  area(& self )->u32  

{  

self .a *  self .a  

}  

}  

fn  main()  

{  

let  square = Square{a: 10 };  

print!( "Area of square is {}" , square.area());  

}  

Output:

Area of square is 100

We define the method inside the implementation block, i.e., impl block, when it is declared within the struct context.

  impl  Square  

{  

fn  area(& self )->u32  

{  

self .a *  self .a  

}  

}  

The first criterion is to be self-aware in the signature and throughout the body.

To invoke the area() function, we utilise the method syntax. An instance is followed by the dot operator, the method name, the parameter, and any arguments in the method syntax.

square.area();  

The square is an instance, and the function name is area().

Method syntax has the following benefit:

The key advantage of method syntax over functions is that all data pertaining to the instance is contained within the impl block opposed than being scattered throughout the code.

Rust Enum

Enum is a special data type that has a set of fixed values. The name of the enumeration is preceded by the enum keyword. It also includes methods.

The syntax - enum:

  enum  enum_name  

{  

  variant1,  

 variant2,  

.  

.  

}  

The enum name is the name of the enum, and variant1,variant2,... are the enum values associated with the enum name in the above style.

For example:

enum  Computer_language  

  C,  

  C++,  

  Java,  

Computer language is the enum name in the previous example, and the values of computer language are C, C++, and Java.

Enum values

Let's start by making an instance of each variation. It appears to be as follows:

  let  c = Computer_language :: C;  

let  cplus = Computer_language :: C++;  

let  java = Computer_language :: Java;  

In the situation above, we construct three instances, c, cplus, and java, each with the values C, C++, and Java.

Under its identification, each form of enum has been namespaced, and a double colon has been utilised.

Because Computer language::C, Computer language::C++, and Computer language::Java all belong to the same type, Computer language, this is useful.

A function can also be defined on a specific instance. Let's define the function that takes a Computer language instance, which looks like this:

fn  language_type(language_name::Computer_language);  

Any of the following variants can invoke this function:

language_type(Computer_language :: C++);  

Let's have a look at an example.

 #[derive(Debug)]  

enum  Employee {  

    Name(String),  

    Id(i32),  

    Profile(String),  

}  

fn  main() {  

     let  n = Employee::Name( "Hema" .to_string());  

     let  i = Employee::Id( 2 );  

     let  p = Employee::Profile( "Computer Engineer" .to_string());  

    println!( " {:?} s {:?} b {:?}" , n,i,p);  

}  

Output:

Name("Hema") s Id(2) b Profile("Computer Engineer")

Employee is a custom data type in the example above, with three variants: Name(String), Id(i32), and Profile (String). The ":?" is used to print each variant's instance.

Match Operator

The match operator compares a value to a set of patterns and runs the code if a match is found. Literal values, variable names, wildcards, and a variety of other items can be used as patterns.

Let's look at an example to better understand the match operator:

  enum  Computerlanguage  

{  

  C,  

  Cplus,  

  Java,  

  Csharp,  

}  

fn  language(language:Computerlanguage)  

{  

  match  language  

 {  

   Computerlanguage::C=> println!( "C language" ),  

   Computerlanguage::Cplus=> println!( "C++ language" ),  

   Computerlanguage::Java=> println!( "Java language" ),  

   Computerlanguage::Csharp=> println!( "C# language" ),  

 }  

}  

fn  main()  

{  

 language(Computerlanguage::C);  

 language(Computerlanguage::Cplus);  

 language(Computerlanguage::Java);  

 language(Computerlanguage::Csharp);  

}  

Output:

C language

C++ language

Java language

C# language

Computerlanguage is a custom data type in the example above, with four variants: C, Cplus, Java, and Csharp. The match operator compares the language's value to the expressions in the matching operator block.

Matching with - Option<T>

When we wish to get the inner value of T from a case, we utilise Option<T>.

There are two variations of Option<T>:

None:  It denotes a failure or a lack of worth.

Some(value):  It's a tuple struct that wraps T around the value.

Let's have a look at an example:

  fn  main()  

{  

 even_number( 2 );  

 even_number( 3 );  

}  

fn  even_number(n:i32)  

{  

  let  num=n;  

   match  checked_even(n)  

  {  

    None=>println!( "None" ),  

    Some(n)=>  

    {  

     if  n== 0   

    {  

    println!( "{} is a even number" ,num);  

    }  

     else   

    {  

    println!( "{} is a odd number" ,num);  

    }},  

  }  

}  

fn  checked_even(number:i32)->Option<i32>  

{  

  Some(number% 2 )  

}  

Output:

2 is a even number

3 is a odd number

Matches are exhaustive

Matches in Rust are exhaustive, which means that the code must cover all potential scenarios in order to be valid. If we forget to write the None case, the Rust compiler will report "pattern 'None' not covered" as an error.

Let's look at an example to better grasp this situation:

  fn  main()  

{  

 Some( 5 );  

}  

fn  Value(n:Option<i32>)  

{  

   match  n  

  {  

    Some(n)=>println!( "{}is a Number" ,n),  

  }  

}  

Output:

PYTHON

CODING BASICS

FOR ABSOLUTE BEGINNERS

BY

TAM SEL

Introduction to Python

sailent features of Python

It is a programming language of general intent that can be used for both scientific and non-scientific programming.

For beginners, it is excellent as the language is translated, thereby producing immediate results.

It incorporates better than the other languages of its time the principle of exception handling and dynamic binding.

Easily readable and understandable are the programmes written in Python.

It is a programming language independent of a platform.

For customizable applications, it is suitable as an extension language.

Learning and using it is simple.

Major Applications

Google search engine , Twitter, etc.

Using Python, Bit Torrent peer to peer file sharing is written.

Python for hardware testing is used by Intel, Cisco, HP , IBM, etc.

A Python scripting API is provided by Maya.

For the creation of industrial robots, Python Used

For their scientific programming activities, NASA and others use Python.

Setting up Python Interpreter

In order to write and run a Python programme, we need to instal a Python interpreter on our computer.

The standard and most common Python development environment is IDLE (GUI integrated).

IDLE refers to the world of Integrated Growth.

This allows a single gui to modify, run, search and debug Python programmes. This atmosphere makes writing programmes simple.

NOTE: In these tutorials, we'll be using version 3.6 of Python IDLE to develop and run Python code. It is available for free at www.python.org.

start up the IDLE

Features of python

Object oriented

Strong exception handling

Automatic memory management

Dynamic

Strong data types

Easy syntax

Indentation based

Forgiving in nature

Printing "Hello World" in Python

Install pip

Pip is a platform that enables the installation and management of python packages.

Python: install pip

In order to instal the new version of pip, run command  in the MacOS

    $ sudo easy_install pip

    $ sudo pip install --upgrade pip

  install the pip in the Ubuntu

    $ sudo apt-get update

    $ sudo apt-get install python-pip

    $ sudo pip install --upgrade pip

pip in Centos

    $ sudo yum update

    $ sudo yum install epel-release

    $ sudo yum install python-pip

    # version>= Centos7

    $ sudo pip install --upgrade pip

Executing first program

We will launch Python on our device to function in the interactive mode.

After the prompt (> > >), we type the Python expression / statement / command and Python automatically responds with the output of the prompt.

First program on Python

Let 's begin by typing "Hello Python!" after the prompt.

>>>print("Hello Python!")

Try the following

a) 5+7
b) 4*10
c) 7/8
d) 9%2
e) 6//4

Also try this

>>> x=1

>>> y=5

>>> z = x+y

>>> print (z)

Other operation:

>>> a=3

>>>a+1, a-1

2) Script Mode

We type the Python program into a file in script mode and then use the interpreter to execute the material from the file.

It is useful for beginners and for testing small pieces of code to function in interactive mode, as we can test them immediately.

But we should still save our code so that we can change and reuse the code to encode more than a few lines.

We'll use the following steps in IDLE to build and run a Python script if the script mode is not made accessible by default in the IDLE environment.

File>New File

Write the Python code.

Save it  (^S) .

Execute it interactive mode- by (^F5) - using RUN option 

Step 1:  File> New File

Step 2:  Write:

def test():

x=2

y=6

z = x+y

print (z)

Step 3:  Save or File > Save As

Step 4:  For execution, press ^F5

>>>test()

Python Keywords

Keywords are the Python programming language's reserved words (and any other programming languages such as C , C++ , Java, etc.) whose definitions are defined and whose definitions can not be modified.

The keywords in python programming languages are case-sensitive.

Python keyword list

In Python 2.5

    and       del       from      not       while   

    as        elif      global    or        with    

    assert    else      if        pass      yield   

    break     except    import    print             

    class     exec      in        raise             

    continue  finally   is        return            

    def       for       lambda    try

In Python 3.8.1

    False   None    True    and     as

    assert  async   await   break   class

    continue def    del     elif    else

    except  finally for     from    global

    if      import  in      is      lambda

    nonlocal not    or  pass    raise

    return  try     while   with    yield

Python built-in keywords

There are built-in python keywords in the python programming language, which are used to perform different tasks for different purposes.

All python keywords – List

Comments in Python

Comments in Python are used to increase the code's readability.

For a better understanding of code and logic that they have used to solve the given issue to the reader, it is valuable information provided by the programmer in source code.

During compilation, comments are not executed and are not shown on the output either.

Types of comments in Python

Single line comment (#)

Multi-line string as comment (''')

1)   Single line comments

Single-line comments are used for one-line statements in Python, such as explanations of various variables , functions, expressions, etc.

A hash (#) symbol is used to render single-line comments without whitespace when the comments go to the next line, then at the beginning of the next line they must position each other's hashtag (#).

Let's see an instance and try to understand how in the software we apply the single-line comments.

EXAMPLE

# Single line comments example

# a program to print a given string and addition.

print('Welcome @ Learnpython')

a=2

b=5

print(a+b)

# addition of both numbers by using plus(+) sign.

2) Multi-line string comments

As we've seen in the above example, we have to put a hash (#) symbol in each line for multi-line comments.

In Python, multi-line string comments are given using the delimiter When it does not fit into one line, it is helpful.

We have to enclose the string with a delimiter at both ends for multiline string comments.

EXAMPLE

'''

    Here we will check a given number n is even or odd

    with multi-line comments in Python.

'''

n=6768

if n%2==0:

       print("Even number.")

else:

      print("Odd number.")

Block Comments in Python

Comments

A comment is a piece of text in a computer program that is intended to be an interpretation or annotation.

It readable by the author in the source code and that is ignored by the compiler / interpreter.

Type of Python Comments

Block Comments  and  Inline Comments ,

1) Block Comments

For the piece of code that follows, Block comments apply. It may refer to a part of the code or the code as a whole.

They have the same degree of indentation as that code.

Each comment line begins with a #.

EXAMPLE

# Python program to print

# Hello World

print("Hello World")

Output:

Hello World

It is also possible to make block comments using ''' '' ' Something written in these quotes is known as Comment.

EXAMPLE

'''

Python program to print

Hello World

'''

print("Hello World")

EXAMPLE 2

def hello():

    '''

    Here, this is docstring

    since it is written right after

    the function definition.

    below given print statement will print

    Hello World

    '''

    print("Hello World")

if __name__ == "__main__":

  # calling hello function

  hello()

2) Inline Comments

A comment on the same line as a declaration is an inline comment.

Inline remarks should be separated from the argument by at least two spaces.

They're supposed to begin with a # and a single room.

EXAMPLE

print("Hello World")  # This is an inline comment

OUTPUT

Hello World

Create multiline comments

There are two ways to do this when we need to comment on several lines / statements, either comment on each line or build multiline comments (or block comment).

The first approach is to comment on every section,

This can be regarded as a single line comment in Python-at the beginning of each line to be commented, we use the hash character (#).

# This is line 1

# This is line 2

# This is line 3

And, the second way to comment on the segment,

This can be considered in Python as a multiline comment-we use triple single quotes ("') at the beginning of the segment to be commented and triple single quotes ("') at the end.

'''

This is line 1

This is line 2

This is line 3

'''

EXAMPLE

'''

Function name: print_text

Parameters: None

Return type: None

Description: This function will print

some text on the screen

'''

def print_text():

  print("Hello, world! How are you?")

if __name__ == "__main__":

  # Here, we will call the print_text function

  # that will print some text on the screen

  print_text()

Python Numeric Types

Data types are an important concept in programming.

Data of different kinds can be stored in variables according to the role that we want the variables to perform.

In Python, the built-in data types are

Text Type

Numeric Type

Mapping Type

Sequence Type

Set Type

Boolean Type

Binary Type

3 numeric data types in Python:

int

float

comple

1) int

The Integer numeric form is used without decimal points to store signed integers, such as -5, 2, 78, etc.

EXAMPLE

# Assigning integer values to Variables

x = 8

y = -9

# Manipulating the value of x

x = x + y

# Prints the updated value of x

print("x= ", x)

# Prints the Data Type of x

print("Data type of x: ", type(x))

Output

x=  -1

Data type of x:  <class 'int'>

2) float

The numerical form of float is used to store floating-point values such as 6.66, 58.9, 3.14, etc.

Floats can be in scientific notation as well, with a power of 10 (3.6e3 = 3.6x 103 = 3600) indicated by E or e.

EXAMPLE

# Assigning float values to Variables

x = 8.9

y = -9.1

# Manipulating the value of x

x = x - y

# Prints the updated value of x

print("x= ", x)

# Prints the Data Type of x

print("Data type of x: ", type(x))

Output

x=  18.0

Data type of x:  <class 'float'>

3) complex

To store complex numbers such as 3.14j, 8.0 + 5.3j, 2 + 6j, etc., the complex numeric form is used.

Format: Real component + Imaginary component j

Note: J must denote the imaginary part of a complex number. It is known to be an invalid syntax in Python if we denote it with i.

EXAMPLE

# Assigning complex values to Variables

x = 1+8.5j

y = 4+9j

# Manipulating the value of x

x = x + y

# Prints the updated value of x

print("x= ", x)

# Prints the Data Type of x

print("Data type of x: ", type(x))

Output

x=  (5+17.5j)

Data type of x:  <class 'complex'>

Variables and DataTypes

1. Number

Data type numbers store numerical values. This type of data is eternal, i.e. the meaning of its object can not be modified (this aspect will be addressed later).

They come in three different kinds:

•         Integer & Long

•         Float/floating point

•         Complex

i) Integers:

Integers are whole numbers with decimal digits such as 100000, -99, 0, 17 consisting of + or-sign.

L is appended to the value when we want a value to be viewed as a very long integer value. Python considers those values as long integers.

>>> a = 10

>>> b = 5192L #example of supplying a very long value to a variable

>>> c= 4298114

>>> type(c) # type ( ) is used to check data type of value

ii) Floating Point:

Floating-point numbers are called numbers of fractions or decimal points.

A floating point number consists of a decimal digit series of signs (+,-) and a dot such as 0.0, -21.9, 0.98333328, 15.2963.

iii) Complex:

The python complex number consists of two floating point values, each one for real and imaginary sections.

We'll use x.real and x.image to access various parts of the vector (object) x.

The imaginary part of the number is defined by j instead of I so the imaginary part of 1 + 0j denotes zero.

EXAMPLE

>>> x = 1+0j

>>> print (x.real,x.imag)

1.0 0.0

2. None

This is a particular category of data with a single value. It is used in a scenario to indicate the absence of value / false. It is pictured by None.

3. Sequence

An ordered set of objects, indexed by positive integers, is a sequence.

It is a mixture of data types that are mutable and non-mutable.

Lines, Lists & Tuples are three sequence data form types available in Python.

3.1) String:

It is an ordered sequence of characters / letters.

They are found in single quotes (") or double quotes (").

The quotes do not form part of the string.

They just tell the machine where it starts and ends with the string constant.

>>>type ('Good Morning')

<class'str'>

>>> type ('3.2')

<class'str'>

3.2) Lists:

The list is also a sequence of some sort of importance.

The values are called elements / objects in the list. Mutable and indexed / ordered are these.

In square brackets, the list is enclosed.

3.3) Tuples:

Tuples are a set of values and are indexed by integers of some kind. They're unchangeable.

4. Sets

Set is an unordered array of values, without duplicate entry, of any kind. Sets will be timeless.

EXAMPLE

>>>s = set ([1,2,3,4])

>>>print(s)

{1, 2, 3, 4 }

Determine a Python variable's type

1) type() method

If type() is passed to a single argument, it returns the type of the given object.

EXAMPLE

>>> test_string = "yes"

>>> test_number = 1

>>> print(type(test_string))

<class 'str'>

>>> print(type(test_number))

<class 'int'>

2) isinstance() method

The isinstance() function tests whether an object (the first argument) is a classinfo class instance or subclass (the second argument)

EXAMPLE

>>> class Example:

...     name = 'include_help'

...

>>> ExampleInstance = Example()

>>> print(isinstance(ExampleInstance, Example))

True

>>> print(isinstance(ExampleInstance, (list, set)))

False

>>> print(isinstance(ExampleInstance, (list, set, Example)))

True

>>>

Comparison between type() and isinstance()

Python Arithmetic Operators

Arithmetic operators are used to perform different arithmetic / mathematical operations, and they are binary operators, meaning that calculations require two operands.

Syntax:

    exp1  +  exp2

    exp1  -  exp2

    exp1  *  exp2

    exp1 **  exp2

    exp1  /  exp2

    exp1 //  exp2

    exp1  %  exp2

PROGRAM

# Python program to demonstrate

# the example of arithmetic operators

a = 10

b = 3

# printing the values

print("a:", a)

print("b:", b)

# operations

print("a + b :", a + b)

print("a - b :", a - b)

print("a * b :", a * b)

print("a ** b:", a ** b)

print("a / b :", a / b)

print("a // b:", a // b)

print("a % b :", a % b)

Output:

a: 10

b: 3

a + b : 13

a - b : 7

a * b : 30

a ** b: 1000

a / b : 3.3333333333333335

a // b: 3

a % b : 1

EXAMPLE 2

# Python program to demonstrate

# the example of arithmetic operators

a = 10.10

b = -2.5

# printing the values

print("a:", a)

print("b:", b)

# operations

print("a + b :", a + b)

print("a - b :", a - b)

print("a * b :", a * b)

print("a ** b:", a ** b)

print("a / b :", a / b)

# // operator rounds the result

# down to the nearest whole number

print("a // b:", a // b)

print("a % b :", a % b)

Output:

a: 10.1

b: -2.5

a + b : 7.6

a - b : 12.6

a * b : -25.25

a ** b: 0.0030845837443758094

a / b : -4.04

a // b: -5.0

a % b : -2.4000000000000004

EXAMPLE 3

# Python program to demonstrate

# the example of arithmetic operators

# Operations on lists, strings, etc

x = "Hello"

y = "World"

# '+', '*' with strings

print("x + y:", x + y)

print("x + y + x:", x + y + x)

print("x * 2:", x * 2)

print("x * 10:", x * 10)

print()

# '+', '*' with lists

x = [10, 20, 30, 40]

y = [40, 30, 20, 10]

print("x + y:", x + y)

print("x + y + x:", x + y + x)

print("x * 2:", x * 2)

print("x * 3:", x * 3)

print()

Output:

x + y: HelloWorld

x + y + x: HelloWorldHello

x * 2: HelloHello

x * 10: HelloHelloHelloHelloHelloHelloHelloHelloHelloHello

x + y: [10, 20, 30, 40, 40, 30, 20, 10]

x + y + x: [10, 20, 30, 40, 40, 30, 20, 10, 10, 20, 30, 40]

x * 2: [10, 20, 30, 40, 10, 20, 30, 40]

x * 3: [10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 40]

Python Identity Operators

Identity operators are used to perform an object comparison operation, i.e., these operators check whether or not both operands apply to the same objects (with the same memory location).

The Identity Operators are follows,

Syntax:

    operand1 is operand2

    operand1 is not operand2

'is' operator example

# Python program to demonstrate the

# example of identity operators

x = [10, 20, 30]

y = [10, 20, 30]

z = x

# Comparing the values using == operator

print("x == y: ", x == y)

print("y == z: ", y == z)

print("z == x: ", z == x)

print()

# Comparing the objects

# whether they are referring

# the same objects or not

print("x is y: ", x is y)

print("y is z: ", y is z)

print("z is x: ", z is x)

print()

Output:

x == y:  True

y == z:  True

z == x:  True

x is y:  False

y is z:  False

z is x:  True

'is not' operator example

# Python program to demonstrate the

# example of identity operators

x = [10, 20, 30]

y = [10, 20, 30]

z = x

# Comparing the values

# using != operator

print("x != y: ", x != y)

print("y != z: ", y != z)

print("z != x: ", z != x)

print()

# Comparing the objects

# whether they are referring

# the same objects or not

print("x is not y: ", x is not y)

print("y is not z: ", y is not z)

print("z is not x: ", z is not x)

print()

Output:

x != y:  False

y != z:  False

z != x:  False

x is not y:  True

y is not z:  True

z is not x:  False

Membership Operators in Python

Membership Operators are the operators used to check if a value / variable, such as string, list, tuples, sets, dictionary or not, exists in the sequence.

Python Membership Operators

EXAMPLE

# Python example of "in" and "not in" Operators

# declare a list and a string

str1 = "Hello world"

list1 = [10, 20, 30, 40, 50]

# Check 'w' (capital exists in the str1 or not

if 'w' in str1:

print "Yes! w found in ", str1

else:

print "No! w does not  found in " , str1

# check 'X' (capital) exists in the str1 or not

if 'X' not in str1:

print "yes! X does not exist in ", str1

else:

print "No!  X exists in ", str1

# check 30 exists in the list1 or not

if 30 in list1:

print "Yes! 30 found in ", list1

else:

print "No! 30 does not found in ", list1

# check 90 exists in the list1 or not

if 90 not in list1:

print "Yes! 90 does not exist in ", list1

else:

print "No! 90 exists in ", list1

Output

    Yes! w found in  Hello world

    yes! X does not exist in  Hello world

    Yes! 30 found in  [10, 20, 30, 40, 50]

    Yes! 90 does not exist in  [10, 20, 30, 40, 50]

Behavior of increment operators in Python

and decrement operators in Python

A coherent and readable language is known to be Python. Unlike in Java, the increment (+ +) and decrement (—) operators do not support python, both in precedence and in return value.

For example, x++ and + + x, or x— or —x, are not valid in Python.

x=1

x++

Output

  File "main.py", line 2

    x++

      ^

SyntaxError: invalid syntax

EXAMPLE

x=1

print(--x)

# 1

print(++x)

# 1

print(x--)

'''

  File "main.py", line 8

    print(x--)

             ^

SyntaxError: invalid syntax

'''

The reasoning for this is that python integers are immutable and can therefore not be modified. So, in order to raise, we would have to do the following.

x = 1

x=x+1

print(x)

x=x-1

print(x)

x +=2

print(x)

x -= 1

print(x)

Output

2

1

3

2

Logical and Bitwise NOT Operators

on Boolean in Python

Not is used for Logical NOT operator in python, and ~ is used for Bitwise NOT. Here, in Python, we'll see their uses and execution.

To reverse the result, the Logical NOT (not) operator returns "False" if the result is "True"; otherwise, "True."

The operator Bitwise NOT (~) is used to invert all the bits, i.e. it returns the number's complement.

Logical NOT (not) operator

PROGRAM

# Logical NOT (not) operator

x = True

y = False

# printing the values

print("x: ", x)

print("y: ", y)

# 'not' operations

print("not x: ", not x)

print("not y: ", not y)

Output:

x:  True

y:  False

not x:  False

not y:  True

Bitwise NOT (~) operator

PROGRAM

# Bitwise NOT (~) operator

x = True

y = False

# printing the values

print("x: ", x)

print("y: ", y)

# '~' operations

print("~ x: ", ~ x)

print("~ y: ", ~ y)

# assigning numbers

x = 123

y = 128

# printing the values

print("x: ", x)

print("y: ", y)

# '~' operations

print("~ x: ", ~ x)

print("~ y: ", ~ y)

Output:

x:  True

y:  False

~ x:  -2

~ y:  -1

x:  123

y:  128

~ x:  -124

~ y:  -129

Logical Operators on String

Logical Operators

Logical AND ( an d )

Logical OR ( o r )

Logical NOT ( no t )

With Strings

An empty string means False as a Boolean value, while True as a Boolean value is a non-empty string.

For "and" operator: If the first operand is true, the second operand is checked and the second operand is returned.

For 'or' operator: If False is the first operand, the second operand is checked and the second operand is returned.

For 'and' operator: If the operand is an empty string, True; False will be returned, otherwise.

EAMPLE 1

# Logical Operators on String in Python

string1 = "Hello"

string2 = "World"

# and operator on string

print("string1 and string2: ", string1 and string2)

print("string2 and string1: ", string2 and string1)

print()

# or operator on string

print("string1 or string2: ", string1 or string2)

print("string2 or string1: ", string2 or string1)

print()

# not operator on string

print("not string1: ", not string1)

print("not string2: ", not string2)

print()

Output:

string1 and string2:  World

string2 and string1:  Hello

string1 or string2:  Hello

string2 or string1:  World

not string1:  False

not string2:  False

EXAMPLE 2

# Logical Operators on String in Python

string1 = "" # empty string

string2 = "World" # non-empty string

# Note: 'repr()' function prints the string with

# single quotes

# and operator on string

print("string1 and string2: ", repr(string1 and string2))

print("string2 and string1: ", repr(string2 and string1))

print()

# or operator on string

print("string1 or string2: ", repr(string1 or string2))

print("string2 or string1: ", repr(string2 or string1))

print()

# not operator on string

print("not string1: ", not string1)

print("not string2: ", not string2)

print()

Output:

string1 and string2:  ''

string2 and string1:  ''

string1 or string2:  'World'

string2 or string1:  'World'

not string1:  True

not string2:  False

if else Conditional Operator

Python also includes the functionality to test conditional statements using the conditional operator, much like other programming languages.

If the other conditional operator is used, depending on the outcome of the given Boolean expression, to evaluate / get either value / statement (from the two values / statements given).

Syntax:

    value1 if expression else value2

Here

Value1-represents the conditional expression value if it is valid.

Expression-represents the condition that a Boolean (i.e. we may assume it is a condition) to evaluate.

Value2-represents the conditional expression value if it is false.

EXAMPLE 1

# find the largest Value

x = 20

y = 10

# if else conditional operator

largest = x if x>y else y

# printing the values

print("x: ", x)

print("y: ", y)

print("largest: ", largest)

print()

x = 10

y = 20

# if else conditional operator

largest = x if x>y else y

# printing the values

print("x: ", x)

print("y: ", y)

print("largest: ", largest)

print()

x = 10

y = 10

# if else conditional operator

largest = x if x>y else y

# printing the values

print("x: ", x)

print("y: ", y)

print("largest: ", largest)

print()

Output:

x:  20

y:  10

largest:  20

x:  10

y:  20

largest:  20

x:  10

y:  10

largest:  10

EXAMPLE 2

# find the largest Value

x = 10

y = 20

z = 30

# if else conditional operator

largest = x if (x>y and x>z) else (y if(y>x and x>z) else z)

# printing the values

print("x: ", x)

print("y: ", y)

print("z: ", z)

print("largest: ", largest)

print()

x = 10

y = 30

z = 20

# if else conditional operator

largest = x if (x>y and x>z) else (y if(y>x and y>z) else z)

# printing the values

print("x: ", x)

print("y: ", y)

print("z: ", z)

print("largest: ", largest)

print()

x = 30

y = 20

z = 10

# if else conditional operator

largest = x if (x>y and x>z) else (y if(y>x and y>z) else z)

# printing the values

print("x: ", x)

print("y: ", y)

print("z: ", z)

print("largest: ", largest)

print()

x = 10

y = 10

z = 10

# if else conditional operator

largest = x if (x>y and x>z) else (y if(y>x and y>z) else z)

# printing the values

print("x: ", x)

print("y: ", y)

print("z: ", z)

print("largest: ", largest)

print()

Output:

x:  10

y:  20

z:  30

largest:  30

x:  10

y:  30

z:  20

largest:  30

x:  30

y:  20

z:  10

largest:  30

x:  10

y:  10

z:  10

largest:  10