Latest Web, Mobile technology, News & More Blogs

# Our Blogs

Dive into the latest insights from the IT industry, updates on disruptive technologies, and business aiding products.

Filter By Category

### Python Basics: Data types

Python is an object-oriented, interpreted programming language that is simple and easy to use that has significant applications in software development, web development, data science, and so on. The first thing you can learn in a programming language is its data types. In this article, we will explore the various data types of Python language.

Python has data types such as numbers, lists, tuple, string, set, and dictionary. We will discuss them one by one below.

Numbers

The first data type in this language is the number that has integers, float and complex data types defined as “int”, “float”, and “complex” classes. What differs integers from the float is the presence of decimal points in float. For example, 7 is an integer, and 7.0 is a floating variable. A complex data type consists of two parts, a real part, and an imaginary part. For example, x+iy is a complex number where x is the real part and y is the imaginary part. We can use two functions to determine the class to which a number belongs.

1. type() – return the type of class of a particular variable
2. isinstance()- checks whether the given variable belongs to a class or not.

For example,

x = 3
print(type(x))
print(type(3.0))

c = 2 + 5j
print(isinstance(c, complex))

Output

<class 'int'>
<class 'float'>
True

The length of an integer data type can be of anything but the float data type has its accuracy up to 15 decimal places and after that it is inaccurate.

The number system such as binary(base 2), octal(base 8), and hexadecimal(base 16) can be represented using a set of prefixes such as

• Binary – ‘0b’ or ‘0B’
• Octal – ‘0o’ or ‘0O’
• Hexadecimal – ‘0x’ or ‘0X’

The process of converting one data type into another is called type conversion. Automatic conversion happens for certain operations. For example, adding an integer and float will automatically result in aÂ float, as it implicitly converts the integer to float.

>>> 1.0 + 5
6.0

We can also explicitly convert a variable of one data type into another by calling some built-in python functions such as int(), float(), complex().

>>> int(2.2)
2
>>> int(-7.8)
-7
>>> float(9)
9.0

Decimal

When we want the most accurate calculations like financial calculations, where precision is so important, we can use decimal instead of float. It can be used by importing the decimal module.

For example,

The second print statement involving the use of a decimal module results in a number with more accurate precision.

Fractions

If we want to use fractions where the numerator and denominator both are integers, we can import the fraction module.

For example,

import fractions

print(fractions.Fraction(0.5))
print(fractions.Fraction(5,6))

Output

1/2
5/6

Math and Random

The math() and random() modules in python offer a wide range of calculations in trigonometry, logarithms, statistics, etc.

For example,

import math
import random

print(math.pi)
print(math.factorial(4))
print(random.randrange(1, 8))

Output

3.141592653589793
24
5

Lists

The list is one of the most used data types in python that stores a sequence of elements in it. We will discuss briefly how to create a list, how to access elements from it, indexing, and more.

List creation

A list can be created by,

list_name= [ ]

The elements contained inside the square brackets are called the items of a list. The list can be either empty, contains items of the same type, different types, or even a list that contains its items. That is, a list can be

list_name=[ ]
list_name=[ 1,2,3,4,5]
list_name=[1, apple, 2, red, 5.5]
list_name=[1, 2, [red, green, yellow], 3, 4, 5]

Accessing an element

The elements contained inside a list have an index associated with them. The indices start from 0 and should be integers. A list of size 6 (6 elements) has an index starting from 0 to 5. The elements can be accessed using their respective indices.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
print(color_list[0])
print(color_list [2])

Output

g
e

print(color_list [6]) //This throws an "IndexError" as we have used an index that is beyond the index range of this list

Negative Indexing

In python, lists are indexed with a negative index starting from the last item in the list.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
print(color_list[-1])
print(color_list[-2])
print(color_list[-3])
print(color_list[-4])
print(color_list[-5])

Output

n
e
e
r
g

List Slicing

A range of elements from a list in python can be accessed by using the “:” operator (slicing operator).

For example,

color_list = ['g', 'r', 'e', 'e', 'n']

print(color_list[2:4])
print(color_list[:-3])
print(color_list[3:])
print(color_list[:])

Output

['e', 'e', 'n']
['g', 'r']
['e', 'n']
['g', 'r', 'e', 'e', 'n']

Lists elements can be added or modified (mutable) by using the ” = ” operator.

For example,

color_list = ['g', 'r', 'e', 'e', 'n']
color_list[0] = b

print(color_list)

color_list[1:4]=['l', 'a', 'c', 'k']

print(color_list)

Output

['b', 'r', 'e', 'e', 'n']
['b', 'l', 'a', 'c', 'k']

We can add elements to the list by using append(),insert() and extend() methods.

For example,

num_list=[1,2,3,4,5]
num_list.append(6) //adds one element at the last
num_list.extend([7,8,9]) //adds a number of elements at the last
print(num_list)

Output

['1', '2', '3', '4', '5', '6', '7', '8', '9']

We can also concatenate two lists by using the ‘+’ operator and multiply to a certain number of times using the ‘*’ operator.

Deletion

Deletion can be performed by using the keywords del, or by using the functions such as remove(), pop(), or clear().

For example

mylist=['1', '2', '3', '4', 5', '6']

del mylist(2) //deletes the element at index 2
del mylist[1:3] //deletes the elements from index1 to 3
del mylist //deletes the entire list

mylist=['a', 'b, 'c', 'd', e', 'f']

mylist.remove('a') //removes the specified element 'a'
mylist.pop //removes the top most(last) element 'f'
mylist.clear() //removes the entire list

Some of the other methods that can be used with the lists are sort(), count(), reverse(), and copy().

Using the “in” keyword, we can check whether an element is present in a list or not and also can be used in list iterations.

Tuples

Tuples are similar to lists in python but they are immutable (cannot be modified).

They can be created by placing the elements inside the () and separated by commas.

For example,

mytuple = (1, 2, 3)

The elements inside the tuples can be of the same data type or different. The tuples can be created with or without a bracket.

Accessing the tuple elements is the same as the list elements. They can be accessed using indexing, negative indexing, and slicing.

For example,

mytuple = (1, 2, 3)

print(mytuple[0]) //1
print(mytuple[-1]) //3
print(mytuple[1:2]) //2,3

Changing the elements in tuples can be done using the concatenation operator and deletion is done by using the keyword del.

Other methods can also be performed using the count(), index(), and a keyword for membership testing and iteration.

The major advantage of using tuples over lists is, iteration in tuples is easier as they are immutable.

Strings

A sequence of Unicode characters that are converted into binary characters for manipulation is called the strings in python. This process of converting a character into a binary number is called encoding and the reverse process is called decoding.

String creation

Strings are the characters that are enclosed within the quotes (either single or double).

For example,

string_name= 'My String'

print(string_name)

Output

My String

Accessing the characters inside a string is the same as accessing the list of tuples. They can be accessed by indexing, negative indexing, or slicing.

For example,

string_name= 'MyString'

print('string= ', string_name)
print('string[0] = ', string_name[0])
print('string[-1] = ', string_name[-1])
print('string[1:5] = ', string_name[1:5])

Output

string= MyString
string[0]= M
string[-1]= g
string[1:5]= yStri

Like tuples, strings are also immutable. We cannot modify or delete a particular character from a string, but we can delete the entire string by using the del keyword.

Some of the other operations performed in strings are concatenate (+),Â Â multiply(*), enumerate(), len(), format(), lower(), upper(), join(), split(), find(),Â Â and replace()

For example,

string_name= 'MyString'

>>>string_name.lower()
'mystring'

>>>string_name.upper()
'MYSTRING'

>>>My String.split()
['My', 'String']

>>>' '.join(['My', 'String'])
'My String'

>>>'My String'.replace('String','NewString')
'My NewString

>>>str1 = 'Hello'
>>>str2 ='How are you?'
>>>print('str1 + str2 = ', str1 + str2)
'Hello How are you?'

>>>print('str1 * 2 =', str1 * 2)
str1*2= HelloHello

Sets

A set is also a mutable data type that consists of unordered unique (immutable) elements in it.

They are used to perform operations like union, intersection, symmetric difference, and more.

Sets can be created by using {} brackets or by calling the set() function which is in-built. Sets can have any number of elements inside it and they can be of either the same or different data types.

For example,

my_set = {1, 2, 3}
print(my_set)

Output

{1, 2, 3}

Empty curly braces may be interpreted as a dictionary in python, so if we want to create an empty, we can do that by using the set() function.

Since sets are unordered, there is no index associated with the elements of sets. So we can add or delete an element from a set by using the functions such as add(), update(), discard() and remove().

For example,

set_name = {1, 3}
print(set_name) //1,3

print(set_name) //1,2,3

set_name.update([2, 3, 4])
print(set_name) //1,2,3,4

Similarly, we can also use the pop() or clear() method to do the deletion operations.

Sets are used to perform operations like union, intersection, symmetric difference, and more.

For example,

X = {1, 2, 3, 4, 5}
Y = {4, 5, 6, 7, 8}

print(X | Y)
print(X & Y)
print(X ^ Y)

Output

{1,2,3,4,5,4,5,6,7,8}
{4,5}
{1,2,3,4,5,6,7,8}

There are many other built-in functions available to operate with sets. They are all(), any(), enumerate(), len(), max(), min(), sorted(), sum() and more.

There is a function called frozenset() using which can create immutable sets, cannot be changed once assigned.

For example,

X = frozenset([1, 2, 3, 4])

Dictionary

Dictionary is a data type that contains an unordered sequence of items in it and each of its elements is associated with a key/value pair.

A dictionary in python can be created by,

dict_name = {1: 'red', 2: 'green'}

Elements of a dictionary can be accessed by keys associated with them, like the indexes in lists and tuples. Dictionary elements can be accessed using the get() method.

Example:

dict_name = {1: 'red', 2: 'green'}

print(dict_name.get(2))

Output

green

A new addition to a dictionary is done by using the assignment (=) operator. If you are trying to assign a value for an already existing key, the value will get updated. Deletion from a dictionary is done by using methods such as pop(), popitem(), clear(), and del keyword.

There are some built-in functions available to use with the dictionaries. They areÂ Â all(), any(), len(), cmp(), sorted().

In this article, we have learned about the different data types such as numbers, lists, tuples, strings, sets, and dictionaries along with their methods of addition, updation, how to access the elements from them, and more.

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected]Â or see careers at Startxlabs.”

### 4 Most Common React Native Keyboard Issues

People’s most favorite platform for developing apps, React native involves handling texts through TextInput that uses the keyboard. To use TextInput, the keyboard should be popped up and occupy some space on the screen. However, you may face some issues with the keyboard while working on the TextInput. In this article, we will discuss some of the common React Native keyboard issues and how to solve them.

Issue 1 – Double-tap issue while the keyboard is already open

When you are trying to press some link, while the keyboard has been already opened, the button or link can’t be clicked on with a single click. It should be clicked twice to get opened. Because your first click will be taken for closing the keyboard and the second click will open the button or link. Sometimes, users may not be aware of this and think that the button is not working. It gives a bad user experience.

Solution

We can resolve this issue by using theÂ keyboardShouldPersistTaps=â€˜alwaysâ€™ property on the ScrollView or the Content part of your code. This property allows the link or button to respond on the first click itself.

Issue 2 – Problem with ScrollingÂ

If you want to scroll down to a series of pages, the already opened keyboard will not be closed automatically. It continues to stay there, which can cause discomfort for the user while scrolling. We have to close the keyboard each time manually.

Solution

This issue can be solved by using the keyboardDismissMode=’on-drag’ property on Scrollview and Content, which will make the keyboard to get disappear automatically on scrolling.

Read our article onÂ Why is React Native the best for Mobile App Development?

Â Issue 3 – Multiline TextÂ

If you are typing a long paragraph or TextInput with multiple lines using multiline true, the text will start to hide behind the keyboard after some extent. It will cause discomfort as we cannot see the text behind the keyboard.

Solution

We can use the scrollEnabled={false} property on the TextInput to resolve this issue.

Issue 4 – Problem with InputFieldÂ

When you are typing in the input field that is located in the middle or near the end of the page, you cannot see the text input, as the input field will hide behind the keyboard. This causes discomfort as we cannot see the text while we are typing.

Solution

We can solve this issue by wrapping up the view with any one of the below-mentioned components.

Component 1 – Inbuilt

<KeyboardAvoidingView
Â Â Â style={styles.container}
/>

Component 2

<KeyboardAwareScrollView
style={{ backgroundColor: '#4C69A5' }}
resetScrollToCoords={{ x: 0, y: 0 }}
contentContainerStyle={styles.container}
scrollEnabled={false}
/>

Read our article onÂ Custom Tab Bar in React Native using SVG, and D3-Shape

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected]Â or see careers at Startxlabs.”

### Fast API vs Flask vs Django

Though the names are different, these three frameworks FastAPI, Flask, and Django have a common similarity in that is they are web frameworks written using the Python language. These three frameworks have been used by developers for a variety of purposes. The three frameworks have distinct features that serve the best in development. Let us look at how these frameworks differ from each other in this article.

FastAPI

Fast API is a Python-based web framework that enables us to use the REST interface in development. It is a fast and high-performance framework to build APIs with the latest Python 3.6+, created by Sebastian Ramirez. Some of the popular features of the FastAPI include:

• Fast: As the name indicates, Fast API is the very fastest framework in Python with higher performance similar to NodeJS and GO.
• Faster Coding: Development speed has been increased from 200% to 300%
• Fewer Bugs: Human-made errors are reduced by 40%. Debugging time is less.
• Easy and Short: The framework is easy to use and it has less code duplication. So each parameter has multiple features and very few bugs.
• Robust: It provides automatic interactive documentation along with production-ready code.
• Standards: The framework is based on the OpenAPI and JSON Schema.
• Editor support: FastAPI is intuitive to use and the feature “Autocompletion” remains a favorite for all.

Pros:

• FastAPI offers validation of the developer’s data types and the deeply nested JSON requests.
• FastAPI has been developed using standards such as OAuth 2.0, JSON Schema, and OpenAPI.
• Building GraphQLAPI with graphene-python, a python library is easy using FastAPI.

Cons:

• It has a small community and lesser educational resources, as it newly emerges.

Read our article on – Python Basics: Data types

Flask is a Python-based micro web framework for developing web applications. It was created by Armin Ronacher. Since it is a microframework, it doesn’t have particular tools, libraries, or ORM (Object Relational Manager). Flask is a WSGI (webServer Gateway Interface) web application framework and doesn’t have features like template engine, routing, and more. The framework is based on WSGI and the Jinja2 template engine. Some of the notable features of flask include:

• Pythonic: Flask is entirely based on Python and very easy to get started with.
• Simple: Since Flask is a micro-framework, it is very simple and also extensible.
• Updated: Flask is a modern framework and its features are up-to-date.
• Readability: The framework is very explicit and it has better readability.
• Less complexity: You can save your program on multiple files, reducing the complexity.

Pros:

• Flask is more comfortable and flexible for the developers to use.
• Unit testing is possible with Flask. It enables you to tweak extensions and transit to a web framework.
• Flask is very simple and beginner-friendly.
• It lets you create apps faster and with minimal effort.

Cons:

• Security is a concern here as it uses modules that cause third-party involvement.
• Flask has a single source and multiple requests take time as it processes them one after the other.

Django

Django is also a python based web framework that uses the MTV (Model Template View) architectural pattern. It is an open-source framework developed by Adrian Holovaty and Simon Willison in 2005. The top features of Django include:

• Well documented: It is a well-established framework for the developers as it provides excellent documentation.
• Python-based: Since it is python based, Django is simple and easy to use.
• SEO Optimized: Django helps in maintaining the website through URLs which makes it efficient and easy for SEO engineers.
• Scalability: The level of implementation using Django is high. It helps in creating applications with greater precision and error-free.
• Security: Django provides security with expertise level of code.

Pros:

• The code structure of Django is efficient and using this, it is very easy to infuse more functionalities into the websites for the developers.
• Django is more flexible as it uses the Rest framework called Django Rest Framework (DRF).
• With Django, it is easy to build web APIs since it has a customizable and modular architecture.
• Django ensures security by protecting against joint SQL injection and forgery attacks from cross-site requests.

Cons:

• With Django, the speed is limited because of more reusable modules.

Read our article on –Â Python Basics: Functions and Variable Scopes

â€‹

We have seen the three frameworks separately and let’s compare them with each other now.

Features

• FastAPI
• Packages –Â Minimalistic framework that doesn’t have reusability enabling packages.
• Community –Â Has small community
• Performance –Â High performant and faster
• Job Openings –Â Fewer opportunities
• Education –Â Easiest to learn but has very few online resources
• Packages –Â Minimalistic framework that doesn’t have reusability enabling packages.
• Community –Â Has a moderate, thriving community
• Performance –Â Moderate in speed
• Job Openings –Â Moderate
• Education –Â Easy to learn and has many online materials.
• Django
• Packages –Â Full-stack web development framework that has reusability enabling packages.
• Community –Â Has the most significant community.
• Performance –Â Not so fast
• Job Openings –Â More opportunities for job
• Education –Â Learning Django is a bit harder but has many online resources available.

Conclusion

All three frameworks are effective for developing web applications as all the three are python based web frameworks. However, choosing the right one for you is in your hand. If you are looking to develop a full-stack website with high performance and functionalities, you can opt for Django. If you are aiming on developing a prototype for a web application and APIs or someoneÂ interested in machine learning, then Flask is ideal for you. FastAPI is suitable for someone who wants to focus on speed and scalability. Otherwise, all the three are good and suit you according to your requirements.

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at hr@startxlabs.comÂ or see careers at Startxlabs.”

### How to create a Read More component in React Native?

We would have seen some apps that have some text display more shortly, revealing the full content only after clicking the “more” button. For example, we can see the big Instagram captions below the post only by clicking the “show more” option. Until it will display only a truncated text with fewer lines. We cannot display the whole text all the time. Sometimes we need a truncated version of the whole content. Do you think this less/more button is easy to develop? Absolutely not. Its implementation is somewhat complicated. So what can we do?

Since this display text is related to UI, it has to be implemented in such a way that it should be displayed efficiently in different screen sizes. So we can not just implement by adding a substring along with it and insert a button associated with it. We need to create a custom component for this. In this article, we will see how we can implement it.

Requirements

To achieve this, we need,

• A component to display more, less buttons and reveals the full content.
• To find out the number of lines of the rendering text for a particular area. This is important to achieve effective display on all devices.

Read our article on Â 4 Most Common React Native Keyboard Issues

MoreLess Component

First, we need a text component that renders another component associated with the text. The moreless component is a functional component that takes 2 props such as truncatedText and fullText. It also has a state known as param and more and a function that updates it.

According to the text, the function helps in returning the text component that displays fullText or truncatedText. Its TouchableOpacity helps the user in toggling the “more” state.

OnTextLayout

Consider a situation, where we have to display the content or text in exact 3 lines for all the screen sizes. If the text is not exceeding the 3 lines, it can be displayed as such, and “more” button should not be added. But if the text exceeds the 3 lines, “more” button has to be added. By clicking on the “more” button, we will be able to see the full text. The revealed, full text will have a “less” button along with it. We achieve this by using the “onTextLayout” prop of the Text component.

â€‹

Before

â€‹

After

This onTextlayout event will tell us how many lines of the text should be displayed by the Text Component. Using this, we can capture the number of required states and save it on the state.

Read our article onÂ Custom Tab Bar in React Native using SVG, and D3-Shape

Following is the code to achieve this.

import React, { useState } from "react";
import { View, Text, StyleSheet, ViewStyle } from "react-native";
import { colors } from "../utils/constants/colors";
import { fonts, fontSize } from "../utils/constants/fonts";
import { SCREEN_WIDTH } from "../utils/globalFunction";

interface PropTypes {
text: string;
containerStyle?: ViewStyle;
targetLines?:number
}

const TextLessMoreView = (props: PropTypes) => {
const [textShown, setTextShown] = useState(false); //To show your remaining Text
const [lengthMore, setLengthMore] = useState(false); //to show the "Read more & Less Line"
const [triggerTextLocation, setTriggerTextLocation] = useState({
top: 0,
right: 0,
});

const toggleNumberOfLines = () => {
setTextShown(!textShown);
};

const onTextLayout = (e) => {
const { lines } = e.nativeEvent;
if (lines && Array.isArray(lines) && lines.length > 0) {
let tempTxtLocaation = {
top: (lines.length - 1) * lines[0].height,
right: SCREEN_WIDTH - lines[lines.length - 1].width - 10,
};
setTriggerTextLocation(tempTxtLocaation);
setLengthMore(lines.length >= props.targetLines);
}
};

return (
<View style={[styles.mainBody, props.containerStyle]}>
<Text
onTextLayout={onTextLayout}
numberOfLines={textShown ? undefined : props.targetLines || 1}
style={styles.txtStyle}
>
{props.text || ""}
</Text>
{lengthMore ? (
<Text
onPress={toggleNumberOfLines}
style={[
styles.lessMoreStyle,
{
position: "absolute",
backgroundColor: colors.primary_background_color,
right: triggerTextLocation.right,
top: triggerTextLocation.top,
},
]}
>
{textShown ? " less" : "... more"}
</Text>
) : null}
</View>
);
};
const styles = StyleSheet.create({
mainBody: {
marginTop: 15,
},
txtStyle: {
fontFamily: fonts.secondary_regular_font,
fontSize: fontSize.modal_title_size,
color: colors.white,
flex: 1,
},
lessMoreStyle: {
fontFamily: fonts.secondary_regular_font,
fontSize: fontSize.modal_title_size,
color: colors.app_orange,
},
});
export default TextLessMoreView;

Usage –

Here this targetLines prop is used to define how many lines to be shown just before to see full content.

<TextLessMoreView
text={"Text to be shown on screen"}
targetLines={1}
/>

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at hr@startxlabs.comÂ or see careers at Startxlabs.”