SCALA BASICS

AND

PYTHON CODING EXAMPLES

PROGRAMMING FOR BEGINNERS

J KING

SCALA INTRODUCTION

SCALA - SCALABLE LAUNGUAGE

SCALA VS JAVA

PYTHON VS SCALA

SCALA KEYWORDS

SCALA IDENTIFIERS

DATA TYPES IN SCALA

SCOPE OF VARIABLES IN SCALA

SCALA RANGES

SCALA  DECISION MAKING

SCALA LOOPS

PYTHON CODING EXAMPLES

ASCII VALUE OF CHARACTER IN PYTHON

CALCULATE SIMPLE INTEREST

CALCULATE COMPOUND INTEREST

PYTHON PROGRAM TO CHECK THE GIVEN YEAR IS A LEAP YEAR OR NOT

PYTHON | SOME OF THE EXAMPLES OF SIMPLE IF ELSE

CALCULATE DISCOUNT BASED ON THE SALE AMOUNT IN PYTHON

DESIGN A SIMPLE CALCULATOR USING IF ELIF IN PYTHON

BMI (BODY MASS INDEX) CALCULATOR IN PYTHON

WRITE FUNCTIONS TO FIND SQUARE AND CUBE OF A GIVEN NUMBER IN PYTHON

COMPUTE THE NET AMOUNT

CONVERT TEMPERATURE IN PYTHON PROGRAM

PYTHON PROGRAM TO CONVERT METERS INTO YARDS

FIND THE DAY IN PYTHON

PYTHON ARRAY PROGRAMS

CREATE MATRIX IN PYTHON

PYTHON PROGRAM TO CREATE MATRIX USING NUMPY

PYTHON DATE & TIME PROGRAMS

PYTHON CODE TO PRINT TODAY'S YEAR, MONTH AND DAY

PYTHON LISTS

PROGRAM FOR ADDING, REMOVING ELEMENTS IN THE LIST

PROGRAM TO FIND THE DIFFERENCES OF TWO LISTS

PROGRAM TO REMOVE DUPLICATE ELEMENTS FROM THE LIST

CREATE THREE LISTS OF NUMBERS, THEIR SQUARES AND CUBES

ITERATE A LIST IN REVERSE ORDER

PRINT LIST AFTER REMOVING EVEN NUMBERS

PYTHON STRING PROGRAMS

DECLARE, ASSIGN AND PRINT THE STRING (DIFFERENT WAYS)

ACCESS AND PRINT CHARACTERS FROM THE STRING

PROGRAM TO PRINT WORDS WITH THEIR LENGTH OF A STRING

COUNT VOWELS IN A STRING

CREATE MULTIPLE COPIES OF A STRING BY USING MULTIPLICATION OPERATOR

OUR OTHER PUBLISHING

PYTHON AND HADOOP BASICS

PYTHON BASICS AND PYTHON CODING EXAMPLES

C# AND C++ CODING EXAMPLES

PYTHON CODING AND C PROGRAMMING EXAMPLES

C++ AND JAVA CODING EXAMPLES

ANDROID BASICS AND PYTHON CODING EXAMPLES

C# BASICS AND PYTHON CODING EXAMPLES

ANGULAR AND PYTHON BASICS

PYTHON BASICS AND SCALA CODING EXAMPLES

JAVA BASICS AND PYTHON CODING EXAMPLES

PYTHON BASICS AND C# CODING EXAMPLES

ANDROID BASICS AND JAVA CODING EXAMPLES

C# BASICS AND C# CODING EXAMPLES

JAVASCRIPT AND HTML BASICS

HTML AND JAVASCRIPT CODING EXAMPLES

SCALA

BASICS

PROGRAMMING FOR BEGINNERS

J KING

SCALA INTRODUCTION

Scala is a programming language with a general purpose, high-level, multi-paradigm. It is a pure object-oriented programming language which also supports the approach to functional programming. There is no primitive data definition, since everything in Scala is object. Scala programs can convert to bytecodes, and they can run on JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides runtimes for the Javascript. Java and some other programming languages like Lisp, Haskell, Pizza etc are highly influenced by Scala.

Scala Evolution:

Martin Odersky, teacher of programming methods at the École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland, and a German computer scientist, designed Scala. Martin Odersky is also the co-creator of the Funnel programming language for javac (Java Compiler), Universal Java and EPFL. He began designing the Scala back in 2001. Scala was first released publicly as their first version on the Java platform in 2004. Scala was amended for the .Net Framework in June 2004. Later, second version, i.e. (v2.0) was followed in 2006. Scala was awarded as the winner of ScriptBowl contest at the 2012 JavaOne conference. As of June 2012, Scala has not supported the. Net Project. Scala's new update is 2.12.6 which was announced on 27-Apr-2018.

WHY SCALA

Simple to Start: Scala is a language of high level so it is similar to other common programming languages such as Java, C, C++. It therefore is very convenient for someone to learn Scala. Scala is easier for the Java programmers to understand.

Incorporates the best features: Scala incorporates the features of numerous languages such as C, C++, Java etc. making it more functional, versatile and efficient.

Closer integration with Java: The Scala's source code is structured to allow its compiler to understand the Java classes. The compiler can also use modules, Java libraries, and tools and so on. The Scala programs can run on JVM after compilation.

Web-Based & Desktop Application Development: Compiling to JavaScript provides support for web applications. Similarly it can be translated to JVM bytecode for desktop applications.

Big Companies : Many of the big companies like Apple, Facebook, Amazon , Google etc. switch most of their codes from several other languages to Scala. It is very flexible, and can be used in backend operations

As the Scala is syntactically almost close to other commonly used languages, codeing and learning in Scala is simpler. In Scala, programs can be written in any of the widely used text editors, such as Notepad++, gedit etc. or on any of the text editors. Save the file after writing the program with the .sc or.scala extension.

For Windows & Linux: You must have Java Development Kit(JDK) 1.8 or greater installed on your system before installing the Scala on Windows or Linux. As Scala always runs on or above Java 1.8.

We'll discuss how to run the Scala programs on online IDE's in this article.

Example: Hello Geeks has a easy application to print! Using object-focused approach.

// Scala program to print Hello, Geeks!

// by using object-oriented approach

// creating object

object Geeks {

// Main method

def main(args: Array[String])

{

// prints Hello, Geeks!

println("Hello, Geeks!")

}

}

Output:

Hello, Geeks!

Scala - Scalable Launguage

Some factors, ranging from syntax details to component abstraction construct, effect the scalability of a language. The key feature of scala making it flexible is that it is a mix of both object-oriented programming as well as functional. This has strong support for all the programming structures such as high-order functions, optimized tail-call, immutable properties, matching patterns, polymorphism, abstraction, inheritance etc. Scala also includes its own interpreter that can be used to directly execute instructions, without previous compilation. Another main aspect is the parallel library of collections intended to help developers address concurrent programming trends.

Another function is as follows:

Scala is tight. It offers better support for backend activities. Scala programs, similar to Java, tend to be short up to a factor of 10. It stops code turning up over and over again to get any outcome that would strain Java program

Example: In Java, a class with constructor:

class Geek

{

// data members of the class.

String name;

int id;

// contructor would initialized data members

// with the values of passed arguments while

// object of that class created.

Geek(String name, int id)

{

this.name = name;

this.id = id;

}

}

In Scala it’ll be:

class Geek(name: String, id: Int) {}

Example : find the first uppercase letter  In Java

// Function to find string which has

// first character of each word.

static char first(String str)

{

for (int i = 0; i < str.length(); i++)

if (Character.isUpperCase(str.charAt(i)))

return str.charAt(i);

return 0;

}

In scala it will be

val first = str.exists(_.isUpperCase)

Scala vs Java

Java is a general-purpose, concurrent computer programming language, class-based, object-oriented, etc. Java applications are compiled into bytecodes that can run on any virtual Java machine (JVM), independent of the architecture of the program.

Scala is a programming language with a general purpose, high-level, multi-paradigm. It is a pure object-oriented programming language which also follows the approach to functional programming. There is no primitive data definition, since everything in Scala is an entity. It is intended to express the general patterns of programming in a streamlined, succinct, and type-safe way.

SCALA

JAVA

Scala is a mixture of both object oriented and functional programming.

Java is a general purpose object oriented language.

Scala is less readable due to nested code.

Java is more readable.

The process of compiling source code into byte code is slow.

The process of compiling source code into byte code is fast.

Scala support operator overloading.

Java does not support operator overloading.

Scala supports lazy evaluation.

Java does not support lazy evaluation.

Scala is not backward compatible.

Java is backward compatible means the code written in the new version can also run in older version without any error.

Any method or function present is Scala are treated like they are variable.

Java treats functions as an object.

In Scala, the code is written in compact form.

In Java, the code is written in long form.

Scala variables are by default immutable type.

Java variables are by default mutable type.

Scala treated everything as an instance of the class and it is more object oriented language as compare to Java.

Java is less object oriented as compare to Scala due to presence of primitives and statics.

Scala does not contain static keyword.

Java contains static keyword.

In Scala, all the operations on entities are done by using method calls.

In Java, operators are treated differently and is not done with method call.

Python vs Scala

Python is a dynamic programming language of high level, interpreted and general purpose which focuses on readability of code. Python includes fewer programming, offers new libraries, fast prototyping and a range of new features.

Scala is a high level and object-oriented  programming language. The Scala source code is built in such a way that the Java classes are interpreted by its compiler.

PYTHON

SCALA

Python is a dynamically typed language.

Scala is a statically typed language.

We don’t need to specify objects in Python because it is a dynamically typed Object Oriented Programming language.

We need to specify the type of variables and objects in Scala because Scala is statically typed Object Oriented Programming language.

Python is easy to learn and use.

Scala is less difficult to learn than Python.

An extra work is created for the interpreter at the runtime.

No extra work is created in Scala and thus it is 10 times faster than Python.

The data types are decided by it during runtime.

This is not the case in Scala that is why while dealing with large data process, Scala should be considered instead of Python

Python’s Community is huge compared to Scala.

Scala also has good community support. But still, it is lesser than Python.

Python supports heavyweight process forking and doesn’t support proper multithreading.

Scala has reactive cores and a list of asynchronous libraries and hence Scala is a better choice for implementing concurrency.

Its methodologies are much complex in Python as it is dynamic programming language.

Testing is much better in scala because it is a statically typed language.

It is popular because of its English-like syntax.

For scalable and concurrent systems, Scala play much bigger.

Python is easy for the developers to write code in it.

Scala is less difficult to learn than Python and it is difficult to write code in Scala.

There is an interface in Python to many OS system calls and libraries. It has many interpreters

It is basically a compiled language and all source codes are compiled before execution

Python language is highly prone to bugs whenever there is any change to the existing code.

No such problem is seen in Scala.

Python has libraries for Machine learning and proper data science tools and Natural Language Processing (NLP).

Where as Scala has no such tools.

Python can be used for small-scale projects.

Scala can be used for large-scale projects.

It doesn’t provide scalable feature support.

It provides scalable feature support.

Scala Keywords

Keywords or Reserved words are the words used by any internal method or represent any predefined actions in a language. Therefore, it is not permitted to use such terms as variable names or objects. This may result in an error in compile-time.

EXAMPLE

// Scala Program to illustrate the keywords

// Here object, def, and var are valid keywords

object Main

{

def main(args: Array[String])

{

var p = 10

var q = 30

var sum = p + q

println("The sum of p and q is :"+sum);

}

}

Output:

The sum of p and q is :40

SCALA KEYWORDS

EXAMPLE

// Scala Program to illustrate the keywords

// Here class keyword is used to create a new class

// def keyword is used to create Function

// var keyword is used to create a variable

class GFG

{

var name = "Tamsel"

var age = 20

var branch = "Computer Science"

def show()

{

println("Hello! my name is " + name + "and my age is"+age);

println("My branch name is " + branch);

}

}

// object keyword is used to define

// an object new keyword is used to

// create an object of the given class

object Main

{

def main(args: Array[String])

{

var ob = new GFG();

ob.show();

}

}

Output:

Hello! my name is Tamseland my age is20

My branch name is Computer Science

Scala Identifiers

Identifiers are used for identification purposes in programming languages. In Scala, a class name, method name, variable name or object name can be used.

EXAMPLE

class GFG{

var a: Int = 20

}

object Main {

def main(args: Array[String]) {

var ob = new GFG();

}

}

In above example

- GFG:  Class name

- a:  Variable name

- Main:  Object name

- main:  Method name

- args:  Variable name

- ob:  Object name

Idenfiers are there

There are some rules to define a valid Scala ID. These rules should be observed, otherwise a compile-time error will occur.

- Scala IDs are case-sensitive.

- You can't use Scala's keyword as an identifier.

- Words reserved can not be used as an identifier such as $etc.

- Scala only permitted identifiers that were created using four identification types below.

- The length of the identifier is not limited, but only an optimum length of 4 – 15 letters is advisable.

- Digits should not be used to start Identifiers([0-9]). For instance, "123geeks" is a not valid Scala ID.

EXAMPLE

// Scala program to demonstrate

// Identifiers

object Main

{

// Main method

def main(args: Array[String])

{

// Valid Identifiers

var `name` = "Siya";

var _age = 20;

var Branch = "Computer Science";

println("Name:" +`name`);

println("Age:" +_age);

println("Branch:" +Branch);

}

}

Output:

Name:Siya

Age:20

Branch:Computer Science

Types of Scala identifiers

Alphanumeric Identifiers: These are those identifiers starting from a letter (capital or letter) or an underscore followed by letters, digits, or underscores.

EXAMPLE FOR Alphanumaeric Identifiers

_GFG, geeks123, _1_Gee_23, Geeks

EXAMPLE

// Scala program to demonstrate

// Alphanumeric Identifiers

object Main

{

// Main method

def main(args: Array[String])

{

// main, _name1, and Tuto_rial are

// valid alphanumeric identifiers

var _name1: String = "ScalaforGeeks"

var Tuto_rial: String = "Scala"

println(_name1);

println(Tuto_rial);

}

}

Output:

ScalaforGeeks

Scala

Operator Identifiers : those identifiers that include one or more operator characters such as +,:,? , ~, # or so on.

// Scala program to demonstrate

// Operator Identifiers

object Main

{

// Main method

def main(args: Array[String])

{

// main, x, y, and sum are valid

// alphanumeric identifiers

var x:Int = 20;

var y:Int = 10;

// Here, + is a operator identifer

// which is used to add two values

var sum = x + y;

println("Display the result of + identifier:");

println(sum);

}

}

Output:

Display the result of + identifier:

30

Mixed Identifiers: These are those that contain alphanumeric and operator-identified identifiers.

EXAMPLE

// Scala program to demonstrate

// Mixed Identifiers

object Main

{

// Main method

def main(args: Array[String])

{

// num_+ is a valid mixed identifier

var num_+ = 20;

println("Display the result of mixed identifier:");

println(num_+);

}

}

Literal identification: These are identifiers in which an arbitrary string with back ticks ('...') is attached.

EXAMPLE

// Scala program to demonstrate

// Literal Identifiers

object Main

{

// Main method

def main(args: Array[String])

{

// `name` and `age` are valid literal identifiers

var `name` = "Siya"

var `age` = 20

println("Name:" +`name`);

println("Age:" +`age`);

}

}

Output:

Name:Siya

Age:20

Data Types in Scala

A data type is a data categorization that tells the compiler what type of value a variable has. For instance, if a variable has an int data type, it has a numeric value. In Scala, the data types in terms of length and storage are similar to Java. Data types are treated with the same objects in Scala so that the first letter of the data type is in a capital letter.

The data types available in Scala as shown in the table below:

DATATYPE

DEFAULT VALUE

DESCRIPTION

Boolean

False

True or False

Byte

0

8 bit signed value. Range:-128 to 127

Short

0

16 bit signed value. Range:-2 15  to 2 15 -1

Char

‘\u000’

16 bit unsigned unicode character. Range:0 to 2 16 -1

Int

0

32 bit signed value. Range:-2 31  to 2 31 -1

Long

0L

64 bit signed value. Range:-2 63  to 2 63 -1

Float

0.0F

32 bit IEEE 754 single-Precision float

Double

0.0D

64 bit IEEE 754 double-Precision float

String

null

A sequence of character

Unit

–

Coinsides to no value.

Nothing

–

It is a subtype of every other type and it contains no value.

Any

–

It is a supertype of all other types

AnyVal

–

It serve as value types.

AnyRef

–

It serves as reference types.

EXAMPLE

// Scala program to illustrate Datatypes

object Test

{

def main(args: Array[String])

{

var a: Boolean = true

var a1: Byte = 126

var a2: Float = 2.45673f

var a3: Int = 3

var a4: Short = 45

var a5: Double = 2.93846523

var a6: Char = 'A'

if (a == true)

{

println("boolean:scalaforgeeks")

}

println("byte:" + a1)

println("float:" + a2)

println("integer:" + a3)

println("short:" + a4)

println("double:" + a5)

println("char:" + a6)

}

}

Output:

boolean:scalaforgeeks

byte:126

float:2.45673

integer:3

short:45

double:2.93846523

char:A

Variables are simply the location for the storage. Each variable is known by name, and some known and unknown piece of information known as value is stored.

A data type is responsible for allocating memory to the variable, so one can define a variable by its data type and name.

There are two types of variable within Scala:

- Mutable Variables

- Immutable Variables

Let's get detailed understanding of each of these variables.

Mutable Variable:

These variables are those variables that allow us to change a value after a variable is declared.

The var keyword is used to define mutable variables.

The first letter of type of data should be in capital letter because it is treated as objects in the Scala data type.

Syntax:

var Variable_name: Data_type = "value";

For Example:

var name: String = "scalaforgeeks";

Immutable Variable:

These variables are the variables that do not allow you to change a value after a variable has been declared.

Immutable variables are defined using the val keyword.

The first letter should be in capital letter because it is treated as objects within the Scala data type.

Syntax:

val Variable_name: Data_type =  "value";

For Example:

val name: String = "scalaforgeeks";

In Scala Rules for naming variable

The name of the variable can include letter, digit, and two special characters Underscore (_) and Dollar($).

White space in name variable is not allowed.

The name of the variable must not contain the word reserved or the keyword.

An alphabet should be the starting letter for the variable name.

Scope of Variables In Scala

Scala variable has three types of scope.

- Fields.

- Method Parameters.

- Local Variables.

Fields

We can access such variables from any method in the object & from outside the object if we declare them with the correct access modifiers.

A field may be mutable or immutable, they may define them using 'var' or 'val.'

EXAMPLE

// Scala program of field

// scope for Scala variable

// class created with field

// variables x and y.

class disp

{

var x = 10.3f

var y = 7f

def windet()

{

println("Value of x : "+x)

}

println("Value of y : "+y);

}

object Example

{

// Main method

def main(args:Array[String])

{

val Example = new disp()

Example.windet()

}

}

Output:

Value of y : 7.0

Value of x : 10.3

Method Parameters

When we call it we use these variables if we want to pass a value inside the method.

If there is a reference to the object from outside the method, they can be accessed both inside the method and outside.

Those variables are always mutable Using the keyword 'val.'

EXAMPLE

// Scala program of Method

// scope for Scala variable

// class created with Method

// variables s1 and s2.

class rect

{

def mult(s1: Int, s2: Int)

{

var result = s1 * s2

println("Area is: " + result);

}

}

object Area

{

// Main method

def main(args:Array[String])

{

val su = new rect()

su.mult(5, 10)

}

}

Output:

Area is: 50

Local Variables

These variables are declared within a method and are only accessible within it.

These variables both mutable and immutable using keywords 'var' & 'val.'

EXAMPLE

// Scala program of Method

// scope for Scala variable

// class created with Local

// variables s1 and s2.

class Area

{

def mult()

{

var(s1, s2) = (3, 80);

var s = s1 * s2;

println("Area is: " + s)

}

}

object Test

{

// Main method

def main(args:Array[String])

{

val ex = new Area()

ex.mult()

}

}

Output:

Area is: 240

Scala Ranges

The Scala Range can be defined as an organized series of uniformly divided integers.

It is helpful to provide more strength with fewer methods so operations done here are very fast.

The ranges can be used for iteration loops.

It can be obtained through certain predefined methods, namely until, by, and to.

Three constants are defined, i.e. (start, end, and increment value).

Syntax:

val range = Range(x, y, z)

EXAMPLE

// Scala program for Ranges

// Creating object

object GFG

{

// Main method

def main(args: Array[String])

{

// applying range method

val x = Range(3, 10, 1)

// Displays given range

println(x)

// Displays starting value

// of the given range

println(x(0))

// Displays last value

// of the given range

println(x.last)

}

}

OUTPUT

Range(3, 4, 5, 6, 7, 8, 9)

3

9

Ranges - Operations performed

If we want a range that includes the end value, we can also use the method ‘ until’ , both methods ( until and Range ) are used for the same purpose.

EXAMPLE

// Scala program for Ranges

// Creating object

object GFG

{

// Main method

def main(args: Array[String])

{

// applying range method

val x = Range(0, 10, 2)

// applying until method

val y = 0 until 10 by 2

// Displays true if both the

// methods are equivalent

println(x == y)

}

}

Output:

True

The Range ‘ upper bound’ may be made inclusive.

EXAMPLE

// Scala program for Ranges

// Creating object

object GFG

{

// Main method

def main(args: Array[String])

{

// applying range method

val x = Range(1, 8)

// Including upper bound

val y = x.inclusive

// Displays all the elements

// of the range

println(y)

}

}

Output:

Range(1, 2, 3, 4, 5, 6, 7, 8)

Inclusive is used here to include the upper bound of the Range.

If need range of integer values,

use the   t o  method ( both to and inclusive Ranges are equivalent).

EXAMPLE

// Scala program for Ranges

// Creating object

object GFG

{

// Main method

def main(args: Array[String])

{

// applying range method

val x = Range(1, 8)

// Including upper bound

val y = x.inclusive

// applying 'to' method

val z = 1 to 8

// Displays true if both the

// methods are equal

println(y == z)

}

}

Output:

True

Scala Decision Making

(if, if-else, Nested if-else, if-else if)

programming decision-making is similar to real-life decision-making.

When the given condition is met, a piece of code is executed in decision making.

These are also sometimes referred to as the Control Flow statements.

Scala uses control statements to control the program's execution flow according to certain conditions.

These are used to advance and branch the execution flow, based on changes to a program's state.

The conditional statements

if

if-else

Nested if-else

if-else if ladder

if statement

"If" statements are the simplest statements of decision making amongst all statements of decision making.

In this statement, the code block will only be executed when the given condition is true and, if the condition is false then that code block will not be executed.

Syntax:

if(condition)

{

// Code to be executed

}

FLOW CHART

EXAMPLE

// Scala program to illustrate the if statement

object Test {

// Main Method

def main(args: Array[String]) {

// taking a variable

var a: Int = 50

if (a > 30)

{

// This statement will execute as a > 30

println("ScalaforGeeks")

}

}

}

Output:

ScalaforGeeks

if-else statement

The if statement alone tells us that it will execute a block of statements if a condition is true and if the condition is false it won't.

But what if we want to do something different, if the condition is wrong.

Here comes else statement.

When the condition is wrong, we can use the else statement with if statement to execute a block of code.

Syntax:

if (condition)

{

// Executes this block if

// condition is true

}

else

{

// Executes this block if

// condition is false

}

FLOW CHART

EXAMPLE

// Scala program to illustrate the if-else statement

object Test {

// Main Method

def main(args: Array[String]) {

// taking a variable

var a: Int = 650

if (a > 698)

{

// This statement will not

// execute as a > 698 is false

println("ScalaorGeeks")

}

else

{

// This statement will execute

println("Sudo Placement")

}

}

}

OUTPUT

Sudo Placement

Nested if-else statement

A nested if an if statement is the target of a different if-else statement.

Nested if-else statement refers to an if-else statement within an if statement or in a else statement.

Scala lets us nest if-else statements into if-else statements.

Syntax:

// Executes when condition_1 is true

if (condition_1)

{

if (condition_2)

{

// Executes when condition_2 is true

}

else

{

// Executes when condition_2 is false

}

}

// Executes when condition_1 is false

else

{

if (condition_3)

{

// Executes when condition_3 is true

}

else

{

// Executes when condition_3 is false

}

}

FLOW CHART

EXAMPLE

// Scala program to illustrate

// the nested if-else statement

object Test {

// Main Method

def main(args: Array[String]) {

// taking three variables

var a: Int = 70

var b: Int = 40

var c: Int = 100

// condition_1

if (a > b)

{

// condition_2

if(a > c)

{

println("a is largest");

}

else

{

println("c is largest")

}

}

else

{

// condition_3

if(b > c)

{

println("b is largest")

}

else

{

println("c is largest")

}

}

}

}

Output:

c is largest

if-else if Ladder

Here a user can choose between multiple options.

The if declarations are executed from top down.

As soon as one of the conditions controlling the if is true;

Then the statement associated with that ‘if’ it is executed, and it bypasses  the rest of the ladder.

If none of the conditions are true, then the final other declaration will be executed.

Syntax:

if(condition_1)

{

// this block will execute

// when condition_1 is true

}

else if(condition_2)

{

// this block will execute

// when condition2 is true

}

.

.

.

else

{

// this block will execute when none

// of the condition is true

}

FLOW CHART

EXAMPLE

// Scala program to illustrate

// the if-else-if ladder

object Test {

// Main Method

def main(args: Array[String]) {

// Taking a variable

var value: Int = 50

if (value == 20)

{

// print "value is 20" when

// above condition is true

println("Value is 20")

}

else if (value == 25)

{

// print "value is 25" when

// above condition is true

println("Value is 25")

}

else if (value == 40)

{

// print "value is 40" when

// above condition is true

println("Value is 40")

}

else

{

// print "No Match Found"

// when all condition is false

println("No Match Found")

}

}

}

OUTPUT

No Match Found

SCALA LOOPS

Looping into programming languages is a feature that facilitates repeatedly executing a set of instructions / functions while some condition evaluates to true.

Loops make task simpler for the programmers.

Scala provides the various loop types for dealing with the condition-based situation in the program.

In Scala the loops are:

- while Loop

- do..while Loop

- for Loop

- Nested Loops

WHILE LOOP

A while loop usually takes a condition in parenthesis.

If the condition is True, the code will be executed within the while loop 's body.

A while loop is used when we don't know how many times we want the loop to be executed but we do know the loop termination condition.

It is also known as a loop controlled by entry, as the condition is checked before the loop is executed.

The while loop can be considered a repeat in if statement.

Syntax:

while (condition)

{

// Code to be executed

}

FLOW CHART

EXAMPLE

// Scala program to illustrate while loop

object whileLoopDemo

{

// Main method

def main(args: Array[String])

{

var x = 1;

// Exit when x becomes greater than 4

while (x <= 4)

{

println("Value of x: " + x);

// Increment the value of x for

// next iteration

x = x + 1;

}

}

}

Output:

Value of x: 1

Value of x: 2

Value of x: 3

Value of x: 4

do..while Loop

A do .. while a loop is nearly the same as a ‘while loop’.

The only difference is that do .. when loop is running at least once.

After first execution the condition is checked. When we want the loop to run at least once, we use a do .. while loop.

It is also known as the exit loop controlled, as the condition is checked after the loop has been executed.

Syntax:

do {

// statements to be Executed

} while(condition);

FLOW CHART

EXAMPLE

// Scala program to illustrate do..while loop

object dowhileLoopDemo

{

// Main method

def main(args: Array[String])

{

var a = 10;

// using do..while loop

do

{

print(a + " ");

a = a - 1;

}while(a > 0);

}

}

Output:

10 9 8 7 6 5 4 3 2 1

For loop

For Loop - similar functionality as while loop

But different syntax.

It's basically a repetition control structure that allows the programmer to write a loop that has to execute a certain number of times.

EXAMPLE

// Scala program to illustrate for loop

object forloopDemo {

// Main Method

def main(args: Array[String]) {

var y = 0;

// for loop execution with range

for(y <- 1 to 7)

{

println("Value of y is: " + y);

}

}

}

Output:

Value of y is: 1

Value of y is: 2

Value of y is: 3

Value of y is: 4

Value of y is: 5

Value of y is: 6

Value of y is: 7

Nested Loops

The loop inside a loop which contains a loop is known as the nested loop.

It may contain a while loop inside a while loop or

The for loop inside a for loop

A while loop may also contain the for loop and vice-versa.

EXAMPLE

// Scala program to illustrate nested loop

object nestedLoopDemo {

// Main Method

def main(args: Array[String]) {

var a = 5;

var b = 0;

// outer while loop

while (a < 7)

{

b = 0;

// inner while loop

while (b < 7 )

{

// printing the values of a and b

println("Value of a = " +a, " b = "+b);

b = b + 1;

}

// new line

println()

// incrementing the value of a

a = a + 1;

// dispalying the updated value of a

println("Value of a Become: "+a);

// new line

println()

}

}

}

OUTPUT

(Value of a = 5, b = 0)

(Value of a = 5, b = 1)

(Value of a = 5, b = 2)

(Value of a = 5, b = 3)

(Value of a = 5, b = 4)

(Value of a = 5, b = 5)

(Value of a = 5, b = 6)

Value of a Become: 6

(Value of a = 6, b = 0)

(Value of a = 6, b = 1)

(Value of a = 6, b = 2)

(Value of a = 6, b = 3)

(Value of a = 6, b = 4)

(Value of a = 6, b = 5)

(Value of a = 6, b = 6)

Value of a Become: 7

PYTHON CODING EXAMPLES

PROGRAMMING FOR BEGINNERS

J KING

PYTHON CODING EXAMPLES

ASCII value of character in Python

In python, we use the function ord() to obtain an ASCII code of a character. Ord() accepts a character, returns its ASCII value.

Syntax:

ord(character);

Example:

Input:

char_var = 'A'

Function call:

ord(char_var)

Output:

65

Code to find ASCII value of a character

# python program to print ASCII

# value of a given character

# Assigning character to a variable

char_var = 'A'

# printing ASCII code

print("ASCII value of " + char_var + " is = ", ord(char_var))

char_var = 'x'

# printing ASCII code

print("ASCII value of " + char_var + " is = ", ord(char_var))

char_var = '9'

# printing ASCII code

print("ASCII value of " + char_var + " is = ", ord(char_var))

Output

ASCII value of A is =  65

ASCII value of x is =  120

ASCII value of 9 is =  57

Calculate simple interest

We use the following formula to calculate simple interest,

(P * R * T) / 100

Where,

- P  – Principle amount

- R  – Rate of the interest, and

- T  – Time in the years

Example:

Input:

p = 250000

r = 36

t = 1

# formula

si = (p*r*t)/100

print(si)

Output:

90000

Python program for simple interest

# Python program to find simple interest

p = float(input("Enter the principle amount : "))

r = float(input("Enter the rate of interest : "))

t = float(input("Enter the time in the years: "))

# calculating simple interest

si = (p*r*t)/100

# printing the values

print("Principle amount: ", p)

print("Interest rate   : ", r)

print("Time in years   : ", t)

print("Simple Interest : ", si)

Output

First run:

Enter the principle amount : 10000

Enter the rate of interest : 3.5

Enter the time in the years: 1

Principle amount:  10000.0

Interest rate   :  3.5

Time in years   :  1.0

Simple Interest :  350.0

Second run:

Enter the principle amount : 250000

Enter the rate of interest : 36

Enter the time in the years: 1

Principle amount:  250000.0

Interest rate   :  36.0

Time in years   :  1.0

Simple Interest :  90000.0

Calculate compound interest

We use the equation below to calculate compound interest

P(1 + R / 100) T

Where,

P  – Principle amount

R  – Rate of the interest, and

T  – Time in the years

Example:

Input:

p = 250000

r = 36

t = 1

# formula

ci =  p * (pow((1 + r / 100), t))

print(ci)

Output:

339999.99999999994

Python program

# Python program to find compound interest

p = float(input("Enter the principle amount : "))

r = float(input("Enter the rate of interest : "))

t = float(input("Enter the time in the years: "))

# calculating compound interest

ci =  p * (pow((1 + r / 100), t))

# printing the values

print("Principle amount  : ", p)

print("Interest rate     : ", r)

print("Time in years     : ", t)

print("compound Interest : ", ci)

Output

First run:

Enter the principle amount : 10000

Enter the rate of interest : 3.5

Enter the time in the years: 1

Principle amount  :  10000.0

Interest rate     :  3.5

Time in years     :  1.0

compound Interest :  10350.0

Second run:

Enter the principle amount : 250000

Enter the rate of interest : 36

Enter the time in the years: 1

Principle amount  :  250000.0

Interest rate     :  36.0

Time in years     :  1.0

compound Interest :  339999.99999999994

Python program to check the given year is a leap year or not

A leap year is a year that can be divided by 4, except for the century year (a year that ends with 00). A year of a century is a leap year if it is divisible by 400. Here, the user presents a year, and we will test if the year in question is a leap year or not. We can solve this problem in two ways first by using the calendar module, and second by simply checking the state of the leap year.

1) By using the calendar module

Initially we learn a little about the calendar module before we go to solve the problem. Calendar module is built into Python which provides us with various functions to solve the date, month and year related problem.

PROGRAM

# importing the module

import calendar

# input the year

year=int(input('Enter the value of year: '))

leap_year=calendar.isleap(year)

# checking leap year

if leap_year: # to check condition

print('The given year is a leap year.')

else:

print('The given year is a non-leap year.')

Output

RUN 1:

Enter the value of year: 2020

The given year is a leap year.

RUN 2:

Enter the value of year: 2021

The given year is a non-leap year.

2) By simply checking method

As we know it is a leap year, or not, to test the year in question. So, we'll introduce the condition here and try to write the Python programme.

Program

# input the year

y=int(input('Enter the value of year: '))

# To check for non century year

if y%400==0 or y%4==0 and y%100!=0:

print('The given year is a leap year.')

else:

print('The given year is a non-leap year.')

Output

RUN 1:

Enter the value of year: 2020

The given year is a leap year.

RUN 2:

Enter the value of year: 2000

The given year is a leap year.

Python | Some of the examples of simple if else

Example1: Enter a number and check whether it is 10 or not

a=int(input("Enter A : "))

if a==10:

print("Equal to 10")

else:

print("Not Equal to 10")

Output

Enter A : 10

Equal to 10

Example2: Find which is largest of two numbers

a=int(input("Enter A: "))

b=int(input("Enter B: "))

if a>b:

g=a

else:

g=b

print("Greater = ",g)

Output

Enter A: 36

Enter B: 24

Greater =  36

Example3: Find which is largest of two numbers using single statement

a=int(input("Enter A: "))

b=int(input("Enter B: "))

c= a if a>b else b

print("Greater = ",c)

Output

Enter A: 24

Enter B: 36

Greater =  36

Calculate discount based on the sale amount in Python

The discount rates are:

Amount          Discount

0-5000          5%

5000-15000      12%

15000-25000     20%

above 25000     30%

Program:

# input sale amount

amt = int(input("Enter Sale Amount: "))

# checking conditions and calculating discount

if(amt>0):

if amt<=5000:

disc = amt*0.05

elif amt<=15000:

disc=amt*0.12

elif amt<=25000:

disc=0.2 * amt

else:

disc=0.3 * amt

print("Discount : ",disc)

print("Net Pay  : ",amt-disc)

else:

print("Invalid Amount")

Output

Enter Sale Amount: 30000

Discount :  9000.0

Net Pay  :  21000.0

Design a simple calculator using if elif in Python

Given two numbers, and we will build a calculator-type program that will use Python to add, subtract, multiply and divide operations.

Example:

Message:

Calculator

1.Add

2.Substract

3.Multiply

4.Divide

Input:

Enter Choice(1-4): 3

Enter A:10

Enter B:20

Output:

Product =  200

Program

# menus

print("Calculator")

print("1.Add")

print("2.Substract")

print("3.Multiply")

print("4.Divide")

# input choice

ch=int(input("Enter Choice(1-4): "))

if ch==1:

a=int(input("Enter A:"))

b=int(input("Enter B:"))

c=a+b

print("Sum = ",c)

elif ch==2:

a=int(input("Enter A:"))

b=int(input("Enter B:"))

c=a-b

print("Difference = ",c)

elif  ch==3:

a=int(input("Enter A:"))

b=int(input("Enter B:"))

c=a*b

print("Product = ",c)

elif ch==4:

a=int(input("Enter A:"))

b=int(input("Enter B:"))

c=a/b

print("Quotient = ",c)

else:

print("Invalid Choice")

Output

Calculator

1.Add

2.Substract

3.Multiply

4.Divide

Enter Choice(1-4): 3

Enter A:10

Enter B:20

Product =  200

BMI (Body Mass Index) calculator in Python

Example:

Input:

Height = 1.75

Weigth = 64

Output:

BMI is: 20.89 and you are: Healthy

Program

# getting input from the user and assigning it to user

height = float(input("Enter height in meters: "))

weight = float(input("Enter weight in kg: "))

# the formula for calculating bmi

bmi = weight/(height**2)

# ** is the power of operator i.e height*height in this case

print("Your BMI is: {0} and you are: ".format(bmi), end='')

#conditions

if ( bmi < 16):

print("severely underweight")

elif ( bmi >= 16 and bmi < 18.5):

print("underweight")

elif ( bmi >= 18.5 and bmi < 25):

print("Healthy")

elif ( bmi >= 25 and bmi < 30):

print("overweight")

elif ( bmi >=30):

print("severely overweight")

Output

Enter height in meters: 1.75

Enter weight in kg: 64

You'r BMI is 28.8979s9183673468 and you are: Healthy

Write functions to find square and cube of a given number in Python

Example:

Input:

Enter an integer number: 6

Output:

Square of 6 is 36

Cube of 6 is 216

Function to get square:

def   square ( num ):

return ( num * num )

Function to get cube:

def   cube ( num ):

return ( num * num * num )

Program

# python program to find square and cube

# of a given number

# User defind method to find square

def square (num):

return  (num*num)

# User defind method to find cube

def cube (num) :

return  (num*num*num)

# Main code

# input a number

number = int (raw_input("Enter an integer number: "))

# square and cube

print "square of {0} is {1}".format(number, square(number))

print "Cube of {0} is {1}".format(number, cube (number))

Output

Enter an integer number: 6

square of 6 is 36

Cube of 6 is 216

Compute the net amount

Of a bank account based on the transactions

Example:

Input:

Enter transactions: D 10000

Want to continue (Y for yes): Y

Enter transaction: W 5000

Want to continue (Y for yes): Y

Enter transaction: D 2000

Want to continue (Y for yes): Y

Enter transaction: W 100

Want to continue (Y for yes): N

Output:

Net amount: 6900

Program

# computes net bank amount based on the input

# "D" for deposit, "W" for withdrawal

# define a variable for main amount

net_amount = 0

while True:

# input the transaction

str = raw_input ("Enter transaction: ")

# get the value type and amount to the list

# seprated by space

transaction = str.split(" ")

# get the value of transaction type and amount

# in the separated variables

type = transaction [0]

amount = int (transaction [1])

if type=="D" or type=="d":

net_amount += amount

elif type=="W" or type=="w":

net_amount -= amount

else:

pass

#input choice

str = raw_input ("want to continue (Y for yes) : ")

if not (str[0] =="Y" or str[0] =="y") :

# break the loop

break

# print the net amount

print "Net amount: ", net_amount

Output

Enter transaction: D 10000

want to continue (Y for yes) : Y

Enter transaction: W 5000

want to continue (Y for yes) : Y

Enter transaction: D 2000

want to continue (Y for yes) : Y

Enter transaction: W 100

want to continue (Y for yes) : N

Net amount:  6900

Convert temperature in Python program

From Celsius to Fahrenheit and vice-versa

Formula used:

Celsius to Fahrenheit:  °C= (5/9)*(°F-32)

Fahrenheit to Celsius:  °F= (9/5)*(°C) + 32

Program

# Define a function to convert

# celsius temperature to Fahrenheit

def Celsius_to_Fahrenheit(c) :

f = (9/5)*c + 32

return f

# Define a function to convert

# Fahrenheit temperature to Celsius

def Fahrenheit_to_Celsius(f) :

c = (5/9)*(f - 32)

return c

# Driver Code

if __name__ == "__main__" :

c = 36

print(c, "degree celsius is equal to:",Celsius_to_Fahrenheit(c),"Fahrenheit")

f = 98

print(f,"Fahrenheit is equal to:",Fahrenheit_to_Celsius(f),"degree celsius")

Output

36 degree celsius is equal to: 96.8 Fahrenheit

98 Fahrenheit is equal to: 36.66666666666667 degree Celsius

Python program to convert meters into yards

Key:  1 meter = 1.094 yards

Example:

Input:

Meters: 245

Output:

Yards: 268.03000000000003

Python code to convert Meters to yards

# Python program to convert Centimeter to Inches

# taking input

num = float(input("Enter the distance measured in centimeter : "))

# converting from cms to inches

""" 1 inch = 2.54 centimeters"""

inc = num/2.54

# printing the result

print("Distance in inch : ", inc)

Output

First run:

Enter the distance measured in meters : 245

Distance in yards :  268.03000000000003

Second run:

Enter the distance measured in meters : 54

Distance in yards :  59.07600000000001

Third run:

Enter the distance measured in meters : 100

Distance in yards :  109.4

Find the day in Python

In this question, the user will provide a particular date which could be from the past or the future and we need to locate the weekday.

To this end, we'll use the calendar module that provides us with various functions to solve the date, month and year related problem.

Until we go to find a specific date's weekday, we must test if the date given is correct or not.

If the date given is not correct then we get some mistake.

So we will use the try-except statement to resolve this form of mistake.

Syntax of try-except statement:

try:

#statement

except error_types:

#statement

Program

# importing the module

import calendar

d,m,y=map(int,input('Enter the value of date,month and year: ').split())

a=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

try:

s=calendar.weekday(y,m,d)

print('Weekday:',a[s])

except ValueError:

print('You have entered an invalid date.')

Output

RUN 1:

Enter the value of date, month and year: 28 10 2019

Weekday: Monday

RUN 2:

Enter the value of date, month and year: 32 10 2019

You have entered an invalid date.

Python array programs

Create matrix in Python

Consider the below example,

mat = [

[10, 20, 30],

[40, 50, 60],

[70, 80, 80]

]

It can be considered a 3x3 matrix,

There are 3 rows and 3 columns in ' mat '  matrix.

Program

# Python matrix creation

mat = [

[10, 20, 30],

[40, 50, 60],

[70, 80, 80]

]

# printing the matrix

print("mat: ", mat)

# printing rows

print("mat[0]: ", mat[0])

print("mat[1]: ", mat[1])

print("mat[2]: ", mat[2])

# printing specific elements

print("mat[0][0]: ", mat[0][0])

print("mat[0][1]: ", mat[0][1])

print("mat[0][2]: ", mat[0][2])

print("mat[1][0]: ", mat[1][0])

print("mat[1][1]: ", mat[1][1])

print("mat[1][2]: ", mat[1][2])

print("mat[2][0]: ", mat[2][0])

print("mat[2][1]: ", mat[2][1])

print("mat[2][2]: ", mat[2][2])

# printing matrix using loop (matrix form)

print("Matrix is: ")

for i in range(3):

for j in range(3):

print(mat[i][j], end = " ")

print() # prints new line

Output

mat:  [[10, 20, 30], [40, 50, 60], [70, 80, 80]]

mat[0]:  [10, 20, 30]

mat[1]:  [40, 50, 60]

mat[2]:  [70, 80, 80]

mat[0][0]:  10

mat[0][1]:  20

mat[0][2]:  30

mat[1][0]:  40

mat[1][1]:  50

mat[1][2]:  60

mat[2][0]:  70

mat[2][1]:  80

mat[2][2]:  80

Matrix is:

10 20 30

40 50 60

70 80 80

Python program to create matrix using numpy

Using numpy.array()

mat = numpy . array ([[ 10 , 20 , 30 ],[ 40 , 50 , 60 ],[ 70 , 70 , 90 ]])

Using numpy.matrix()

mat = numpy . matrix ( "10 20 30; 40 50 60; 70 80 90" )

Program

# Python matrix creation using numpy

# importing the numpy

import numpy as np

# creating matrix using numpy.array()

mat1 = np.array([[10,20,30],[40,50,60],[70,70,90]])

# printing matrix

print("mat1...")

print(mat1)

# creating matrix using numpy.matrix()

mat2 = np.matrix("10 20 30; 40 50 60; 70 80 90")

# printing matrix

print("mat2...")

print(mat2)

Output

mat1...

[[10 20 30]

[40 50 60]

[70 70 90]]

mat2...

[[10 20 30]

[40 50 60]

[70 80 90]]

Python Date & Time Programs

Python program to print current hour, minute, second and microsecond

Steps:

Import the  datetime  class, from “ datetime  module”

Create an object by -

calling the  now()  function of  datetime  class

Extract and print the current hour, minute, second and microsecond using the object of  datetime.now() .

Program

# Python program to print current hour,

# minute, second and microsecond

# importing the datetime class from

# datetime module

from datetime import datetime

# creating object

obj_now = datetime.now()

# printing the current date and time

print("Current date & time: ", obj_now)

# extracting and printing the current

# hour, minute, second and microsecond

print("Current hour =", obj_now.hour)

print("Current minute =", obj_now.minute)

print("Current second =", obj_now.second)

print("Current microsecond =", obj_now.microsecond)

OUTPUT

Current date & time:  2020-07-30 14:43:52.294475

Current hour = 14

Current minute = 43

Current second = 52

Current microsecond = 294475

Python code to print today's year, month and day

In the example below – a python program is being implemented to print the current / current year, month and year.

CODE

# Python program to

# print today's year, month and day

# importing the date class datetime module

from datetime import date

# creating the date object of today's date

current_date = date.today()

# printing the current date

print("Current date: ", current_date)

# extracting the current year, month and day

print("Current year:", current_date.year)

print("Current month:", current_date.month)

print("Current day:", current_date.day)

OUTPUT

Current date:  2020-07-30

Current year: 2020

Current month: 7

Current day: 30

>

Python Lists

Program for Adding, removing elements in the list

Python List append() Method

It is used to add / append an item to the list (that will be passed as a parameter in method).

Syntax:

list.append(element)

Here,

List-is a list name.

Append()-is the name of the method which is used to add element / object to the list.

Item-is an element to be added to the list (which is known as an object or item).

Python List pop() Method

Using this to remove / pop an item from the list

Syntax:

list.pop()

Here,

List  - is the list name.

Pop()  - is the name of the method used to delete last item from the list.

PROGRAM

# Declaring a list with integer and string elements

list = [10, 20, 30, "New Delhi", "Mumbai"]

# printing list

print "List elements are: ", list

# adding elements

list.append (40)

list.append (50)

list.append ("Chennai")

# printing list after adding elements

print "List elements: ", list

# removing elements

list.pop () ;

# printing list

print "List elements: ", list

# removing elements

list.pop () ;

# printing list

print "List elements: ", list

Output

List elements are:  [10, 20, 30, 'New Delhi', 'Mumbai']

List elements:  [10, 20, 30, 'New Delhi', 'Mumbai', 40, 50, 'Chennai']

List elements:  [10, 20, 30, 'New Delhi', 'Mumbai', 40, 50]

List elements:  [10, 20, 30, 'New Delhi', 'Mumbai', 40]

Program to find the differences of two lists

Given two integer lists, we will find the differences, i.e. the elements that do not exist in the second lists.

Example:

Input:

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

List2 = [10, 20, 30, 60, 70]

Output:

Different elements:

[40, 50]

PROGRAM

# list1 - first list of the integers

# lists2 - second list of the integers

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

list2 = [10, 20, 30, 60, 70]

# printing lists

print "list1:", list1

print "list2:", list2

# finding and printing differences of the lists

print "Difference elements:"

print (list (set(list1) - set (list2)))

Output

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

list2: [10, 20, 30, 60, 70]

Difference elements:

[40, 50]

PROGRAM 2

With mixed element type, print 1) the elements that do not exist in list 2 and 2) those that do not exist in list 1.

# list1 - first list with mixed type elements

# lists2 - second list with mixed type elements

list1 = ["Amit", "Shukla", 21, "New Delhi"]

list2 = ["Aman", "Shukla", 21, "Mumbai"]

# printing lists

print "list1:", list1

print "list2:", list2

# finding and printing differences of the lists

print "Elements not exists in list2:"

print (list (set(list1) - set (list2)))

print "Elements not exists in list1:"

print (list (set(list2) - set (list1)))

Output

list1: ['Amit', 'Shukla', 21, 'New Delhi']

list2: ['Aman', 'Shukla', 21, 'Mumbai']

Elements not exists in list2:

['Amit', 'New Delhi']

Elements not exists in list1:

['Aman', 'Mumbai']

Program to remove duplicate elements from the list

Example:

Input:

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

Output:

List after removing duplicate elements

list2:  [10, 20, 30, 40, 50]

Logic

It is too easy to implement the program by adding elements one by one to another list by checking whether or not element is available in the new list.

Let's assume that 20 is available in list 1 three times, and when we add 20 (first occurrence) to list 2, it will be added, but when we add 20 (second occurrence) to list 2, condition will be false and element will not be added to list. And finally, without duplicate elements we'll get list.

PROGRAM

# declare list

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

# creating another list with unique elements

# declare another list

list2 = []

# appending elements

for n in list1:

if n not in list2:

list2.append(n)

# printing the lists

print "Original list"

print "list1: ", list1

print "List after removing duplicate elements"

print "list2: ", list2

Output

Original list

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

List after removing duplicate elements

list2:  [10, 20, 30, 40, 50]

Program (Defining By User defines function):

# Function to remove duplicates

def removeDuplicates (list1):

# declare another list

list2 = []

# appending elements

for n in list1:

if n not in list2:

list2.append (n)

return list2

# Main code

# declare a list

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

# print the list

print "Original list: ", list1

print "List after duplicate remove: ", removeDuplicates (list1)

Output

Original list:  [10, 20, 10, 20, 30, 40, 30, 50]

List after duplicate remove:  [10, 20, 30, 40, 50]

Create three lists of numbers, their squares and cubes

Example:

Input:

Start = 1

End = 10

Output:

numbers: [1, 2, 3, 4, 5, 6, 7, 8,  9, 10]

squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

cubes  : [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Logic

Three lists to declare.

Defining range, here we define beginning with 1 and ending with 10.

Run a loop with the range as range (start, end + 1) and count as loop counter.

Connect the count of the loop counter to the list named numbers, connect the square to the list called squares and add the cube to the list called cubes.

In the end, print out the lists.

PROGRAM

# declare lists

numbers = []

squares = []

cubes = []

# start and end numbers

start = 1

end = 10

# run a loop from start to end+1

for count in range (start, end+1) :

numbers.append (count)

squares.append (count**2)

cubes.append (count**3)

# print the lists

print "numbers: ",numbers

print "squares: ",squares

print "cubes  : ",cubes

Output

numbers:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squares:  [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

cubes  :  [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Iterate a list in reverse order

Given a list, and in python we can iterate it in reverse order.

Example:

Input:

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

Output:

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

Input;

list = ['Hello', 10 'World', 20]

Output:

list = [20, 'World', 10, 'Hello']

PROGRAM

# define a list

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

# print the list

print "original list: ", list1

# iterate the list

list1 = list1[::-1]

# print the list

print "list in reverse order: ", list1

# another list with string and integer elements

list2 = ['Hello', 10, 'world', 20]

# print the list

print "Original list: ", list2

# iterate the list

list2 = list2[::-1]

# print the list

print "list in reverse order: ", list2

Output

original list:  [10, 20, 30, 40, 50]

list in reverse order:  [50, 40, 30, 20, 10]

Original list:  ['Hello', 10, 'world', 20]

list in reverse order:  [20, 'world', 10, 'Hello']

Print list after removing EVEN numbers

Example:

Input:

list = [11, 22, 33, 44, 55]

Output:

list after removing EVEN numbers

list = [11, 33, 55]

LOGIC

Using for ... in loop to traverse every number in the sequence.

Test the condition, i.e. the number is divisible by 2 or not – the number must be divisible by 2 .

If number is divisible by 2 Then Remove the number from list

Using list.remove() method to remove the number from list.

PROGRAM

# list with EVEN and ODD number

list = [11, 22, 33, 44, 55]

# print original list

print "Original list:"

print list

# loop to traverse each element in the list

# and, remove elements

# which are EVEN (divisible by 2)

for i  in list:

if(i%2 == 0):

list.remove(i)

# print list after removing EVEN elements

print "list after removing EVEN numbers:"

print list

Output

Original list:

[11, 22, 33, 44, 55]

list after removing EVEN numbers:

[11, 33, 55]

Python string programs

Declare, assign and print the string (Different ways)

Ways

Syntax

Description

Way1

Single quotes

'Message'

Assign a single line string.

Way2

Double quotes

"Message"

Assign a single line string.

Way3

Triple single quotes

'''Message'''

Assign single line as well as multi-line string.

Way4

Triple double quotes

"""Message"""

Assign single line as well as multi-line string.

PROGRAM

# Declare, assign string (1)

# using single quotes 'string'

str1 = 'Hello world, How are you?'

# Declare, assign string (2)

# using double quotes "string"

str2 = "Hello world, How are you?"

# Declare assign string (3)

# using triple single quotes '''string'''

str3 = '''Hello world, How are you?'''

# Declare assign string (4)

# using triple double quotes """string"""

str4 = """Hello world, How are you?"""

# Declare, assign multi-line string (5)

# Triple double quotes allows to assign

# multi-line string

str5 = '''Hello world,

How are you?'''

# print the string

print "str1: ", str1

print "str2: ", str2

print "str3: ", str3

print "str4: ", str4

print "str5: ", str5

Output

str1:  Hello world, How are you?

str2:  Hello world, How are you?

str3:  Hello world, How are you?

str4:  Hello world, How are you?

str5:  Hello world,

How are you?

Access and print characters from the string

Example:

Input:

str: "Hello world"

Output:

First character: H

Second character: e

Last character: d

Second last character: l

Characters from 0th to 4th index: Hello

And, so on...

PROGRAM

# access characters in string

# declare, assign string

str = "Hello world"

# print complete string

print "str:", str

# print first character

print "str[0]:", str[0]

# print second character

print "str[1]:", str[1]

# print last character

print "str[-1]:", str[-1]

# print second last character

print "str[-2]:", str[-2]

# print characters from 0th to 4th index i.e.

# first 5 characters

print "str[0:5]:", str[0:5]

# print characters from 2nd index to 2nd last index

print "str[2,-2]:", str[2:-2]

# print string character by character

print "str:"

for i in str:

print i,

#comma after the variable

# it does not print new line

Output

str: Hello world

str[0]: H

str[1]: e

str[-1]: d

str[-2]: l

str[0:5]: Hello

str[2,-2]: llo wor

str:

H e l l o   w o r l d

Program to print words with their length of a string

Example:

Input:

str = "Hello World How are you?"

Output:

Hello ( 5 )

World ( 5 )

How ( 3 )

are ( 3 )

you? ( 4 )

String.split() Method

To split the string into words, we use the method split(), an inbuilt method that splits the string into sub-string (words) defined by the given delimiter.

split() Method Syntax:

String.split(delimiter)

EXPLANATION

For example, there's a string str = "ABC PQR XYZ" and we want to break it into words using space to divide it, then space here would be delimiter. The statement will be str.split(" ") to break the string into words, and then output will be "ABC" "PQR" "XYZ."

PROGRAM

# Function to split into words

# and print words with its length

def splitString (str):

# split the string by spaces

str = str.split (' ')

# iterate words in string

for words in str:

print words," (", len (words), ")"

# Main code

# declare string and assign value

str = "Hello World How are you?"

# call the function

splitString(str)

Output

Hello  ( 5 )

World  ( 5 )

How  ( 3 )

are  ( 3 )

you?  ( 4 )

Count vowels in a string

Example:

Input:

Str = "Hello world"

Output:

Total vowels are: 3

PROGRAM

# count vowels in a string

# declare, assign string

str = "Hello world"

# declare count

count = 0

# iterate and check each character

for i in str:

# check the conditions for vowels

if( i=='A' or i=='a' or i=='E' or i=='e'

or i=='I' or i=='i' or i=='O' or i=='o'

or i=='U' or i=='u'):

count +=1;

# print count

print "Total vowels are: ", count

Output

Total vowels are:  3

Create multiple copies of a string by using multiplication operator

Using multiplication operator to create multiple copies of a string,

the multiplication operator ( * ) will be used

Example:

Input:

str1 = "Hello"

n = 3

logic:

str2 =str1*3

Output:

str2= "HelloHelloHello"

Program:

# Python program to create N copies

# of a given string

# define inputs: string and N

str1 = "Hello"

n = 3

# create copies

str2 = str1 * 3

# print

print "str1: ", str1

print "str2: ", str2

Output

str1:  Hello

str2:  HelloHelloHello

Table of Contents

SCALA INTRODUCTION

Scala - Scalable Launguage

Scala vs Java

Python vs Scala

Scala Keywords

Scala Identifiers

Data Types in Scala

Scope of Variables In Scala

Scala Ranges

Scala Decision Making

SCALA LOOPS

PYTHON CODING EXAMPLES

ASCII value of character in Python

Calculate simple interest

Calculate compound interest

Python program to check the given year is a leap year or not

Python | Some of the examples of simple if else

Calculate discount based on the sale amount in Python

Design a simple calculator using if elif in Python

BMI (Body Mass Index) calculator in Python

Write functions to find square and cube of a given number in Python

Compute the net amount

Convert temperature in Python program

Python program to convert meters into yards

Find the day in Python

Python array programs

Create matrix in Python

Python program to create matrix using numpy

Python Date & Time Programs

Python code to print today's year, month and day

Python Lists

Program for Adding, removing elements in the list

Program to find the differences of two lists

Program to remove duplicate elements from the list

Create three lists of numbers, their squares and cubes

Iterate a list in reverse order

Print list after removing EVEN numbers

Python string programs

Declare, assign and print the string (Different ways)

Access and print characters from the string

Program to print words with their length of a string

Count vowels in a string

Create multiple copies of a string by using multiplication operator