Loop Statements in Shell Script

There are total 3 types of looping statements that can be used in bash programming  

  1. while statement
  2. for statement
  3. until statement

To control the flow of the loop, two control statements are used they are, 
 

  1. break
  2. continue

Their descriptions and syntax are as follows: 

while statement 

Here the command is evaluated and based on the resulting loop will be executed, if the command raises to false then the loop will be terminated 

for statement 

The for loop operates on lists of items. It repeats a set of commands for every item in a list. Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.

until statement 

 The until loop is executed as many times as the condition/command evaluates to false. The loop terminates when the condition/command becomes true. 

 

Panda Series

class pandas.Series(data=Noneindex=Nonedtype=Nonename=Nonecopy=Falsefastpath=False)[source]

One-dimensional ndarray with axis labels (including time series).

Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN).

Operations between Series (+, -, /, , *) align values based on their associated index values– they need not be the same length. The resulting index will be the sorted union of the two indexes. Parametersdataarray-like, Iterable, dict, or scalar value

Contains data stored in Series. If data is a dict, argument order is maintained.indexarray-like or Index (1d)

Values must be hashable and have the same length as data. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, …, n) if not provided. If data is dict-like and index is None, then the values in the index are used to reindex the Series after it is created using the keys in the data.dtypestr, numpy.dtype, or ExtensionDtype, optional

Data type for the output Series. If not specified, this will be inferred from data. See the user guide for more usages.namestr, optional

The name to give to the Series.copybool, default False

Copy input data.

Attributes

S.NFunctionMeaning
1TReturn the transpose, which is by definition self.
2arrayThe ExtensionArray of the data backing this Series or Index.
3atAccess a single value for a row/column label pair.
4attrsDictionary of global attributes of this dataset.
5axesReturn a list of the row axis labels.
6dtypeReturn the dtype object of the underlying data.
7dtypesReturn the dtype object of the underlying data.
8flagsGet the properties associated with this pandas object.
9hasnansReturn if I have any nans; enables various perf speedups.
10iatAccess a single value for a row/column pair by integer position.
11ilocPurely integer-location based indexing for selection by position.
12indexThe index (axis labels) of the Series.
13is_monotonicReturn boolean if values in the object are monotonic_increasing.
14is_monotonic_decreasingReturn boolean if values in the object are monotonic_decreasing.
15is_monotonic_increasingAlias for is_monotonic.
16is_uniqueReturn boolean if values in the object are unique.
17locAccess a group of rows and columns by label(s) or a boolean array.
18nameReturn the name of the Series.
19nbytesReturn the number of bytes in the underlying data.
20ndimNumber of dimensions of the underlying data, by definition 1.
21shapeReturn a tuple of the shape of the underlying data.
22sizeReturn the number of elements in the underlying data.
23valuesReturn Series as ndarray or ndarray-like depending on the type.

1. pandas.Series.T

property Series.T

Return the transpose, which is by definition self.

2. pandas.Series.array

property Series.array

The ExtensionArray of the data backing this Series or Index.ReturnsExtensionArray

An ExtensionArray of the values stored within. For extension types, this is the actual array. For NumPy native types, this is a thin (no copy) wrapper around numpy.ndarray.

.array differs .values which may require converting the data to a different form.

3. pandas.Series.at

property Series.at

Access a single value for a row/column label pair.

Similar to loc, in that both provide label-based lookups. Use at if you only need to get or set a single value in a DataFrame or Series.RaisesKeyError

If ‘label’ does not exist in DataFrame.

4. pandas.Series.attrs

property Series.attrs

Dictionary of global attributes of this dataset.

5. pandas.Series.axes

property Series.axes

Return a list of the row axis labels.

6.pandas.Series.dtype

property Series.dtype

Return the dtype object of the underlying data.

7.pandas.Series.dtypes

property Series.dtypes

Return the dtype object of the underlying data.

8. pandas.Series.flags

property Series.flags

Get the properties associated with this pandas object.

The available flags are

9. pandas.Series.hasnans

property Series.hasnans

Return True if there are any NaNs.

Enables various performance speedups.

10. pandas.Series.iat

property Series.iat

Access a single value for a row/column pair by integer position.

Similar to iloc, in that both provide integer-based lookups. Use iat if you only need to get or set a single value in a DataFrame or Series.RaisesIndexError

When integer position is out of bounds.

11. pandas.Series.iloc

property Series.iloc

Purely integer-location based indexing for selection by position.

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.

Allowed inputs are:

  • An integer, e.g. 5.
  • A list or array of integers, e.g. [4, 3, 0].
  • A slice object with ints, e.g. 1:7.
  • A boolean array.
  • callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.

.iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics).

12. pandas.Series.index

Series.index

The index (axis labels) of the Series.

13. pandas.Series.is_monotonic

property Series.is_monotonic

Return boolean if values in the object are monotonic_increasing.Returns bool

14. pandas.Series.is_monotonic_decreasing

property Series.is_monotonic_decreasing

Return boolean if values in the object are monotonic_decreasing.Returns bool

15. pandas.Series.is_monotonic_increasing

property Series.is_monotonic_increasing

Alias for is_monotonic.

16. pandas.Series.is_unique

property Series.is_unique

Return boolean if values in the object are unique.
Returns bool

17. pandas.Series.loc

property Series.loc

Access a group of rows and columns by label(s) or a boolean array.

.loc[] is primarily label based, but may also be used with a boolean array.

Allowed inputs are:

  • A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
  • A list or array of labels, e.g. ['a', 'b', 'c'].
  • A slice object with labels, e.g. 'a':'f'.WarningNote that contrary to usual python slices, both the start and the stop are included
  • A boolean array of the same length as the axis being sliced, e.g. [True, False, True].
  • An alignable boolean Series. The index of the key will be aligned before masking.
  • An alignable Index. The Index of the returned selection will be the input.
  • callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)

See more at Selection by Label.RaisesKeyError

If any items are not found.IndexingError

If an indexed key is passed and its index is unalignable to the frame index.

18. pandas.Series.name

property Series.name

Return the name of the Series.

The name of a Series becomes its index or column name if it is used to form a DataFrame. It is also used whenever displaying the Series using the interpreter.Returnslabel (hashable object)

The name of the Series, also the column name if part of a DataFrame.

See alsoSeries.rename

Sets the Series name when given a scalar input.Index.name

Corresponding Index property.

Examples

The Series name can be set initially when calling the constructor.

>>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
>>> s
0    1
1    2
2    3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0    1
1    2
2    3
Name: Integers, dtype: int64

The name of a Series within a DataFrame is its column name.

>>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
...                   columns=["Odd Numbers", "Even Numbers"])
>>> df
   Odd Numbers  Even Numbers
0            1             2
1            3             4
2            5             6
>>> df["Even Numbers"].name
'Even Numbers'

19. pandas.Series.nbytes

property Series.nbytes

Return the number of bytes in the underlying data.

20. pandas.Series.ndim

property Series.ndim

Number of dimensions of the underlying data, by definition 1.

21. pandas.Series.shape

property Series.shape

Return a tuple of the shape of the underlying data.

22. pandas.Series.size

property Series.size

Return the number of elements in the underlying data.

23. pandas.Series.values

property Series.values

Return Series as ndarray or ndarray-like depending on the dtype.

Warning

We recommend using Series.array or Series.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.Returnsnumpy.ndarray or ndarray-like

See alsoSeries.array

Reference to the underlying data.Series.to_numpy

A NumPy array representing the underlying data.

Examples

>>> pd.Series([1, 2, 3]).values
array([1, 2, 3])
>>> pd.Series(list('aabc')).values
array(['a', 'a', 'b', 'c'], dtype=object)
>>> pd.Series(list('aabc')).astype('category').values
['a', 'a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']

Timezone aware datetime data is converted to UTC:

>>> pd.Series(pd.date_range('20130101', periods=3,
...                         tz='US/Eastern')).values
array(['2013-01-01T05:00:00.000000000',
       '2013-01-02T05:00:00.000000000',
       '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')

Methods

S.NMethodMeaning
1abs()Return a Series/DataFrame with absolute numeric value of each element.
2add(other[, level, fill_value, axis])Return Addition of series and other, element-wise (binary operator add).
3add_prefix(prefix)Prefix labels with string prefix.
4add_suffix(suffix)Suffix labels with string suffix.
5agg([func, axis])Aggregate using one or more operations over the specified axis.
6aggregate([func, axis])Aggregate using one or more operations over the specified axis.
7align(other[, join, axis, level, copy, …])Align two objects on their axes with the specified join method.
8all([axis, bool_only, skipna, level])Return whether all elements are True, potentially over an axis.
9any([axis, bool_only, skipna, level])Return whether any element is True, potentially over an axis.
10append(to_append[, ignore_index, …])Concatenate two or more Series.
11apply(func[, convert_dtype, args])Invoke function on values of Series.
12argmax([axis, skipna])Return int position of the largest value in the Series.
13argmin([axis, skipna])Return int position of the smallest value in the Series.
14argsort([axis, kind, order])Return the integer indices that would sort the Series values.
15asfreq(freq[, method, how, normalize, …])Convert TimeSeries to specified frequency.
16asof(where[, subset])Return the last row(s) without any NaNs before where.
17astype(dtype[, copy, errors])Cast a pandas object to a specified dtype dtype.
18at_time(time[, asof, axis])Select values at particular time of day (e.g., 9:30AM).
19autocorr([lag])Compute the lag-N autocorrelation.
20backfill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='bfill'.
21between(left, right[, inclusive])Return boolean Series equivalent to left <= series <= right.
22between_time(start_time, end_time[, …])Select values between particular times of the day (e.g., 9:00-9:30 AM).
23bfill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='bfill'.
24bool()Return the bool of a single element Series or DataFrame.
25catalias of pandas.core.arrays.categorical.CategoricalAccessor
26clip([lower, upper, axis, inplace])Trim values at input threshold(s).
27combine(other, func[, fill_value])Combine the Series with a Series or scalar according to func.
28combine_first(other)Combine Series values, choosing the calling Series’s values first.
29compare(other[, align_axis, keep_shape, …])Compare to another Series and show the differences.
30convert_dtypes([infer_objects, …])Convert columns to best possible dtypes using dtypes supporting pd.NA.
31copy([deep])Make a copy of this object’s indices and data.
32corr(other[, method, min_periods])Compute correlation with other Series, excluding missing values.
33count([level])Return number of non-NA/null observations in the Series.
34cov(other[, min_periods, ddof])Compute covariance with Series, excluding missing values.
35cummax([axis, skipna])Return cumulative maximum over a DataFrame or Series axis.
36cummin([axis, skipna])Return cumulative minimum over a DataFrame or Series axis.
37cumprod([axis, skipna])Return cumulative product over a DataFrame or Series axis.
38cumsum([axis, skipna])Return cumulative sum over a DataFrame or Series axis.
39describe([percentiles, include, exclude, …])Generate descriptive statistics.
40diff([periods])First discrete difference of element.
41div(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
42divide(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
43divmod(other[, level, fill_value, axis])Return Integer division and modulo of series and other, element-wise (binary operator divmod).
44dot(other)Compute the dot product between the Series and the columns of other.
45drop([labels, axis, index, columns, level, …])Return Series with specified index labels removed.
46drop_duplicates([keep, inplace])Return Series with duplicate values removed.
47droplevel(level[, axis])Return DataFrame with requested index / column level(s) removed.
48dropna([axis, inplace, how])Return a new Series with missing values removed.
49dtalias of pandas.core.indexes.accessors.CombinedDatetimelikeProperties
50duplicated([keep])Indicate duplicate Series values.
51eq(other[, level, fill_value, axis])Return Equal to of series and other, element-wise (binary operator eq).
52equals(other)Test whether two objects contain the same elements.
53ewm([com, span, halflife, alpha, …])Provide exponential weighted (EW) functions.
54expanding([min_periods, center, axis])Provide expanding transformations.
55explode([ignore_index])Transform each element of a list-like to a row.
56factorize([sort, na_sentinel])Encode the object as an enumerated type or categorical variable.
57ffill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='ffill'.
58fillna([value, method, axis, inplace, …])Fill NA/NaN values using the specified method.
59filter([items, like, regex, axis])Subset the dataframe rows or columns according to the specified index labels.
60first(offset)Select initial periods of time series data based on a date offset.
61first_valid_index()Return index for first non-NA/null value.
62floordiv(other[, level, fill_value, axis])Return Integer division of series and other, element-wise (binary operator floordiv).
63ge(other[, level, fill_value, axis])Return Greater than or equal to of series and other, element-wise (binary operator ge).
64get(key[, default])Get item from object for given key (ex: DataFrame column).
65groupby([by, axis, level, as_index, sort, …])Group Series using a mapper or by a Series of columns.
66gt(other[, level, fill_value, axis])Return Greater than of series and other, element-wise (binary operator gt).
67head([n])Return the first n rows.
68hist([by, ax, grid, xlabelsize, xrot, …])Draw histogram of the input series using matplotlib.
69idxmax([axis, skipna])Return the row label of the maximum value.
70idxmin([axis, skipna])Return the row label of the minimum value.
71infer_objects()Attempt to infer better dtypes for object columns.
72interpolate([method, axis, limit, inplace, …])Fill NaN values using an interpolation method.
73isin(values)Whether elements in Series are contained in values.
74isna()Detect missing values.
75isnull()Detect missing values.
76item()Return the first element of the underlying data as a Python scalar.
77items()Lazily iterate over (index, value) tuples.
78iteritems()Lazily iterate over (index, value) tuples.
79keys()Return alias for index.
80kurt([axis, skipna, level, numeric_only])Return unbiased kurtosis over requested axis.
81kurtosis([axis, skipna, level, numeric_only])Return unbiased kurtosis over requested axis.
82last(offset)Select final periods of time series data based on a date offset.
83last_valid_index()Return index for last non-NA/null value.
84le(other[, level, fill_value, axis])Return Less than or equal to of series and other, element-wise (binary operator le).
85lt(other[, level, fill_value, axis])Return Less than of series and other, element-wise (binary operator lt).
86mad([axis, skipna, level])Return the mean absolute deviation of the values over the requested axis.
87map(arg[, na_action])Map values of Series according to input correspondence.
88mask(cond[, other, inplace, axis, level, …])Replace values where the condition is True.
89max([axis, skipna, level, numeric_only])Return the maximum of the values over the requested axis.
90mean([axis, skipna, level, numeric_only])Return the mean of the values over the requested axis.
91median([axis, skipna, level, numeric_only])Return the median of the values over the requested axis.
92memory_usage([index, deep])Return the memory usage of the Series.
93min([axis, skipna, level, numeric_only])Return the minimum of the values over the requested axis.
94mod(other[, level, fill_value, axis])Return Modulo of series and other, element-wise (binary operator mod).
95mode([dropna])Return the mode(s) of the Series.
96mul(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator mul).
97multiply(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator mul).
98ne(other[, level, fill_value, axis])Return Not equal to of series and other, element-wise (binary operator ne).
99nlargest([n, keep])Return the largest n elements.
100notna()Detect existing (non-missing) values.
101notnull()Detect existing (non-missing) values.
102nsmallest([n, keep])Return the smallest n elements.
103nunique([dropna])Return number of unique elements in the object.
104pad([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='ffill'.
105pct_change([periods, fill_method, limit, freq])Percentage change between the current and a prior element.
106pipe(func, *args, **kwargs)Apply func(self, *args, **kwargs).
107plotalias of pandas.plotting._core.PlotAccessor
108pop(item)Return item and drops from series.
109pow(other[, level, fill_value, axis])Return Exponential power of series and other, element-wise (binary operator pow).
110prod([axis, skipna, level, numeric_only, …])Return the product of the values over the requested axis.
111product([axis, skipna, level, numeric_only, …])Return the product of the values over the requested axis.
112quantile([q, interpolation])Return value at the given quantile.
113radd(other[, level, fill_value, axis])Return Addition of series and other, element-wise (binary operator radd).
114rank([axis, method, numeric_only, …])Compute numerical data ranks (1 through n) along axis.
115ravel([order])Return the flattened underlying data as an ndarray.
116rdiv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator rtruediv).
117rdivmod(other[, level, fill_value, axis])Return Integer division and modulo of series and other, element-wise (binary operator rdivmod).
118reindex([index])Conform Series to new index with optional filling logic.
119reindex_like(other[, method, copy, limit, …])Return an object with matching indices as other object.
120rename([index, axis, copy, inplace, level, …])Alter Series index labels or name.
121rename_axis([mapper, index, columns, axis, …])Set the name of the axis for the index or columns.
122reorder_levels(order)Rearrange index levels using input order.
123repeat(repeats[, axis])Repeat elements of a Series.
124replace([to_replace, value, inplace, limit, …])Replace values given in to_replace with value.
125resample(rule[, axis, closed, label, …])Resample time-series data.
126reset_index([level, drop, name, inplace])Generate a new DataFrame or Series with the index reset.
127rfloordiv(other[, level, fill_value, axis])Return Integer division of series and other, element-wise (binary operator rfloordiv).
128rmod(other[, level, fill_value, axis])Return Modulo of series and other, element-wise (binary operator rmod).
129rmul(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator rmul).
130rolling(window[, min_periods, center, …])Provide rolling window calculations.
131round([decimals])Round each value in a Series to the given number of decimals.
132rpow(other[, level, fill_value, axis])Return Exponential power of series and other, element-wise (binary operator rpow).
133rsub(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator rsub).
134rtruediv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator rtruediv).
135sample([n, frac, replace, weights, …])Return a random sample of items from an axis of object.
136searchsorted(value[, side, sorter])Find indices where elements should be inserted to maintain order.
137sem([axis, skipna, level, ddof, numeric_only])Return unbiased standard error of the mean over requested axis.
138set_axis(labels[, axis, inplace])Assign desired index to given axis.
139set_flags(*[, copy, allows_duplicate_labels])Return a new object with updated flags.
140shift([periods, freq, axis, fill_value])Shift index by desired number of periods with an optional time freq.
141skew([axis, skipna, level, numeric_only])Return unbiased skew over requested axis.
142slice_shift([periods, axis])(DEPRECATED) Equivalent to shift without copying data.
143sort_index([axis, level, ascending, …])Sort Series by index labels.
144sort_values([axis, ascending, inplace, …])Sort by the values.
145sparsealias of pandas.core.arrays.sparse.accessor.SparseAccessor
146squeeze([axis])Squeeze 1 dimensional axis objects into scalars.
147std([axis, skipna, level, ddof, numeric_only])Return sample standard deviation over requested axis.
148stralias of pandas.core.strings.accessor.StringMethods
149sub(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator sub).
150subtract(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator sub).
151sum([axis, skipna, level, numeric_only, …])Return the sum of the values over the requested axis.
152swapaxes(axis1, axis2[, copy])Interchange axes and swap values axes appropriately.
153swaplevel([i, j, copy])Swap levels i and j in a MultiIndex.
154tail([n])Return the last n rows.
155take(indices[, axis, is_copy])Return the elements in the given positional indices along an axis.
156to_clipboard([excel, sep])Copy object to the system clipboard.
157to_csv([path_or_buf, sep, na_rep, …])Write object to a comma-separated values (csv) file.
158to_dict([into])Convert Series to {label -> value} dict or dict-like object.
159to_excel(excel_writer[, sheet_name, na_rep, …])Write object to an Excel sheet.
160to_frame([name])Convert Series to DataFrame.
161to_hdf(path_or_buf, key[, mode, complevel, …])Write the contained data to an HDF5 file using HDFStore.
162to_json([path_or_buf, orient, date_format, …])Convert the object to a JSON string.
163to_latex([buf, columns, col_space, header, …])Render object to a LaTeX tabular, longtable, or nested table/tabular.
164to_list()Return a list of the values.
165to_markdown([buf, mode, index, storage_options])Print Series in Markdown-friendly format.
166to_numpy([dtype, copy, na_value])A NumPy ndarray representing the values in this Series or Index.
167to_period([freq, copy])Convert Series from DatetimeIndex to PeriodIndex.
168to_pickle(path[, compression, protocol, …])Pickle (serialize) object to file.
169to_sql(name, con[, schema, if_exists, …])Write records stored in a DataFrame to a SQL database.
170to_string([buf, na_rep, float_format, …])Render a string representation of the Series.
171to_timestamp([freq, how, copy])Cast to DatetimeIndex of Timestamps, at beginning of period.
172to_xarray()Return an xarray object from the pandas object.
173tolist()Return a list of the values.
174transform(func[, axis])Call func on self producing a Series with transformed values.
175transpose(*args, **kwargs)Return the transpose, which is by definition self.
176truediv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
177truncate([before, after, axis, copy])Truncate a Series or DataFrame before and after some index value.
178tshift([periods, freq, axis])(DEPRECATED) Shift the time index, using the index’s frequency if available.
179tz_convert(tz[, axis, level, copy])Convert tz-aware axis to target time zone.
180tz_localize(tz[, axis, level, copy, …])Localize tz-naive index of a Series or DataFrame to target time zone.
181unique()Return unique values of Series object.
182unstack([level, fill_value])Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
183update(other)Modify Series in place using values from passed Series.
184value_counts([normalize, sort, ascending, …])Return a Series containing counts of unique values.
185var([axis, skipna, level, ddof, numeric_only])Return unbiased variance over requested axis.
186view([dtype])Create a new view of the Series.
187where(cond[, other, inplace, axis, level, …])Replace values where the condition is False.
188xs(key[, axis, level, drop_level])Return cross-section from the Series/DataFrame.

1.pandas.Series.add

Series.add(otherlevel=Nonefill_value=Noneaxis=0)[source]

Return Addition of series and other, element-wise (binary operator add).

Equivalent to series + other, but with support to substitute a fill_value for missing data in either one of the inputs.ParametersotherSeries or scalar valuefill_valueNone or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.levelint or name

Broadcast across a level, matching Index values on the passed MultiIndex level.ReturnsSeries

The result of the operation.

See alsoSeries.radd

Reverse of the Addition operator, see Python documentation for more details.

Examples

>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.add(b, fill_value=0)
a    2.0
b    1.0
c    1.0
d    1.0
e    NaN
dtype: float64

2.pandas.Series.add

Series.add(otherlevel=Nonefill_value=Noneaxis=0)[source]

Return Addition of series and other, element-wise (binary operator add).

Equivalent to series + other, but with support to substitute a fill_value for missing data in either one of the inputs.ParametersotherSeries or scalar valuefill_valueNone or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.levelint or name

Broadcast across a level, matching Index values on the passed MultiIndex level.ReturnsSeries

The result of the operation.

See alsoSeries.radd

Reverse of the Addition operator, see Python documentation for more details.

Examples

>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.add(b, fill_value=0)
a    2.0
b    1.0
c    1.0
d    1.0
e    NaN
dtype: float64

3.pandas.Series.add_prefix

Series.add_prefix(prefix)[source]

Prefix labels with string prefix.

For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed.Parametersprefixstr

The string to add before each label.ReturnsSeries or DataFrame

New Series or DataFrame with updated labels.

See alsoSeries.add_suffix

Suffix row labels with string suffix.DataFrame.add_suffix

Suffix column labels with string suffix.

Examples

>>> s = pd.Series([1, 2, 3, 4])
>>> s
0    1
1    2
2    3
3    4
dtype: int64
>>> s.add_prefix('item_')
item_0    1
item_1    2
item_2    3
item_3    4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
   A  B
0  1  3
1  2  4
2  3  5
3  4  6
>>> df.add_prefix('col_')
     col_A  col_B
0       1       3
1       2       4
2       3       5
3       4       6

4.pandas.Series.add_suffix

Series.add_suffix(suffix)[source]

Suffix labels with string suffix.

For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed.Parameterssuffixstr

The string to add after each label.ReturnsSeries or DataFrame

New Series or DataFrame with updated labels.

See alsoSeries.add_prefix

Prefix row labels with string prefix.DataFrame.add_prefix

Prefix column labels with string prefix.

Examples

>>> s = pd.Series([1, 2, 3, 4])
>>> s
0    1
1    2
2    3
3    4
dtype: int64
>>> s.add_suffix('_item')
0_item    1
1_item    2
2_item    3
3_item    4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
   A  B
0  1  3
1  2  4
2  3  5
3  4  6
>>> df.add_suffix('_col')
     A_col  B_col
0       1       3
1       2       4
2       3       5
3       4       6



XML Interview Questions And Answers

Q #1) What does XML stands for?

Answer: XML stands for Extensible Markup Language.

Q #2) What is XML used for?

Answer: XML is a tool that is used to store and transfer data.

Q #3) Is XML format or content-driven?

Answer: XML is content-driven.

Q #4) Does XML support user-defined tags?

Answer: Yes, the users can create their own tags in XML.

Q #5) What is XML declaration tag?

Answer: <? XML version = “1.0” encoding = “UFT-8”? >

Q #6) Can XML be used for multimedia purpose?

Answer: Yes, XML can be used for multimedia purposes by using SVG and SMIL.

Q #7) What does SVG stand for and what is it used for?

Answer: SVG stands for Scalable Vector Graphics. It is an XML language that is used to display animations, images, graphics, and 2D from the XML code. Vector mathematical formulas are used here to render the content.

Q #8) What does SMIL stand for and what is it used for?

Answer: SMIL stands for Synchronized Multimedia Integration Language. It is an XML language that is used to integrate images, text, and other media for a presentation.

Q #9) What is the difference between XML and HTML?

Answer: 

XMLHTML
XML consists of user defined tags.HTML consists of pre-defined tags.
XML is used to store and transform data.HTML is used for designing a web page.
XML is content driven.HTML is format driven.
XML is case sensitive.HTML is not case sensitive.
XML requires end tag for well formatted document.HTML does not require an end tag.

Q #10) What are the benefits of XML?

Answer: The benefits of XML are as follows:

  • Simplicity: XML is simple to read and understand.
  • Availability: XML can be created using any text editor.
  • Flexibility: XML doesn’t have any fixed tags, hence user-defined tags can also be used.

Q #11) What importance does XSLT hold in XML?

Answer: XSLT stands for Extensible Style sheet Language Transformation. It is used to transform an XML document to HTML before it is displayed to any browser.

Q #12) What is XQuery?

Answer: XQuery is used to fetch data from the XML file, which is the SQL database.

Q #13) What is Xlink in XML?

Answer: Xlink used in XML files, are the standard way of creating hyperlinks in XML files.

Q #14) What is Xpointer in XML?

Answer: Xpointer in XML allows hyperlinks to point to more specific parts of the XML documents or files.

Q #15) What is XML signature/encryption?

Answer: It defines the processing rules and syntax for encrypting and creating digital signatures on XML.

Q #16) What is DTD in XML?

Answer: DTD stands for Document Type Definition, which describes a document written in XML. XML declaration syntax is defined in DTD. Naming convention rules of different types of elements are also defined in DTD.

Q #17) What is DOM? What is it used for?

Answer: DOM stands for the Document Object Model. It is an API, Application Programming Interface that allows navigation through objects. Documents are treated as objects. DOM documents are generated by the user or created by a parser.

Q #18) What is the main disadvantage of DOM?

Answer: The main disadvantage is that a large portion of memory is consumed by DOM.

Q #19) What does SOAP stand for?

Answer: SOAP is a Simple Object Access Protocol.

Q #20) What is the relation of SOAP with XML?

Answer: SOAP uses XML to define a protocol for the exchange of information in distributed computing environments.

Q #21) What are the three components in SOAP?

Answer: It consists of an envelope, a set of encoding rules, and a convention for representing remote procedure calls.

Q #22) What is XML parser function?

Answer: It is used to convert an XML file or document into the XML DOM object which is usually written in JavaScript.

Q #23) What is an XML schema?

Answer: XML schema provides definition of an XML document.

It comprises of:

  • Attributes and elements.
  • Child elements.
  • The data type of elements.
  • Order of elements and attributes.

Q #24) What is CDATA in XML?

Answer: CDATA stands for character data. Characters like ‘<’ and ‘>’ are not allowed in XML. CDATA starts with <! CDATA [“and end with”]>. CDATA is an unparsed character data that cannot be parsed by the XML parser.

Q #25) How are comments used in XML?

Answer: Comments are displayed as <!—comment–> . It is similar to HTML. It can be used for a single line or multiple lines.

Q #26) What is the usage of XML in development?

Answer: XML has multiple usages as shown below:

  • XML is used for flat files and databases.
  • It is used to store data and transport data on the Internet.
  • It can generate different dynamic data using style sheets.
  • XML is used to develop database-driven websites.
  • It is used to store data for eCommerce websites.

Q #27) What are the disadvantages of XML?

Answer: Disadvantages of XML include:

  • XML is just a text file if attributes and elements are not closed and defined properly.
  • Overlapping markup is not allowed.

Q #28) What do XML editors check?

Answer: The XML editors check are as follows:

  • XML against schema
  • XML Syntax color code
  • XML against DTD
  • XML standard open and close tags

Q #29) What is Diffgram in XML?

Answer: Diffgram is an XML format that is used to find the current and original versions of the XML document.

Q #30) What is XML Parser?

Answer: XML parser is a piece of software, which checks for a well-defined format and performs validation of document. It also allows us to read, create, and modify an existing XML document.

Q #31) How to connect XML with the database?

Answer: XML import and export modules are used to connect XML applications with databases. There has to be a 1:1 match between the field name of element type and the database table in DTD or XML schema. While in some cases little programming is required to establish the desired match.

Q #32) How to run an XML file?

Answer: XML is not a programming language. It cannot be run or executed. It can be viewed or displayed on the browser or using the XML editor.

Q #33) Describe XPath.

Answer: XPath can be described as follows:

  1. XPath is a W3C recommendation.
  2. It is the syntax for defining parts of an XML document.
  3. It uses path expressions to navigate in the XML documents.
  4. XPath contains a standard function library.
  5. XPath is a major element of the XSLT standard.
  6. It is used to navigate through attributes and elements in an XML document.

Q #34) Provide an example of XML.

Answer:

<? XMLversion=”1.0” encoding = “UTF-8”?><FurnitureStore><Furniturecategory=”Table”><Titlelang=”en”> Sale for today</Title><Type> Laptop table</Type><Year>2008</Year><Price>500</Price></FurnitureStore>

Q #35) What are well-formed XML documents?

Answer: Well-formed XML documents have the following features:

  1. An XML document must have a root element.
  2. XML tags are case sensitive.
  3. XML elements should be properly nested.
  4. XML values should be properly quoted.
  5. XML tags should be closed properly.

Q #36) What are XML attributes? Explain with an example.

Answer: XML attribute values should always be quoted. Single or double quotes can be used in XML.

For example:

  • <Person degree = “PHD”>
  • <Person name = ‘Jacob’>

Q #37) Write a code for XML attribute and element.

Answer:

<Personlocation = “India”><Statename>Maharashtra</Statename><Cityname>Mumbai</Cityname></Person>     <Person>     <Location> India </Location>     <Statename>Maharashtra</Statename>     <Cityname>Mumbai</Cityname>     </Person>

In the first element, location is an attribute. In last, location is an element. The user can choose the attribute or element.

Q #38) Can XML files be viewed in browsers?

Answer: Yes, the XML file can be viewed in all known browsers. They are not displayed as HTML pages.

Q #39) What is XML Httprequest? What are its advantages?

Answer: All modern browsers have a built-in XML Httprequest object to request for data from a server.

Its advantages are as follows:

  • Updating a web page without reloading the page.
  • Request data from a server
  • Receive data from a server after the page has been loaded.
  • Send data to a server in the background.

Q #40) Example of HttpRequest.

Answer:

var xhttp= newXML Httprequest();Xhttp.onreadystatechange=function();{ If this.readystate==4&& this.status==200)        { Action to be performed when document is ready;Document.getelementbyID(“Demo”)Innerhtml=xhttp.responseText;}};

Q #41) What is XML element?

Answer: The XML element contains start tag, end tag, and values.

For Example:

  • <City&gt; Pune </City>
  • <Price> 400.00 </Price>

XML element with no value is said to be empty like <element> </element>

Q #42) What are XML naming rules?

Answer: Naming rules are:

  • Element names must start with a letter or underscore.
  • Element names are case sensitive.
  • Element names cannot start with the letters XML.
  • Element names can contain letters, digits, hyphens, underscore, and periods.
  • Element names cannot contain spaces.

Q #43) What is SAX in XML?

Answer: SAX stands for Simple API for XML. It is a sequential access parser.

It provides a mechanism of reading data from an XML document. It is said to be an alternative to DOM. DOM operates on the documents as a whole, SAX parsers operate on each piece of the XML document sequentially.

SAX consumes less memory. It cannot be used to write an XML document.

Q #44) What is XSNL?

Answer: XSNL stands for XML Search Neutral Language. This language acts between the meta-search interface and the targeted system.

Q #45) What is the difference between a simple element and a complex element?

Answer: Simple elements cannot be left empty. It contains fewer attributes, child elements, etc. Simple elements are text-based elements. Complex elements can contain sub-elements, empty elements, etc. The complex element can hold multiple attributes and elements.

Shell Scripting break & continue

In this chapter, we will discuss shell loop control in Unix. So far you have looked at creating loops and working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of the loop.

In this chapter, we will learn the following two statements that are used to control shell loops−

  • The break statement
  • The continue statement

The infinite Loop

All the loops have a limited life and they come out once the condition is false or true depending on the loop.

A loop may continue forever if the required condition is not met. A loop that executes forever without terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.

Example

Here is a simple example that uses the while loop to display the numbers zero to nine −

#!/bin/sh

a=10

until [ $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

This loop continues forever because a is always greater than or equal to 10 and it is never less than 10.

The break Statement

The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then steps down to the code following the end of the loop.

Syntax

The following break statement is used to come out of a loop −

break

The break command can also be used to exit from a nested loop using this format −

break n

Here n specifies the nth enclosing loop to the exit from.

Example

Here is a simple example that shows that the loop terminates as soon as a becomes 5 −

#!/bin/sh

a=0

while [ $a -lt 10 ]
do
   echo $a
   if [ $a -eq 5 ]
   then
      break
   fi
   a=`expr $a + 1`
done

Upon execution, you will receive the following result −

0
1
2
3
4
5

Here is a simple example of a nested for loop. This script breaks out of both loops if var1 equals 2 and var2 equals 0 

#!/bin/sh

for var1 in 1 2 3
do
   for var2 in 0 5
   do
      if [ $var1 -eq 2 -a $var2 -eq 0 ]
      then
         break 2
      else
         echo "$var1 $var2"
      fi
   done
done

Upon execution, you will receive the following result. In the inner loop, you have a break command with argument 2. This indicates that if a condition is met you should break out of the outer loop and ultimately from the inner loop as well.

1 0
1 5

The continue statement

The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop.

This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop.

Syntax

continue

Like with the break statement, an integer argument can be given to the continue command to skip commands from nested loops.

continue n

Here n specifies the nth enclosing loop to continue from.

Example

The following loop makes use of the continue statement which returns from the continue statement and starts processing the next statement

#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "Number is an even number!!"
      continue
   fi
   echo "Found odd number"
done

Upon execution, you will receive the following result −

Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number

Shell Scripting While Loops

In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −

  • The while loop
  • The for loop
  • The until loop
  • The select loop

You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.

Once you have good programming practice you will gain the expertise and thereby, start using appropriate loops based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++, PERL, etc.

Nesting Loops

All the loops support the nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to an unlimited number of times based on your requirement.

Here is an example of a nesting while loop. The other loops can be nested based on the programming requirement in a similar way −

Nesting while Loops

It is possible to use a while loop as part of the body of another while loop.

Syntax

while command1 ; # this is loop1, the outer loop
do
   Statement(s) to be executed if command1 is true

   while command2 ; # this is loop2, the inner loop
   do
      Statement(s) to be executed if command2 is true
   done

   Statement(s) to be executed if command1 is true
done

Example

Here is a simple example of loop nesting. Let’s add another countdown loop inside the loop that you used to count to nine −

#!/bin/sh

a=0
while [ "$a" -lt 10 ]    # this is loop1
do
   b="$a"
   while [ "$b" -ge 0 ]  # this is loop2
   do
      echo -n "$b "
      b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done

This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.

0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

Robot Framework Variables

Different types of variables

The variable name consists of the type identifier ($@&%), curly braces ({}) and the variable name between the braces. Use capital letters with global variables in the *** Variables *** section (${SEARCH_URL}). Use small letters with local variables that are only available in certain tasks or user keywords (${search_url}).

  • Scalar: ${var}
  • List: @{var}
  • Dictionary: &{var}
  • Environment: %{var}

Assigning variables

*** Settings ***
Documentation     Assigning variables.
Library           Collections
# You can create variables in a Python file and import them:
#Variables        variables.py

*** Keywords ***
What Does The Cat Say
    [Return]    Meow!

*** Tasks ***
Assign variables
    ${string}    Set Variable    Hello, world!    # ${string} = Hello, world!
    @{list}    Create List    a    b    c    # @{list} = [ a | b | c ]
    &{dict}    Create Dictionary    key1=val1    key2=val2    # &{dict} = { key1=val1 | key2=val2 }
    ${a}    ${b}    ${c}    Create List    a    b    c    # ${a} = a, ${b} = b, ${c} = c
    ${cat_says}    What Does The Cat Say    # ${cat_says} = Meow!
    ${evaluate}    Evaluate    datetime.date.today()    # ${evaluate} = 2020-09-08
    ${inline_evaluation}
    ...    Set Variable
    ...    ${{datetime.date.today() + datetime.timedelta(1)}}    # ${inline_evaluation} = 2020-09-09

Expressions are evaluated using Python’s eval function. All Python built-in functions are available. All unrecognized Python variables are considered to be modules that are automatically imported. It is possible to use all available Python modules, including the standard modules and any installed third party modules.

Built-in variables

VariableDescription
${CURDIR}The path to the task data file directory.
${EMPTY}Like the ${SPACE}, but without the space. Used to pass empty arguments.
${EXECDIR}The path to the task execution directory.
${False}Boolean False.
${None}Python None.
${null}Java null.
${SPACE}ASCII space (\x20).
${TEMPDIR}The path to the temporary directory.
${True}Boolean True.
${/}The directory path separator. / in UNIX-like systems and \ in Windows.
${:}The path element separator. : in UNIX-like systems and ; in Windows.
${\n}The line separator. \n in UNIX-like systems and \r\n in Windows.

Runtime variables

VariableDescription
${DEBUG_FILE}Debug file.
${KEYWORD_MESSAGE}The error message of the current keyword.
${KEYWORD_STATUS}The status of the current keyword, either PASS or FAIL.
${LOG_FILE}Logfile.
${LOG_LEVEL}Log level
${OUTPUT_DIR}Output directory.
${OUTPUT_FILE}Output file.
${PREV_TEST_MESSAGE}The error message of the previous task.
${PREV_TEST_NAME}The name of the previous task, or an empty string if no tasks have been executed yet.
${PREV_TEST_STATUS}The status of the previous task: PASSFAIL, or an empty string when no tasks have been executed.
${REPORT_FILE}Report file.
${SUITE_DOCUMENTATION}The documentation of the current task suite.
${SUITE_MESSAGE}The full message of the current task suite, including statistics.
&{SUITE_METADATA}The metadata of the current task suite.
${SUITE_NAME}The full name of the current task suite.
${SUITE_SOURCE}The path to the suite file or directory.
${SUITE_STATUS}The status of the current task suite, either PASS or FAIL.
${TEST_DOCUMENTATION}The documentation of the current task.
${TEST_MESSAGE}The message of the current task.
${TEST_NAME}The name of the current task.
${TEST_STATUS}The status of the current task, either PASS or FAIL.
@{TEST_TAGS}The tags of the current task are in alphabetical order.

Why Should We Use Robot Framework?

Although we can automate the Functionality through Many Automation Framework Like Selenium, Appium, Robotium, UFT, etc.., we can not take the leverage of the automation tools to make a test Driven Program. In this post we will learn about Why Should We Use Robot Framework?

Robot Framework is a generic test automation framework for acceptance testing and acceptance test-driven development (ATDD). It has easy-to-use tabular test data syntax and it utilizes the keyword-driven testing approach. Its testing capabilities can be extended by test libraries implemented either with Python or Java, and users can create new higher-level keywords from existing ones using the same syntax that is used for creating test cases.

The Robot Framework project is hosted on GitHub where you can find further documentation, source code, and an issue tracker. Downloads are hosted at PyPI. The framework has a rich ecosystem around it consisting of various generic test libraries and tools that are developed as separate projects.

Robot Framework is an operating system and application-independent. The core framework is implemented using Python and runs also on Jython (JVM) and IronPython (.NET).

Robot Framework itself is open-source software released under Apache License 2.0, and most of the libraries and tools in the ecosystem are also open source. The framework was initially developed at Nokia Networks and it is nowadays sponsored by Robot Framework Foundation.

  • Enables easy-to-use tabular syntax for creating test cases in a uniform way.
  • Provides the ability to create reusable higher-level keywords from the existing keywords.
  • Provides easy-to-read result reports and logs in HTML format.
  • Is platform and application-independent.
  • Provides a simple library API for creating customized test libraries that can be implemented natively with Python.
  • Provides a command-line interface and XML-based output files for integration into existing build infrastructure (continuous integration systems).
  • Provides support for testing web applications, rest APIs, mobile applications, running processes, connecting to remote systems via Telnet or SSH, and so on.
  • Supports creating data-driven test cases.
  • Has built-in support for variables, practical particularly for testing in different environments.
  • Provides tagging to categorize and select test cases to be executed.
  • Enables easy integration with source control: test suites are just files and directories that can be versioned with the production code.
  • Provides test-case and test-suite-level setup and teardown.
  • The modular architecture supports creating tests even for applications with several diverse interfaces.

If you are thinking to automate a System Which Needs The Following Library Find the Details Functionalities From the Bellow Post.

Difference Between MVC and MVT Patterns

Are you a web developer, who does create amazing websites but doesn’t know much about all the theoretical concepts like software design patterns, and all? Today, let’s understand the two basic types of software development patterns, primarily used in web development frameworks.

Let’s see what MVC (Model View Controller) and MVT (Model View Template) design patterns are and the differences between them. MVC and MVT patterns allow developers to change the visual part of an app and the business logic part separately.

If you have come here to know the differences between these patterns, and you aren’t patient enough to read the entire article, here is a quick answer for you.

What is the difference between MVC and MVT? In MVC, programmers need to write all the control-specific code whereas, in MVT, the framework itself handles the controller part. There are also some differences when it comes to the presentation of data to the user.

I know you won’t understand much from this quick answer if you are a beginner at these concepts. So, let’s deep dive into both design patterns and understand them.

Model View Controller (MVC)

This design pattern breaks down software into three major components: the model, the view, and the controller. Each of these components has independent jobs, and they can work separately without affecting each other.

Let’s see the role of each component in MVC.

  • Model – The model represents an object carrying data. It can also have logic to update the controller if its data changes. But, it contains no logic describing how to present the data to a user.
  • View – View represents the visualization of the data that the model contains. The view knows how to access the model’s data, but it does not know what this data means.
  • Controller – The controller acts on both model and view. It controls the data flow into the model object and updates the view whenever data changes. It keeps the view and model separate.

This is done to separate internal representations of information from the ways information is presented to and accepted by the user.

The main advantage of using a design pattern like this is that multiple developers can work simultaneously on each of these specific components.

The best thing about MVC is that each component has a particular purpose. The model part holds the data of your app, the View makes your app look pretty, and the Controller controls how your app functions. Any web application is structured, keeping these three core components in mind.

MVC helps to organize the core functions of your code neatly. It will be easy to make any changes to your app later as you will be able to identify which code does what.

Also, if you’re using an MVC framework, then it will be easy to share your code with other developers. After the initial learning hurdle, everything becomes easy when you use a framework.

MVC reduces complexities in designing web apps, primarily large applications, by keeping the code and workflow structured. It makes the overall code simple to maintain, test, debug, and reuse.

You can watch the following video to learn more about MVC.

Model View Template (MVT) 

The Model-View-Template (MVT) is slightly different from MVC. It is a collection of three essential components Model, View, and Template. These three layers are responsible for different things, and we use them independently. Django is a popular web development framework that uses the MVT design pattern. 

The main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is an HTML file mixed with Django Template Language (DTL).

Here is a simple diagram that shows the MVT architecture in Django:

Model View Template (MVT) architecture in Django

So, in the case of Django, let’s see what each component is doing:

  • The model helps to handle the database. It is a data access layer, which contains the required fields and behaviors of the data you’re storing. There’s hardly an application without a database. A model is a Python class, and it does not know anything about other Django layers.  Models help developers to create, read, update, and delete objects (CRUD operations) in the original database. Also, they hold business logic, custom methods, properties, and other things related to data manipulation.
  • The view is used to execute the business logic and interact with a model to carry data and render a template. The view fetches data from a model. Then, it either gives each template access to specific data to be displayed, or it processes data beforehand. It accepts HTTP requests, applies business logic provided by Python classes and methods, and provides HTTP responses to the client requests.
  • The template is a presentation layer that handles the User Interface part completely. These are files with HTML code, which is used to render data. The contents of these files can be static or dynamic. A template is used only to present data since there’s no business logic in it.

In Django, the view describes which data is presented, but a view normally delegates to a template, which describes how the data is presented.

The developer provides the model, the view, and the template, then maps it to a URL, and Django does the magic, to serve it to the user.

In short, a web application has data, layout, and logic. The model will work with the data, the view will work with the logic, and the template will work with the layout.

If you’re familiar with other MVC Web-development frameworks, you may consider Django views to be the controllers and Django templates to be the views.

In Django, the view describes the data that gets presented to the user; it’s not necessarily how the data looks, but which data gets presented.

The view describes which data you see, not how you see it. It’s a subtle distinction. Also, it’s sensible to separate content from presentation – which is where templates come in.

The controller is the framework itself, the machinery that sends a request to the appropriate view, according to the Django URL configuration. [Source].

At the end of the day, it comes down to getting stuff done. Also, regardless of how things are named, Django gets stuff done most logically.

So, that’s all about the differences between MVC and MVT design patterns.

If you have any doubts regarding this, leave them in the comments section below. I’ll be happy to help you. Also, if you have any additional points to make regarding this topic, let me know in the comments.

If you’re looking to do your next project using the Django framework, I want you to check out this resource. I’ve written an article that lists out 12 Django Project Ideas that you can take and implement right away.

If this article was helpful, do share this article with your fellow programmers. I would appreciate it, and it will encourage me to create more useful tutorials like this.

Happy coding!

Special Symbols or Operators in Shell Scripting

In this post, we will learn how to use inbuild special symbols in the shell to make our code simple.
Let’s assume we have a file in the temp directory and we will use the inbuilt keyword to test the functionality.

We have 2 files in the Desktop

The ls command shows all the files in the current directory.

root@vps43086554:~/Desktop# ls
sample.sh sample.txt
root@vps43086554:~/Desktop#

Now will make a simple shell script sample.sh where we will write an if condition where the condition will check with the help of existing keywords.

if [ -e sample.txt ];
then echo “Inside if ture part”
fi

In the above the if condition we have written an if the condition where we have written -e and a file name.

File Operators

-e

Ture if file exists.
Menas it will check if the file exists in the directory then it will return true.

Prerequisite -Create 2 files sample.sh sample.txt

if [ -e sample.txt ];
then echo “Inside if ture part”
fi

Output-
root@vps43086554:~/Desktop# sh sample.sh
Inside if ture part
root@vps43086554:~/Desktop#

-d

True if the file is a directory.

Prerequisite- Create a folder named a folder.

Code to create a folder named as folder.

root@vps43086554:~/Desktop# mkdir folder
root@vps43086554:~/Desktop# ls
folder sample.sh sample.txt

Code to check the folder is exists or not.

if [ -e folder ];
then echo “Inside if ture part”
fi

Output

root@vps43086554:~/Desktop# sh sample.sh
Inside if ture part

-f

True if the file exists and the file is a regular file.

Prerequisite- Create an invalid file named non_normarl.gfd.

Code-

if [ -f non_normal.gfd ];
then echo “Inside if ture part”
fi
if [ -f sample.txt ];
then echo “Inside if ture part of valid file”
fi

root@vps43086554:~/Desktop# sh sample.sh
Inside if ture part of valid file

-r

True if the file is readable by you

-s

True if the file exists and is not empty.

-w

True if the file is writable by you.

-x

True if the file is executable by you.

String Operators

-z “String”

True if the string is empty

-n “String”

True if the file is not empty.

STRING1=STRING2

True id the strings are equal.

STRING1!=STRING2

True if the strings are not equal.

agr1 -eq arg2

True if arg1 is equal to arg2

agr1 -nq arg2

True if arg1 is not equal to arg2

arg1 -lt arg2

True if the arg1 is less than arg2

arg1 -le arg2

True if arg1 is less than or equal to arg2

arg1 -gt arg2

True if the arg1 is greater than arg2

arg1 -ge arg2

True if the arg1 is greater than or equal to arg2

Building an Executable Version of a C Program

.c file is your source code file while a .exe file is an executable file, which is obtained after you successfully compile the code.

For compilation you need compilers:

Open compiler writes a new C program, compile it using f9 and then run it. Once you run a program the .exe file is created under the output directory as set in the Options – Directories.

An executable file can be executed in two ways that are:

1) By typing the name of the executable file in the command prompt.

2) By double click on the application (executable file) in windows mode.

Hope this may help you.