Tuesday, 19 February 2019

String Operation in Python

In Python String is a sequence of characters.

It is an object that represents a sequence of characters. You can create a string in python as shown below
Python Code:
x = "XMarksThe Spot"

String are constant. They cannot be changed once memory is allocated for them. Every time you perform operations on a String it rather creates a new string. Below example show you some common String operations in Python.
Python Code:
s = "XMarksTheSpot"
upper(s) # Prints XMARKSTHESPOT
lower(s) # Prints xmarksthespot
s.startswith("XMa") # Prints True
s.replace("X", "Y") # Prints YMarksTheSpot
len(s) # Prints 13
s[0] # Prints X
s[1] # Prints MarksTheSpot

We can slice parts of a string using slice operator :. The digit in front of the the : represents the start index. The digit after the : represents the end index. For example :
Python Code:
>>> s[1:3]
'Ma'

We can get list of characters for a given string using list function.
Python Code:
>>> list(s)
['X', 'M', 'a', 'r', 'k', 's', 'T', 'h', 'e', 'S', 'p', 'o', 't']

We can remove leading and trailing space from a string using strip function.
Python Code:
>>> x = " I have a lot of space before and after me...... do I?"
>>> x.strip( )
'I have a lot of space before and after me... do I?'

We can remove spaces from the left of a string using Istrip function.
Python Code:
>>>x.Istrip( )
' I have a lot of space before and after me ... do I? '

We can remove spaces from the right of a string using rstrip function.
Python Code:
>>> x.rstrip( )
' I have a lot of space before and after me ... do I? '

Join function on a string can join a list of strings using a specified delimiter. In the example below, we are joining a list of strings with comma as delimiter.
Python Code:
>>> ",".join (["Apple","a","day"])
'Apple,a,day'

We can check whether a given string starts with a substring using startswith method.
Python Code:
>>> y = "Superwoman"
>>> y.startswith("Duper")
False
>>> y.startswith("Super")
True

We can check whether a given string ends with a substring using endswith method.
Python Code:
>>> y.endswith("girl")
False
>>> y.endswith("woman")
True

We can use split method on a string to split a string into a list of substrings. To the split method, we need to pass a delimiter on which the split operation is to be performed.
Python Code:
>>> z="www.ntirawen.com"
>>>z.split(".")
['www','ntirawen','com']

zfill function is used to fill up the leading part of string with zeros until the specified with.
Python Code:
>> z.zfill(25)
'00000000www.ntirawen.com'

We can format a string using % operator. % is a format specifier used to specify how the data is to be formatted. In the below example, we are using %d format specifier which is an integer. 
Python Code:
>>> "There are %d letters in the alphabet" % 26
'There are 26 letters in the alphabet'

In the below example, we are using %s format specifier, which is a string, in addition to %d format specifier.
Python Code:
>>> "There are %d planets. The largest planet is %s" %(8,"Jupiter")
'There are 8 planets. The largest planet is Jupiter'

Sunday, 17 February 2019

Loops in Python

Loops are used in cases where you need to repeat a set of instruction over and over again until a certain condition is met. There are two primary  types of looping in Python.
  • For Loop
  • While Loop

For Loop

Python Code:
for i in range(1,10):
  print(i, end=' ')

A for loop contains three operations. The first operation i is initializing the loop iterator with first value of range function. range function is supping values as iterator from (1,10).for loop catches the Stop Iterator error and breaks the looping.

Output:
1 2 3 4 5 6 7 8 9

While  Loop

Python Code:
i = 0
while i < 10:
  print(i, end= ' ')
   i+=1

Output:
1 2 3 4 5 6 7 8 9

A while loop variable is initialized before the statement. Here we initialized i to 0. In the while statement, we have kept until when the loop is valid.

So here we check up to i < 10. Inside the while loop we are printing i and then incrementing it by 1.
Imagine what would happen if we don't increment i by 1?
The loop will keep running a concept called infinite loop. Eventually the program will crash.

Break and Continue:

Break Statement:

A break statement will stop the current loop and it will continue to the next statement of the program after the loop.

Python Code:
i = 0
while i < 10:
   i+ = 1
   print(i, end=' ')
    if i == 5:
       break

Output:
1 2 3 4 5

In the above random example, we are incrementing i from an initial value of 0 by 1. When the value of i is 5, we are breaking the loop.

Continue Statement:

Continue will stop the current iteration of the loop and it will start the next iteration.It is very useful when we have some exception cases, but do not wish to stop the loop for such scenarios.

Python Code:
i = 0
while i < 10:
  i+ = 1
  if i%2 == 0:
     continue
  print(i, end= ' ')

Output:
1 3 5 7 9

In the above example, we are skipping all even numbers via the id conditional check i%2.So we end up printing only odd numbers. 

Saturday, 16 February 2019

Conditional Statements in Python

Conditional statement in python can be used to take decisions based on certain conditions in your program.

In this blog we will describe you four most commonly used forms of conditionals.We will encounter more of these forms and variations in your professional programming life.
  • If Then
  • If Then Else
  • If Then Else If Else
  • Nested If Then
If Then :

As the name indicates it is quite simple.If a certain condition is satisfied, then perform some action.

Python Code:
accountBalance = 0
if accountBalance < 1000
  print("Close Account!")

Output:
Close Account!

In the example above, we are checking account balance in the if statement. If the account balance comes to less than 1000, we are printing a line to close the account.

In a real world scenario this can be the case to check an account has minimum balance.

If Then Else:

An extra else statement can be added to an if condition, to execute what should happen if the if condition is not satisfied.

Python Code:
accountBalance = 1001
if accountBalance < 1000:
  print("Close Account!")
else:
  print("We love having you with us!")

Output:
We love having you with us!

In the above example, if the account balance is >=1000, we are printing a warm message.

If Then Else If Else:

If a primary if condition is not satisfied, we can add an Else if statement in between to check another condition if required.

Python Code:
accountBalance = 1000002
if accountBalance < 1000:
    print("Close Account!")
elif accountBalance > 1000000:
   print("We really love having you with us. Please find a Europe tour cruise package in your mailbox!")
else:
   print("We love having you with us!")


Output:
We really love having you with us. Please find a Europe tour cruise package in your mailbox!

In the above example, we added an else if condition.
For high valued customers who have more than a large threshold of account balance with us, we printed a separate message.

Nested If Then:

We can nest multiple If Then statements. Be careful when using this as it can become a mess to read . You can use && or || operators to avoid it in some scenarios.

Python Code:
accountBalance = 600
if accountBalance < 1000:
    if accountBalance < 500:
        print("Close Account!")
      else:
        print("You better maintain a minimum balance Pal! You got 5 days time.")
elif accountBalance > 1000000:
 print("We really love having you with us.Please find a Europe tour cruise package in your mailbox!")
else:
 print("We love having with us!")

Output:
 You better maintain a minimum balance Pal! You got 5 days time.

In the above example, we added a nested if statement where we are further checking if account balance is less than 500. If it is not, then we are giving a friendly and warm warning message.

Data Types and Operators in Python

The Data types in Python are :
  • boolean
  • byte
  • list
  • tuple
  • dict
  • Complex Number
  • float
  • long
  • string
Primitive data types are stored in stack memory.

boolean:
Valid values: true, false
Default value: false
Size: 1 bit

Python Code:
isEnabled = True

Byte:

Python Code:
b'Python'

List:

Python Code:
listOfFruits = ["apples", "mango", "bananas"]

Tuple:

Python Code:
listOfVegetables = ("carrot", "brinjal", "cauliflower")

Dict:

Python Code:
numberDictionary = {"ONE" : 1, "TWO" :2}

Complex Number: 

Python Code:
z = 2+3j

float:
Python Code:
x = 2.3

long:
Python Code:
bigValue = 1094324242344L

string:
Python Code
x = "The Quick Brown Fox Jumps Over The Lazy Dog"


Python Operators: 

Listed below are various operators available in Python. A brief description is provide with the operators and an example of most commonly used operators is provided to end this blog.

Multiplication/division operators:

* : It multiples the left and right operand and returns the result.
% : Modulo operator. Divides the left operand with the right operand and returns the remainder.
/  : Division Operator. Divides the left operand and returns the result.

Additional / Subtraction :

+ : Addition Operator. Adds the left operand with the right operand and returns the result.
- : Subtraction Operator. Subtracts the left operand and right operand and returns the result.

Shift Operators :

<< : Left Shift Operator. Moves the left operand to the left by the number of bits specified by the right operand.
>> : Right Shift Operator. Moves the left operand to the left by the number of bits specified by the right operand.

Relational Operators :

< : Less than Operator. Check if the left operand is less than the right operand. Return True or False.
> : Greater than Operator. Check if the left operand is greater than the right operand. Return True or False.
>= : Greater than or equal to. Check if the left operand is greater than or equal to the right operand . Return True or False.
is : Instance of Operator. Check if the left operand is instance of right operand. Example: Is Dog Animal. True. Is Dog Plant. False.


Equality :

== : Check if left operand is equal to the right operand. Return True or False.
!= : Check if left operand is not equal to the right operand. Return True or False.

Bitwise AND :
& : Bitwise AND Operator. If bit exists in both left and right operand, copy the bit to the result.

Bitwise exclusive OR :
^ : Bitwise XOR Operator. If bit is set in either left or right operand but not in both, copy the bit to the result.

Bitwise inclusive OR :
| : Bitwise OR Operator. If bit exists in either left to right operand is true, the result will be true else false.

Logical AND :
and : Logical AND Operator. If both left and right operand is true, the result will be true else false.

Logical OR :
or : Logical OR Operator. If Either left or right operand is true, the resultwill be true or false.

Assignment Operator :

= : Assignment operator. Assign the right operand to the left operand.
+= : Add plus assignment operator. Adds the left and right operand AND assigns the result to the left operand
-= : Subtract plus assignment operator. Subtract the left and right operand AND assigns the result to the left operand.
*= : Multiples plus assignment operator. Multiplies the left and right operand AND assigns the result to the left operand.
/= : Divides plus assignment operator. Divides the left and right operand And assigns the result to the left operand.
%= : Modulo plus assignment operator. Divides the left and right operand AND assigns the remainder to the left operand.
&= : Bitwise AND plus assignment operator.
^= : Bitwise OR plus assignment operator.
>>= : Right shift plus assignment operator.

Friday, 15 February 2019

TextView in Android

In Android, TextView displays text to the user and optionally allows them to edit it programmatically.
TextView is a complete text editor, however basic class is configured to not allow editing but we can edit it.


View is the parent class of TextView. Being a subclass of view the text view component can be used in your app’s
GUI inside a ViewGroup, or as the content view of an activity.
We can create a TextView instance by declaring it inside a layout(XML file) or by instantiating
it programmatically(Java Class).
TextView code in XML:

<TextView android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PirawenAndroid" />
TextView code in JAVA:

TextView textView = (TextView) findViewById(R.id.textView);

textView.setText("PirawenAndroid"); //set text for text view


Attributes of TextView:
Now let’s we discuss about the attributes that helps us to configure a TextView in your xml file.
1. id: id is an attribute used to uniquely identify a text view. Below is the example code in which we set
the id of a text view.
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

2. gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text like left, right, center, top, bottom, center_vertical, center_horizontal etc.
Below is the example code with explanation included in which we set the center_horizontal gravity for text
of a TextView.
<TextView
android:id="@+id/simpleTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="PirawenAndroid"
android:textSize="20sp"
android:gravity="center_horizontal"/> <!--center horizontal gravity-->

3. text: text attribute is used to set the text in a text view. We can set the text in xml as well as in the java class.
Below is the example code with explanation included in which we set the text “PirawenAndroid” in a text view.

<TextView
android:id="@+id/simpleTextView"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:text="PirawenAndroid"/><!--Display Text as PirawenAndroid-->
In Java class:
Below is the example code in which we set the text in a textview programmatically means in java class.
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("PirawenAndroid"); //set text for text view
4. textColor: textColor attribute is used to set the text color of a text view.
Color value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
Below is the example code with explanation included in which we set the red color for the displayed text.
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PirawenAndroid"
android:layout_centerInParent="true"
android:textSize="25sp"
android:textColor="#f00"/><!--red color for text view-->


In Java class:
Below is the example code in which we set the text in a textview programmatically means in java class.
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("PirawenAndroid"); //set text for text view
4. textColor: textColor attribute is used to set the text color of a text view.
Color value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
Below is the example code with explanation included in which we set the red color for the displayed text.
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="PirawenAndroid"
android:layout_centerInParent="true"
android:textSize="25sp"
android:textColor="#f00"/><!--red color for text view-->

In Java class:
Below is the example code in which we set the text size of a text view programmatically means in java class.
TextView textView = (TextView)findViewById(R.id.textView);
textView.setTextSize(20); //set 20sp size of text

6. textStyle: textStyle attribute is used to set the text style of a text view.
The possible text styles are bold, italic and normal.  If we need to use two or more styles for a text view then
“|” operator is used for that.
Below is the example code with explanation included in which we  set the bold and italic text styles for text.

<TextView
   android:id="@+id/simpleTextView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="PirawenAndroid"
   android:layout_centerInParent="true"
   android:textSize="40sp"
   android:textStyle="bold|italic"/><!--bold and italic text style of text-->
7. background: background attribute is used to set the background of a text view.
We can set a color or a drawable in the background of a text view.
8. padding: padding attribute is used to set the padding from left, right, top or bottom.
In above example code of background we also set the 10dp padding from all the side’s of text view.
Below is the example code with explanation included in which we set the black color for the background,
white color for the displayed text and set 10dp padding from all the side’s for text view.
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PirawenAndroid"
android:layout_centerInParent="true"
android:textSize="40sp"
android:padding="10dp"
android:textColor="#fff"
android:background="#000"/> <!--red color for background of text view-->
In Java class:
Below is the example code in which we set the background color of a text view programmatically means in
java class.
TextView textView = (TextView)findViewById(R.id.textView);
textView.setBackgroundColor(Color.BLACK);//set background color

Example of TextView:
Below is the example of TextView in which we display a text view and set the text in xml file and then change
the text on button click event programmatically. Below is the final output and code:
Step 1: Create a new project and name it textViewExample.

Select File -> New -> New Project. Fill the forms and click "Finish" button.
Step 2: Open res -> layout -> xml (or) activity_main.xml and add following code.
Here we will create a button and a textview in Relative Layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <TextView
       android:id="@+id/simpleTextView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
       android:text="Before Clicking"
       android:textColor="#f00"
       android:textSize="25sp"
       android:textStyle="bold|italic"
       android:layout_marginTop="50dp"/>

   <Button
       android:id="@+id/btnChangeText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"

       android:background="#f00"
       android:padding="10dp"
       android:text="Change Text"
       android:textColor="#fff"
       android:textStyle="bold" />
</RelativeLayout>


Step 3: Open app -> java -> package and open MainActivity.java and add the following code.
Here we will change the text of TextView after the user click on Button.

package example.irawen.textviewexample;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main); //set the layout

       final TextView simpleTextView = (TextView) findViewById(R.id.simpleTextView);

//get the id for TextView

       Button changeText = (Button) findViewById(R.id.btnChangeText); //get the id for button

       changeText.setOnClickListener(new View.OnClickListener() {
           @Override

           public void onClick(View view) {
               simpleTextView.setText("After Clicking"); //set the text after clicking button

           }
       });
   }


}

Output:
Now run the app in Emulator and click on the button. You will see text will change “After Clicking”.
 

Popular Posts

Categories

AI (32) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (888) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses