1598565600

# Count of valid pairs (X, Y) from given strings such that concatenating X

Given an array **arr[] of N **strings. Let X and Y be two strings, and Y are said to bevalid pair if the rearrangement of the resultant string from the concatenation of X with X (i.e., X+X) gives Y. The task is to count the number of such valid pairs.

Examples:

Input:_ N = 4, arr[] = {“hacker”, ”ackerhackerh”, ”int”, ”iittnn”, ”long”}_

Output:_ 2 _

Explanation:

Pair {“hacker”, ”ackerhackerh”} “hacker” When concatenated with “hacker” gives ”ackerhackerh” after rearrangement.

_Pair {“int”, ”iittnn”} “int” When concatenated with “int” gives ”iittnn” after rearrangement. _

Input:_ N = 3, arr[] = {“easy”, ”yeasseay“, “medium“} _

Output:1

Explanation:

Pair {“easy”, ”yeasseay“} “easy” When concatenated with “easy” gives ”yeasseay“ after rearrangement.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The idea is to generate all possible pairs and check if any pairs form a valid pair as per the given condition or not. If yes then count this pair and check for the next pair. Print the value of count after the above steps.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to store the sorted string in Hashmap along with its count and iterate through each string of the array concatenate it with itself and find its count in Hashmap add it to the count of pairs. Below are the steps:

1. Create a hashmap.
2. Sort the given strings in the array and store its count in hashmap.
3. Again iterate through all strings and concatenate each string with itself sort the string and find its count in Hashmap.
4. Update the final count in the above step and print the final count after all the above steps.

Below is the implementation of the above approach:

• Java
• Python3

`// Java program for the above approach`

`**import**` `java.util.*;`

`**public**` `**class**` `Main {`

`// Function that count total number`

`// of valid pairs`

`**public**` `**static**` `**int**`

`countPairs(String arr[],` `**int**` `N)`

`{`

`// Create hashmap to store the`

`// frequency of each string`

`// in sorted form`

`HashMap<String, Integer> map`

`=` `**new**` `HashMap<>();`

`// Initialise the count of pairs`

`**int**` `count =` `0``;`

`**for**` `(``**int**` `i =` `0``; i < N; i++) {`

`String s = sort(arr[i]);`

`// Store each string in sorted`

`// form along with it's count`

`map.put(s, map.getOrDefault(s,` `0``) +` `1``);`

`}`

`// Iterate through each string`

`// in the array`

`**for**` `(``**int**` `i =` `0``; i < N; i++) {`

`// Concatenate each string with itself`

`String s = sort(arr[i] + arr[i]);`

`// Find its count in the hashmap`

`count += map.getOrDefault(s,` `0``);`

`}`

`// Return answer`

`**return**` `count;`

`}`

`// Function to implement sorting on`

`// strings`

`**public**` `**static**` `String sort(String s)`

`{`

`// Convert string to char array`

`**char**` `ch[] = s.toCharArray();`

`// Sort the array`

`Arrays.sort(ch);`

`StringBuffer sb =` `**new**` `StringBuffer();`

`**for**` `(``**char**` `c : ch)`

`sb.append(c);`

`// Return string`

`**return**` `sb.toString();`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String args[])`

`{`

`**int**` `N =` `3``;`

`// Given array of strings`

`String arr[] = {` `"easy"``,` `"yeasseay"``,`

`"medium"` `};`

`// Function Call`

`System.out.println(countPairs(arr, N));`

`}`

`}`

Output:

``````1
``````

Time Complexity:_ O(N)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#hash #sorting #strings

1665369120

## CellularAutomata.jl: Cellular Automata Simulation toolkit for Julia

Cellular Automata

A cellular automaton is a collection of "colored" cells on a grid of specified shape that evolves through a number of discrete time steps according to a set of rules based on the states of neighboring cells. The rules are then applied iteratively for as many time steps as desired.

mathworld.wolfram.com/CellularAutomaton

## Elementary CA

To generate an elementary cellular automaton, use

``````ca = CellularAutomaton(rule, init, gen)
``````

where `rule` is the Wolfram code (integer), `init` is a vector containing the initial starting condition and `gen` is the number of generations to be computed. For a single starting cell in the middle just omit the `init` vector.

To generate 15 generations of elementary cellular automaton of rule 90 use

``````using CellularAutomata

ca90 = CellularAutomaton(90, 16)
``````
``````                            #
# #
#   #
# # # #
#       #
# #     # #
#   #   #   #
# # # # # # # #
#               #
# #             # #
#   #           #   #
# # # #         # # # #
#       #       #       #
# #     # #     # #     # #
#   #   #   #   #   #   #   #
# # # # # # # # # # # # # # # #
``````

## Totalistic CA

For a more complex cellular automaton you can change the number of states `k` the cell can be and the radius `r` of neighbors that can influence the states. If `k` is changed to be larger than 2, a totalistic CA is computed where only the average value of all neighbors count. This can be done like this

``````ca = CellularAutomaton(993, 15, k=3)
``````
``````                        X
XXX
X# #X
X     X
XXX   XXX
X# #X X# #X
X     #     X
XXX   ###   XXX
X# #X # X # X# #X
X      # X #      X
XXX    ## X ##    XXX
X# #X  #   X   #  X# #X
X     X### XXX ###X     X
XXX   X XX  # #  XX X   XXX
X# #X XX###X## ##X###XX X# #X
``````

## 2 dimensional CAs

Two dimensional cellular automaton (like Conway's Game of Life) can be created by

``````ca = CA2d(B, S, init, gen)
``````

where `B` and `S` are vectors that have the numbers of neighboring cells that define when cell is born or survives, `init` (matrix) is the initial starting condition and `gen` is the number of generations the CA is to be computed.

Game of life is then run for 9 generations for e.g. a turbine pattern by typing

``````ca = CA2d([3], [2, 3], init, 9)
``````

1st step

``````   ###### ##
###### ##
##
##     ##
##     ##
##     ##
##
## ######
## ######

``````

2nd

``````    ####
#    # ##
#    #   #
##    #
##    #  #
#  #   #  #
#  #    ##
#    ##
#   #    #
## #    #
####

``````

3rd

``````     ##
####
# ## ## #
##  #
##  ##  ###
#### #  ###
#  #   #  #
###  # ####
###  ##  ##
#  ##
# ## ## #
####
##

``````

4th

``````    #  #
#
##
# ##      #
#  #   #
#   # ###
#           #
### #   #
#   #  #
#      ## #
##
#
#  #

``````

5th

``````        ##
#
###  ##
### #   #
#    # ##
# #
## #    #
#   # ###
##  ###
#
##
``````

6th

``````        ##
#
# #  ##
# # ###  #
#  ######
## ##
######  #
#  ### # #
##  # #
#
##

``````

7th

``````     #  # #
## # ###
#      #
##     #

#     ##
#      #
### # ##
# #  #

``````

8th

``````    ## ## #
##  ## ##
#
##
##     ##
##
#
## ##  ##
# ## ##

``````

9th

``````   ###### ##
###### ##
##
##     ##
##     ##
##     ##
##
## ######
## ######

``````

## Running Tests

To run tests, execute the following command from the root folder of the repository:

``julia tests/run_tests.jl``

Author: Natj
Source Code: https://github.com/natj/CellularAutomata.jl

1598565600

## Count of valid pairs (X, Y) from given strings such that concatenating X

Given an array **arr[] of N **strings. Let X and Y be two strings, and Y are said to bevalid pair if the rearrangement of the resultant string from the concatenation of X with X (i.e., X+X) gives Y. The task is to count the number of such valid pairs.

Examples:

Input:_ N = 4, arr[] = {“hacker”, ”ackerhackerh”, ”int”, ”iittnn”, ”long”}_

Output:_ 2 _

Explanation:

Pair {“hacker”, ”ackerhackerh”} “hacker” When concatenated with “hacker” gives ”ackerhackerh” after rearrangement.

_Pair {“int”, ”iittnn”} “int” When concatenated with “int” gives ”iittnn” after rearrangement. _

Input:_ N = 3, arr[] = {“easy”, ”yeasseay“, “medium“} _

Output:1

Explanation:

Pair {“easy”, ”yeasseay“} “easy” When concatenated with “easy” gives ”yeasseay“ after rearrangement.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The idea is to generate all possible pairs and check if any pairs form a valid pair as per the given condition or not. If yes then count this pair and check for the next pair. Print the value of count after the above steps.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to store the sorted string in Hashmap along with its count and iterate through each string of the array concatenate it with itself and find its count in Hashmap add it to the count of pairs. Below are the steps:

1. Create a hashmap.
2. Sort the given strings in the array and store its count in hashmap.
3. Again iterate through all strings and concatenate each string with itself sort the string and find its count in Hashmap.
4. Update the final count in the above step and print the final count after all the above steps.

Below is the implementation of the above approach:

• Java
• Python3

`// Java program for the above approach`

`**import**` `java.util.*;`

`**public**` `**class**` `Main {`

`// Function that count total number`

`// of valid pairs`

`**public**` `**static**` `**int**`

`countPairs(String arr[],` `**int**` `N)`

`{`

`// Create hashmap to store the`

`// frequency of each string`

`// in sorted form`

`HashMap<String, Integer> map`

`=` `**new**` `HashMap<>();`

`// Initialise the count of pairs`

`**int**` `count =` `0``;`

`**for**` `(``**int**` `i =` `0``; i < N; i++) {`

`String s = sort(arr[i]);`

`// Store each string in sorted`

`// form along with it's count`

`map.put(s, map.getOrDefault(s,` `0``) +` `1``);`

`}`

`// Iterate through each string`

`// in the array`

`**for**` `(``**int**` `i =` `0``; i < N; i++) {`

`// Concatenate each string with itself`

`String s = sort(arr[i] + arr[i]);`

`// Find its count in the hashmap`

`count += map.getOrDefault(s,` `0``);`

`}`

`// Return answer`

`**return**` `count;`

`}`

`// Function to implement sorting on`

`// strings`

`**public**` `**static**` `String sort(String s)`

`{`

`// Convert string to char array`

`**char**` `ch[] = s.toCharArray();`

`// Sort the array`

`Arrays.sort(ch);`

`StringBuffer sb =` `**new**` `StringBuffer();`

`**for**` `(``**char**` `c : ch)`

`sb.append(c);`

`// Return string`

`**return**` `sb.toString();`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String args[])`

`{`

`**int**` `N =` `3``;`

`// Given array of strings`

`String arr[] = {` `"easy"``,` `"yeasseay"``,`

`"medium"` `};`

`// Function Call`

`System.out.println(countPairs(arr, N));`

`}`

`}`

Output:

``````1
``````

Time Complexity:_ O(N)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#hash #sorting #strings

1594769515

## How to validate mobile phone number in laravel with example

Data validation and sanitization is a very important thing from security point of view for a web application. We can not rely on user’s input. In this article i will let you know how to validate mobile phone number in laravel with some examples.

if we take some user’s information in our application, so usually we take phone number too. And if validation on the mobile number field is not done, a user can put anything in the mobile number field and without genuine phone number, this data would be useless.

Since we know that mobile number can not be an alpha numeric or any alphabates aand also it should be 10 digit number. So here in this examples we will add 10 digit number validation in laravel application.

We will aalso see the uses of regex in the validation of mobile number. So let’s do it with two different way in two examples.

## Example 1:

In this first example we will write phone number validation in HomeController where we will processs user’s data.

``````<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('createUser');
}

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function store(Request \$request)
{
\$request->validate([
'name' => 'required',
'phone' => 'required|digits:10',
'email' => 'required|email|unique:users'
]);

\$input = \$request->all();
\$user = User::create(\$input);

return back()->with('success', 'User created successfully.');
}
}
``````

## Example 2:

In this second example, we will use regex for user’s mobile phone number validation before storing user data in our database. Here, we will write the validation in Homecontroller like below.

``````<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Validator;

class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('createUser');
}

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function store(Request \$request)
{
\$request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)\$/|min:10',
'email' => 'required|email|unique:users'
]);

\$input = \$request->all();
\$user = User::create(\$input);

return back()->with('success', 'User created successfully.');
}
}
``````

#laravel #laravel phone number validation #laravel phone validation #laravel validation example #mobile phone validation in laravel #phone validation with regex #validate mobile in laravel

1655243220

## A Weather_widget Used for Flutter with Many Custom Config

weather_widget

Simple weather related widget, which can be freely combined to form a variety of weather backgrounds

## Getting Started

depend

``````dependencies:
weather_widget: ^1.0.6
``````

Weatherwidget is easy to use, just add weatherwidget to start using

``````WeatherWidget(
size:Size.infinite,
weather:'Sunny',
sunConfig:SunConfig()
),
``````

This will add a sunny day using the default settings

or other weather type
(Note: Raindrops and snowflakes need to specify the default number, and they will move randomly within the range)

``````WeatherWidget(
size:Size.infinite,
weather:'Cloudy',
cloudConfig:CloudConfig()
),

WeatherWidget(
size:Size.infinite,
weather:'Rainy',
rainConfig:RainConfig(
rainNum:'the num of raindrops you want'
)
),

WeatherWidget(
size:Size.infinite,
weather:'Snowy',
snowConfig:SnowConfig(
snowNum:'the num of snowflakes you want'
)
),

WeatherWidget(
size:Size.infinite,
weather:'Thunder',
thunderConfig:ThunderConfig()
),``````

Of course, each config contains other settings, such as the range, size, length, falling speed and color of random raindrops. You can use them to create hailstones and other weather features
If the default weather is not enough, you can use individual widgets and stack() widget to piece together the desired weather
Like this sunset breeze, etc

These are include in this widget
background

``````    BackgroundWidget（List<Color>,size）
``````

cloud

``````    CloudWidget (Color)
``````

A single random raindrop

``````RainWidget (
@required rainRangeXStart, #X-axis starting point of raindrop random occurrence
@required rainRangeXEnd,
@required rainRangeYStart,
@required rainRangeYEnd,
@required durationRangeStartMill,  #Minimum time to fall
@required durationRangeEndMill,
rainLength,
rainWidth,
rainColor,
rainCurve  #Curve of falling animation
)
``````

A single random snowflake

``````SnowWidget (
this.snowAreaXStart,  #X-axis starting point of snowflake random occurrence
this.snowAreaXEnd,
this.snowWaveRangeMin,    #The minimum floating distance of snowflakes
this.snowWaveRangeMax,
this.snowFallSecMin,  #Minimum time of snowflake falling
this.snowFallSecMax,
this.snowWaveSecMin,  #Minimum time for snowflake to float
this.snowWaveSecMax,
this.snowSize,
this.snowColor,
this.snowAreaYStart,   #Y-axis point of snowflake occurrence
this.snowAreaYEnd,
this.waveCurve,        #Floating animation curve
)
``````

A single flash

``````ThunderWidget (
this.flashMillStart,   #Minimum flashing time
this.flashMillEnd,
this.pauseMillStart,   #Minimum interval time
this.pauseMillEnd,
this.blurStyle,        #blur model
this.blurSigma,
this.points,
this.color,
this.width
)
``````

a single wind

``````WindWidget (
this.pauseMillStart,    #Minimum interval time
this.pauseMillEnd,
this.windPositionY,     #Y-axis point of wind occurrence
this.windSlideMill,     #Passing time
this.windColor,
this.windWidth,
this.windSlideXEnd,
this.windSlideXStart,
this.windGap,           #line spacing in a wind
this.blurStyle,
this.blurSigma
)
``````

Using sunny weather by set the WeatherWidget background config in a sunConfig()

## Use this package as a library

### Depend on it

Run this command:

With Flutter:

`` \$ flutter pub add weather_widget``

This will add a line like this to your package's pubspec.yaml (and run an implicit `flutter pub get`):

``````dependencies:
weather_widget: ^1.0.6``````

Alternatively, your editor might support `flutter pub get`. Check the docs for your editor to learn more.

### Import it

Now in your Dart code, you can use:

``````import 'package:weather_widget/WeatherWidget.dart';
import 'package:weather_widget/example/main.dart';``````

example/main.dart

``````import 'package:flutter/material.dart';
import 'package:weather_widget/WeatherWidget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WeatherWidget(
size: Size.infinite,
weather: 'Thunder',
thunderConfig:ThunderConfig(
thunderWidth:12
)
)
);
}
}``````

Author: Carendule
Source Code: https://github.com/carendule/WeatherWidget

1666770774

## Variables in Python

In this Python tutorial for beginners, we learn about Variables in Python. Variables are containers for storing data values. A Python variable is a symbolic name that is a reference or pointer to an object.

## Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

### Example

``````x = 5
y = "John"
print(x)
print(y)``````

Variables do not need to be declared with any particular type, and can even change type after they have been set.

### Example

``````x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)``````

## Casting

If you want to specify the data type of a variable, this can be done with casting.

### Example

``````x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0``````

## Get the Type

You can get the data type of a variable with the `type()` function.

### Example

``````x = 5
y = "John"
print(type(x))
print(type(y))``````

## Single or Double Quotes?

String variables can be declared either by using single or double quotes:

### Example

``````x = "John"
# is the same as
x = 'John'``````

## Case-Sensitive

Variable names are case-sensitive.

### Example

This will create two variables:

``````a = 4
A = "Sally"
#A will not overwrite a``````

## What is a Variable in Python?

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.

### Python Variable Types

Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like a, aa, abc, etc.

In this tutorial, we will learn,

• How to Declare and use a Variable
• Re-declare a Variable
• Concatenate Variables
• Local & Global Variables
• Delete a variable

## How to Declare and use a Variable

Let see an example. We will define variable in Python and declare it as “a” and print it.

``````a=100
print (a)``````

## Re-declare a Variable

You can re-declare Python variables even after you have declared once.

Here we have Python declare variable initialized to f=0.

Later, we re-assign the variable f to value “guru99”

Python 2 Example

``````# Declare a variable and initialize it
f = 0
print f
# re-declaring the variable works
f = 'guru99'
print f``````

Python 3 Example

``````# Declare a variable and initialize it
f = 0
print(f)
# re-declaring the variable works
f = 'guru99'
print(f)``````

## Python String Concatenation and Variable

Let’s see whether you can concatenate different data types like string and number together. For example, we will concatenate “Guru” with the number “99”.

Unlike Java, which concatenates number with string without declaring number as string, while declaring variables in Python requires declaring the number as string otherwise it will show a TypeError

For the following code, you will get undefined output –

``````a="Guru"
b = 99
print a+b``````

Once the integer is declared as string, it can concatenate both “Guru” + str(“99”)= “Guru99” in the output.

``````a="Guru"
b = 99
print(a+str(b))``````

## Python Variable Types: Local & Global

There are two types of variables in Python, Global variable and Local variable. When you want to use the same variable for rest of your program or module you declare it as a global variable, while if you want to use the variable in a specific function or method, you use a local variable while Python variable declaration.

Let’s understand this Python variable types with the difference between local and global variables in the below program.

1. Let us define variable in Python where the variable “f” is global in scope and is assigned value 101 which is printed in output
2. Variable f is again declared in function and assumes local scope. It is assigned value “I am learning Python.” which is printed out as an output. This Python declare variable is different from the global variable “f” defined earlier
3. Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of “f” is it displays the value of global variable f=101

Python 2 Example

``````# Declare a variable and initialize it
f = 101
print f
# Global vs. local variables in functions
def someFunction():
# global f
f = 'I am learning Python'
print f
someFunction()
print f``````

Python 3 Example

``````# Declare a variable and initialize it
f = 101
print(f)
# Global vs. local variables in functions
def someFunction():
# global f
f = 'I am learning Python'
print(f)
someFunction()
print(f)``````

While Python variable declaration using the keyword global, you can reference the global variable inside a function.

1. Variable “f” is global in scope and is assigned value 101 which is printed in output
2. Variable f is declared using the keyword global. This is NOT a local variable, but the same global variable declared earlier. Hence when we print its value, the output is 101

We changed the value of “f” inside the function. Once the function call is over, the changed value of the variable “f” persists. At line 12, when we again, print the value of “f” is it displays the value “changing global variable”

Python 2 Example

``````f = 101;
print f
# Global vs.local variables in functions
def someFunction():
global f
print f
f = "changing global variable"
someFunction()
print f``````

Python 3 Example

``````f = 101;
print(f)
# Global vs.local variables in functions
def someFunction():
global f
print(f)
f = "changing global variable"
someFunction()
print(f)``````

## Delete a variable

You can also delete Python variables using the command del “variable name”.

In the below example of Python delete variable, we deleted variable f, and when we proceed to print it, we get error “variable name is not defined” which means you have deleted the variable.

Example of Python delete variable or Python clear variable :

``````f = 11;
print(f)
del f
print(f)``````

## Summary:

• Variables are referred to “envelop” or “buckets” where information can be maintained and referenced. Like any other programming language Python also uses a variable to store the information.
• Variables can be declared by any name or even alphabets like a, aa, abc, etc.
• Variables can be re-declared even after you have declared them for once
• Python constants can be understood as types of variables that hold the value which can not be changed. Usually Python constants are referenced from other files. Python define constant is declared in a new or separate file which contains functions, modules, etc.
• Types of variables in Python or Python variable types : Local & Global
• Declare local variable when you want to use it for current function
• Declare Global variable when you want to use the same variable for rest of the program

To delete a variable, it uses keyword “del”.

## A Beginner’s Guide To Python Variables

A variable is a fundamental concept in any programming language. It is a reserved memory location that stores and manipulates data. This tutorial on Python variables will help you learn more about what they are, the different data types of variables, the rules for naming variables in Python. You will also perform some basic operations on numbers and strings. We’ll use Jupyter Notebook to implement the Python codes.

Variables are entities of a program that holds a value. Here is an example of a variable:

x=100

In the below diagram, the box holds a value of 100 and is named as x. Therefore, the variable is x, and the data it holds is the value.

The data type for a variable is the type of data it holds.

In the above example, x is holding 100, which is a number, and the data type of x is a number.

In Python, there are three types of numbers: Integer, Float, and Complex.

Integers are numbers without decimal points. Floats are numbers with decimal points. Complex numbers have real parts and imaginary parts.

Another data type that is very different from a number is called a string, which is a collection of characters.

Let’s see a variable with an integer data type:

``x=100``

To check the data type of x, use the type() function:

``type(x)``

Python allows you to assign variables while performing arithmetic operations.

``````x=654*6734
type(x)``````

To display the output of the variable, use the print() function.

``print(x) #It gives the product of the two numbers``

Now, let’s see an example of a floating-point number:

``````x=3.14
print(x)``````

type(x) #Here the type the variable is float

Strings are declared within a single or double quote.

``````x=’Simplilearn’

print(x)

x=” Simplilearn.”

print(x)

type(x)``````

In all of the examples above, we only assigned a single value to the variables. Python has specific data types or objects that hold a collection of values, too. A Python List is one such example.

Here is an example of a list:

``````x=[14,67,9]

print(x)

type(x)``````

You can extract the values from the list using the index position method. In lists, the first element index position starts at zero, the second element at one, the third element at two, and so on.

To extract the first element from the list x:

``print(x[0])``

To extract the third element from the list x:

``print(x[2])``

Lists are mutable objects, which means you can change the values in a list once they are declared.

``````x[2]=70 #Reassigning the third element in the list to 70

print(x)``````

Earlier, the elements in the list had [14, 67, 9]. Now, they have [14, 67, 70].

Tuples are a type of Python object that holds a collection of value, which is ordered and immutable. Unlike a list that uses a square bracket, tuples use parentheses.

``````x=(4,8,6)

print(x)

type(x)``````

Similar to lists, tuples can also be extracted with the index position method.

``print(x[1]) #Give the element present at index 1, i.e. 8``

If you want to change any value in a tuple, it will throw an error. Once you have stored the values in a variable for a tuple, it remains the same.

When we deal with files, we need a variable that points to it, called file pointers. The advantage of having file pointers is that when you need to perform various operations on a file, instead of providing the file’s entire path location or name every time, you can assign it to a particular variable and use that instead.

Here is how you can assign a variable to a file:

``````x=open(‘C:/Users/Simplilearn/Downloads/JupyterNotebook.ipynb’,’r’)

type(x)``````

Suppose you want to assign values to multiple variables. Instead of having multiple lines of code for each variable, you can assign it in a single line of code.

``(x, y, z)=5, 10, 5``

The following line code results in an error because the number of values assigned doesn’t match with the number of variables declared.

If you want to assign the same value to multiple variables, use the following syntax:

``x=y=z=1``

Now, let's look at the various rules for naming a variable.

1. A variable name must begin with a letter of the alphabet or an underscore(_)

Example:

``````abc=100 #valid syntax

_abc=100 #valid syntax

3a=10 #invalid syntax

@abc=10 #invalid syntax``````

. The first character can be followed by letters, numbers or underscores.

Example:

``````a100=100 #valid

_a984_=100 #valid

a9967\$=100 #invalid

xyz-2=100 #invalid``````

Python variable names are case sensitive.

Example:

``````a100 is different from A100.

a100=100

A100=200``````

Reserved words cannot be used as variable names.

Example:

``````break, class, try, continue, while, if

break=10

class=5

try=100``````

Python is more effective and more comfortable to perform when you use arithmetic operations.

The following is an example of adding the values of two variables and storing them in a third variable:

``````x=20

y=10

result=x+y

print(result)``````

Similarly, we can perform subtraction as well.

``````result=x-y

print(result)``````

Additionally, to perform multiplication and division, try the following lines of code:

``````result=x*y

print(result)

result=x/y

print(result)``````

As you can see, in the case of division, the result is not an integer, but a float value. To get the result of the division in integers, use “//”the integer division.

The division of two numbers gives you the quotient. To get the remainder, use the modulo (%) operator.

Now that we know how to perform arithmetic operations on numbers let us look at some operations that can be performed on string variables.

``var = ‘Simplilearn’``

You can extract each character from the variable using the index position. Similar to lists and tuples, the first element position starts at index zero, the second element index at one, and so on.

``````print(var[0]) #Gives the character at index 0, i.e. S

print(var[4]) #Gives the character at index 4, i.e. l``````

If you want to extract a range of characters from the string variable, you can use a colon (:) and provide the range between the ones you want to receive values from. The last index is always excluded. Therefore, you should always provide one plus the number of characters you want to fetch.

``print(var[0:3]) #This will extract the first three characters from zero, first, and second index.``

The same operation can be performed by excluding the starting index.

``print(var[:3])``

The following example prints the values from the fifth location until the end of the string.

Let’s see what happens when you try to print the following:

``print(var[0:20]) #Prints the entire string, although the string does not have 20 characters.``

To print the length of a string, use the len() function.

``len(var)``

Let’s see how you can extract characters from two strings and generate a new string.

``````var1 = “It’s Sunday”

var2 = “Have a great day”``````

The new string should say, “It’s a great Sunday” and be stored in var3.

``````var3 = var1[:5] + var2[5:13] + var1[5:]

print(var3)``````

Get prepared for your next career as a professional Python programmer with the Python Certification Training Course. Click to enroll now!

## Conclusion

I hope this blog helped you learn the concepts of Python variables. After reading this blog, you may have learned more about what a variable is, rules for declaring a variable, how to perform arithmetic operations on variables, and how to extract elements from numeric and string variables using the index position.

#python #programming