Variables and Data types in Python

Python is an all-rounder programming language that deals with various kinds of fundamentals; these are going to use to develop Python programs, which include variable, identifiers, data types, strings arrays, etc..

Let us understand one by one as follow:

Python Identifiers:

A name which represents Variable, class, Function, Method name or Object which is used for identification purpose is called as Identifier

  • Identifiers can be in Lowercase(a to z),
  • Uppercase(A to Z), and digits(0 to 9)
  • It can be an Underscore( _ )

Ex: valid examples

 myClass
 classTest
 Num_1 

Invalid examples

1_var
ca$h=10

Just see the below example

python-identifier-error

Some Rules for Python Identifiers :

  • Where the identifier does not include any special characters like $,%,&, *,etc..
  • Identifier names never start with Digits
    identifier-never-starts-with-digits
  • Python Identifiers are the case sensitive
    case-sensitive-identifier
  • There is no length limit for Python Identifiers
    identifier-no-lenght-limit
  • Even though there is no length limit for identifiers we should not use unnecessarily too lengthy identifiers
  • In Python there are some reserved words are there which we cannot apply to declare the variables
    identifiers-reserved-words
  • If any variable starts with _x is called a protected variable
  • If any variable starts with two underscores __x is called a private variable
  • If any variable starts with two underscores and ends with two variables is called as Magic variable __x__

Python keywords :

The words which are used to represent the syntax and Structure of the python language is called as Keywords or Python Reserved words.

  • Keywords are case sensitive
  • there are 33 keywords in Python language
  • All the keywords except True, False and None are in the lowercase

The list of Keywords are as follows :

False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
  • All the keywords contain only alphabet symbols
  • let us see some examples:

true-error

  • Python is a dynamically typed language, and hence, it does not require any int, float, complex type of reserved words.
  • There is a keyword module in Python; we can import them, as shown below:

    import keyword
    keyword.kwlist​

    If you enter the above command, it will list out all the keywords which are present in the keyword module

    kw-list

Mutability in Python

Introduction to Python Datatypes

Data type: It represents the type of data stored in a variable that is used in our program is called as Datatype.

Python is a dynamically typed programming language, and hence we are not required to define the types of the Data explicitly

Based on the assigned value, the class will be considered by the python virtual machine, and also there will be a function called type(a), which represents the data type of a.

Example:

  • Int type
a=10

data-type-int

  • Boolean type
b=True​

data-type-boolean

  • Float type
    c=10.5​
    data-type-float

Different data types available in Python

There are 14 types of Data types are present in the Python

int float complex string boolean
list tuple set frozen set bytes
bytes array dict range none
Note: Everything in the Python is an Object

There are three inbuilt functions in the Python :

Consider an example where we are assigning a value to an a=10

  • And if we want to know the type of a, we will use type(a) and then it will display the data type of a
  • And if we're going to see the address of a, that means where it is located then we will use id(a)
  • And if we want to print the value of a, we will use print(a)
    a=10
    type(a)
    id(a)
    print(a)​

inbuilt-functions

Python Bytes and Bytearray

Integer/int Datatype

The numbers without any decimal point, then it is called an integer, or some times we can call it the whole number.

In python three versions, there no limit to how long an integer value can be, and hence, we can use long integer values. long-int

We can represent these integral values in Four types

Decimal Form(base 10): In this form, we are going to use the numbers between 0 to 9 like, and this is also called a default number system.

a=986
a=123

Binary Form(base 2): In this form, we are going to use the number between 0 to 1, by default all the numbers in the Python are going to considered as a binary number, for example, if you represent the a value as

a=1111

Then it will examine the amount as one thousand one hundred eleven only so to represent this value in the binary format we need to prefix it with 0b

a=0b1111

in the below image you can see the difference between a=1111 and a=0b1111

binary-form

Octal Form( base 8) : In this format, we are going to use the numbers between 0 to 7, and literal value should start with zero, followed by small o or capital o.

a=0o123

octal-form

And also it will throw an error if we use a number more than 7

octal-form-error

Hexadecimal Form(base 16): In this format, we are going to use the numbers between 0to 9, and alphabets between A to F, including lower case also.

Here the values of

  • A=10
  • B=11
  • C=12
  • D=13
  • E=14
  • F=15

And the numbers should be prefixed with 0 and either uppercase X or lowercase x

a=0x123
a=0x1556
a=0xface
a=0xbeef
a=0xzoo

hexa-form

Python Datatype summary

Float Datatype

The numbers with Decimal points are called as float datatypes

float-data-types

We can represent the float values only in the decimal form, and we cannot represent them in Integral way, binary form, octal form, and hexadecimal form, as shown below:

f=1.23
f=0b1.111
f=0o123.456
f=0x12357

float-errors

if f=1.2e3 which is nothing but 1.2*10^3 this type of representation is called as scientific notation or exponential form and it is applicable only for floating points

f=1.2e3

exponantial-float

In this format, we can represent the more significant values as well, as it will consume, less space

f=15.63e10

exponantial-floating-form

Python None Datatype

Complex Datatype

Complex Data type is the special Datatype which is present in the Python programming language, which can be used to develop

  • Scientific application
  • Arithmetic applications
  • Electrical engineering applications

Let us see how to represent the complex data type or the Syntax of complex data type

a+bj : where a is the real part and b is the imaginary part and j=j^2=-1

x=10+20j

complex-data-type

x=10+20i

complex-data-type-error

And from the above example consider x=10+20j, and if you want to print the actual value then you can give the command as

x=10+20j
print(x.real)

real-part

Similarly, if you're going to print the imaginary number

x=10+20j
print(x.imag)

imaginary-number

In the real part and the imaginary part, we can use decimal points

x=10+20j
x=10.5+20j
x=10.5+20.6j

And also in the real part, we can use either binary form, octal form, hexadecimal form but in the imaginary part we should represent only it in the Decimal form

x=10+20j
x10.5+20.6j
x=0b1111+20j
x=0b111+0b1111

errors-in-complex

We can also perform arithmetic operations by using this syntax

x=10+20j
y=20+30j
x+y=?
x*y=?

complex-arithmetic-operations

Python Special characters

Boolean Datatype

Boolean Data type is the one which is used to represent in the numerical form, and the constant value of boolean Data type is True and False, where T and F are always should be in the uppercase.

b=True
b=true

boolean-form

consider the below example

a=10
b=20
c=a>b
print(c)
print(type(c))

boolean-operations

Example: 2: internally the True values will be one, and the False valve will be 0and hence if we perform the below operation

print(True+True)
print(True-False)

true-plus-true

Python Immutability

Python string Datatype

String Datatype : A sequence of characters is called a string, which may contain literal constants or some variables. The String is always represented in double-quotes.

Example: "Chercher. tech", "Banana", "Apple","One", etc..

Importance of string Datatype

  • In python, the most commonly used data type is string only.
  • The default return type of input function is always a string type only.
  • By default, the command line arguments are a string only.
  • The single character within a single quote or double quote is also considered as string datatype only.
    ex: ch='A', ch="B",etc..
  • We can define the multi-line literals by using either three single quotes or triple double-quotes.
    Example: """Elepbhant                       '''Parrot
                      Tiger                                  Crow     
                            Lion"""                               Roaster'''

Python Operator

    Ways to Access the String Characters

    We can access the String by using the following two ways

    Index:

    The index is used to access a specific character at the given index of the string; the index value of the first character is zero (0).

    string="dhanvik"
    print(string[0])=?
    print(string[1])=?
    print(string[4])=?

    In the above example, the string is stored like

    assigning-index-values

    The output is:

    d
    h
    v

    In the above example, the index value is up to 6, and if I am going to print as below then you will get an index error

    print(string[100])
    #the output is:
    Traceback (most recent call last):
      File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 5, in <module>
        print(string[100])
    IndexError: string index out of range
    

    index-error

    One more very important thing is that python will provide support for both positive indexing and negative indexing, that means from backward direction index value will start from -1 so the string is stored like

    negative-indexing-python

    string="dhanvik"
    print(string[-1])
    print(string[-5])
    #The output is:
    k
    a
    

    Slice operator :

    In string, we have an operator called Slice, which is nothing but a part of a string, in some cases, if we want to print a part of that string or a slice of that string, then we will use this operator.

    The syntax of the slice operator is

    s[begin:end:step]
    

    Begin : The integer where the beginning of a slicing object will start.

    End : The integer until which the slicing will take place or slicing will stop.

    Step : Integer, which determines the increment between each index for slicing.

    • The step value can be either +ve or -ve
    • If the step value is +ve then, we have to consider from the begin to end-1 in Forwarding direction(From left to right)
    • If the step value is -ve then, we have to consider from the begin to end+1 in Backward direction(From right to left)
    • In the backward direction, if the step value -1, then the result is always empty.
    • In the forward direction, if the step value 0, then the result is always empty.
    • In forwarding Direction:
      The default value for begin is 0
      The default value for the end is the length of the string
      The default value for step is +1
    • In Backward Direction:
      The default value for begin is -1
      The default value for the end is -(length of the string+1)
    • We can consider both +ve and -ve values for beginning and end index in case of forwarding and backward directions.

    The following example to demonstrate a slice operator.

    string='abcdefghij'
    Below are the inputs and outputs
    string[1:6:2] => 'bdf'
    string[::1] =>'abcdefghij'
    string[::-1] =>'jihgfedcba'
    string[3:7:-1] => ''
    string[7:4:-1] => 'hgf'
    string[0:10000:1] =>'abcdefghij'
    string[-4:1:-1]=> 'gfedc'
    string[-4:1:-2] =>'gec'
    string[5:0:1] =>''
    string[9:0:0] =>ValueError: slice step cannot be zero
    string[0:-10:-1]=> ''
    string[0:-11:-1] =>'a'
    string[0:0:1] =>''
    string[0:-9:-2] => ''
    string[-5:-9:-2] =>'fd'
    string[10:-1:-1] =>''
    string[10000:2:-1] => 'jihgfed'
    

    Example: Here string="abcdefghijklmnopqrstuvwxyz"
    And the index value will start from zero and hence a=0, b=1, and c=3, etc... z=25.

    string="abcdefghiklmnopqrstuvwxyz"
    print(s[3:9])

    Then the above example will return from the third index to 9-1, that means up to 8 index

    defghi

    example:2

    string="abcdefghiklmnopqrstuvwxyz"
    print(string[ :9])

    In the above example am going to mention only the end argument and begin argument is empty, so in this case, it will going to consider by default from the beginning itself

    abcdefghi
    

    Python Modules

    Concatenate and Repeat Operators for String

    We can use+operator for concatenation and * operator for repeating strings.

    Concatenation:

    Concatenation is nothing but combining or joining two strings, to perform concatenation, both the arguments must be of string type. We are going to combine strings using the concatenation operator (+).

    concatenation-image-one

    Example:

    print("chercher"+"tech")
    

    string-mathematical-operator

    Example:

    string="dhan"+"vik"
    print(s)
    string="dhan"+"10"
    print(s)
    string="dhan"+10
    Print(s)

    concatenation-operation

    Repetition Operator:

    Repetition: Some times we want to write the same text multiple times; instead of writing it manually, we can use the repetition operator to repeat the same text as many times as you want.

    To perform the repetition, one argument should be a string, and another must be of int datatype, Here we are using the Multiplication operator or an asterisk operator to repeat the text.

    Example:

    #String_to_be_repeated*number_of_times
    main_string="cherchertech."*3
    print(main_string)

    The output is:

    #The output is:
    cherchertech.cherchertech.cherchertech.
    How to Concatenate String and Other Datatypes

    We have several ways to concatenate different data types

    1.By converting the non-string to the string data type

    Example:

    integer_value=56
    target_string="Health is wealth"+str(integer_value)
    print(target_string)

    The output is:

    Health is wealth56

    2. By using the interpolation, we will represent interpolation by using % symbol

    price= 42
    banana_price='The cost of six banana is %d' % (price)
    print(banana_price)

    The output is:

    The cost of six banana is 42

    3.Using the format()method

    price = 42
    base_price='The cost of six banana is {}'.format(price)
    print(base_price)

    The output is:

    The cost of six banana is 42
    

    Python Input and Output Statements

    Substring in Python

    A part/sequence of characters of String is called as a substring.

    example: 
    main string: "wonder is wonderful"
    substring1: "wonder"
    substring2: :won"
    substring3: "is"
    substring4: "wonderful"
    substring5: "ful"
    

    Python supports to check whether the given character or a string is a member of any string or not by using the in and not operators.

    Example:1

    main_string="Strong"
    substring="S" in main_string
    print(substring)

    The output is:

    True

    Example:2

    main_string="Trust"
    substring="o" not in main_string
    print(substring)

    The output is:

    True

    The following example to demonstrate membership operator

    main_string = input("Enter main string:")
    substring = input("Enter sub string:")
    if substring in main_string:
        print(substring,"is found in main string")
    else:
        print(substring,"is not found in main string")

    If the main string is chercher.tech technologies

    the-output-of-cherchertech-one

    If the substring is not present in the main string, then the output is

    output-of-python-string-operation

    Command Line Arguments

    Comparison of String

    We can compare the strings using the comparison/relational operators.

    • Equal (==)
    • Not equal (!=)
    • Greater than (>)
    • Less than (<)
    • Greater than or equal to (>=)
    • Less than or equal to (<=)
    Example: 2!=4, 8==2*4, 6>4,etc..

    The following example is to compare the two strings; python compares the two strings by comparing each character based on their Unicode values.

    string_one=input("Enter first string:")
    string_two=input("Enter Second string:")
    if string_one==string_two:
        print("Both strings are equal")
    elif string_one<string_two:
        print("First String is less than Second String")
    else:
        print("First String is greater than Second String")

    By comparing the moon and sun the python will return as Moon<Sun because of the Unicode value of S is greater than the Unicode value of M, we can get the Unicode of each character by using print(ord("M")) and print(ord("S"))

    comparison-operator-two

    And hence the output of the comparison program is as below

    output-of-moon-sun

    If we compare India and India, then the output is

    output-of-india-india

    Python Program Flow Control

    String Methods in Python

    Python has some built-in methods which we can use on strings to perform some operations.

    Remove spaces in String

    Python provides us with some inbuilt functions to remove the spaces from a string

    • rstrip(): To remove spaces at the right-hand side
    • lstrip() : To remove spaces at the left-hand side
    • strip() : To remove spaces both sides

    Example without Removing spaces from the string

    city=input("Enter your city Name:")
    if city=='Hyderabad':
        print("Hello Hyderbadi..Adab")
    elif city=='Chennai':
        print("Hello Madrasi...Vanakkam")
    elif city=="Bangalore":
        print("Hello Kannadiga...Shubhodaya")
    else:
        print("your entered city is invalid")

    If I enter the city name as Bangalore without spaces, then the output is

    output-of-hello-kannadiga

    And I enter the city name beginning with space as Hyderabad then the output is

    output-of-hyderabad

    Python will not remove any spaces before or after the given string, by using a method strip() we can remove the spaces.

    We are assigning stripped value to a variable called scity as scity=city.strip()

    city=input("Enter your city Name:")
    scity=city.strip()
    if scity=='Hyderabad':
        print("Hello Hyderbadi..Adab")
    elif scity=='Chennai':
        print("Hello Madrasi...Vanakkam")
    elif scity=="Bangalore":
        print("Hello Kannadiga...Shubhodaya")
    else:
        print("your entered city is invalid")

    If I enter the city name Bangalore with space in the beginning and as well as spaces at the end, then the output will be.

    out-put-of-space-bangalore

    To Find the Index of given Substring

    Python also provides some in-built methods to find the index of the given substring,

    There are four methods we have to find the substring

    find()=> Used to find the substring in the forward direction.

    Example:1

    string="ABCD"
    print(string.find("B"))

    The output is: If B is present in the given string then, python's find() method will return its index value(1). The find method is always going to search from right to left(A->D)

    1

    Example:2

    string="ABCD"
    print(string.find("z"))

    The output is: If the given substring is not present in the string then find() method will return -1.

    -1

    rfind()=>Used to find the substring in a backward direction.

    Example1: if we pass the rfind() method to find the substring B from the given string s="ABCDBA", The rfind() method will always search from left to right so that it will return index value as 4.

    string= "ABCDBA"
    print(string.rfind("B"))

    The output is:

    4

    Example2: In the case of rfind() method, also if the given substring is not present in the string, then the python will return index value as -1 only.

    string= "ABCDBA"
    print(string.rfind("z"))

    The output is:

    -1

    index= Used to find the substring in a forward direction.

    Example1: If the main string string="ABCDEFGH" and we have to find the substring in the range between D to G then we can use the find() method with index range as print(string.find(substring,begin,end))

    string="ABCDEFGH"
    print(string.find("B",3,6))

    The output is: The Given substring "B" is not present in the given index range and hence python will return -1.

    -1

    Example2: If the print(string.find("F",3,6)) then the output is

    string= "ABCDEFGH"
    print(string.find("F",3,6))

    The output is:

    5

    Example3: In the same way, we can access the substring by using the index() method also

    string="IJKLMNOPQRST"
    print(string.index("O"))
    

    The output is:

    6

    Example4: If the substring is not present in the given string the index() is going to throw a value error.

    string="IJKLMNOPQRST"
    print(string.index("A"))

    The output is:

    Traceback (most recent call last):
      File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 2, in <module>
        print(string.index("A"))
    ValueError: substring not found

    rindex()=>Used to find the substring in a backward direction

    Example1: Similarly, if we use rindex() method to find the substring R in the given string, python will search from left to right and returns as 8.

    string="PQRSTUVWRX"
    print(string.rfind("R"))

    The output is:

    8

    The following example demonstrates the index() method

    mail=input("enter your mail Id:")
    try:
        i=mail.index("@")
        print("Mail id contains @ symbol, which is mandatory")
    except ValueError:
        print("Mail id does not contain @ symbol, which is mandatory")

    The entered mail id does not contain @ symbol then, the output is

    enter your mail Id:ashumurty
    Mail id does not contain @ symbol, which is mandatory

    The entered mail id contain @ symbol then, the output is

    enter your mail Id:ahumurty@gmail.com
    Mail id contains @ symbol, which is mandatory
    

    Counting the substring in the given string

    We can determine the number of times a specific character/substring present in the given string.

    Python provides an in-built function count(), which returns the number of occurrences of a substring in the given string.

    The syntax for the count() method is

    string.count(substring)

    The following example demonstrates the count() method

    string="ABBABBAABBABA"
    print(string.count("B"))
    #The output is:
    7
    

    If the given substring is not present in the string then, python will return 0.

    string="ABBABBAABBABA"
    print(string.count("R"))
    #The output is:
    0

    To count the substring within the given index print(string.count("B",start_index,end_index)), then the output is

    string="ABBABBAABBABA"
    print(string.count("B",4,100))
    #The output is:
    5

    To find the index of all the occurrence of the given substring

    string="ABCABCABCA"
    subs="ABC"
    new_string=string.find(subs)
    if new_string==-1:
        print("specified substring not found")
    while new_string!= -1:
            print("{} present at index:{}".format(subs,new_string))
            new_string= string.find(subs,new_string+len(subs),len(string))
    

    The output is:

    Enter substring to search:ABC
    ABC present at index:0
    ABC present at index:3
    ABC present at index:6
    

    We can make substring to enter dynamically as

    string="ABCABCABCA"
    subs=input("Enter substring to search:")
    new_string=string.find(subs)
    if new_string==-1:
        print("specified substring not found")
    while new_string!= -1:
            print("{} present at index:{}".format(subs,new_string))
            new_string=string.find(subs,new_string+len(subs),len(string))
    

    The output is:

    Enter substring to search:A
    A present at index:0
    A present at index:3
    A present at index:6
    A present at index:9
    

    If you want to know the number occurrences by using s.count(subs)

    string="ABCABCABCA"
    subs=input("Enter substring to search:")
    new_string=string.find(subs)
    if new_string==-1:
        print("specified substring not found")
    while new_string!= -1:
            print("{} present at index:{}".format(subs,new_string))
            new_string= string.find(subs,new_string+len(subs),len(string))
    print("The number of occurrences:",string.count(subs))

    Then the output is

    Enter substring to search:A
    A present at index:0
    A present at index:3
    A present at index:6
    A present at index:9
    The number of occurrences: 4

    The following example to replace the string with another string by using the replace() method

    The syntax for replace() method is string.replace(oldstring, newstring)

    string="ABABABA"
    string_one=string.replace("A", "B")
    print(string_one)
    #The output is:
    BBBBBBB

    By using the replace() method we can also remove the spaces between the string as follow

    string="cher cher tech"
    string_one=string.replace(" ","")
    print(string_one)
    #the output is:
    cherchertech
    

    We can also use another one method to find the number of spaces between the strings instead of count() method

    string="cher cher tech"
    string_one=string.replace(" ","")
    #print("The Number of spaces :",string.count(" "))
    print("The Number of spaces:" , len(string)-len(string_one))
    #The output is:
    The Number of spaces: 2
    

    The replace() is case sensitive

    string="Learning Python is Very Difficult"
    string_one=string.replace("Difficult", "Easy")
    print(string_one)
    #The output is:
    Learning Python is Very Easy

    If we enter the difficult instead of Difficult then the replace() method won't replace and returns as it is.

    string="Learning Python is Very Difficult"
    string_one=string.replace("difficult", "Easy")
    print(string_one)
    
    #The output is:
    Learning Python is Very Difficult
    
    All the string objects in Python are immutable, but we are replacing the string by using the replace() method by creating a new object.


    The proof is :

    string="ABABAABA"
    string_one=string.replace("A","B")
    print(string)
    print(string_one)
    #The output is:
    ABABAABA
    BBBBBBBB
    

    If we print the address of stringand string_one

    string="ABABAABA"
    print("Before Replacement address of string:", id(string))
    string_one=string.replace("A","B")
    print("After Replacement address of string:", id(string))
    #The output is:
    Before Replacement address of string: 7059760
    After Replacement address of string: 7059760
    

    Splitting and Joining of given String

    Splitting: The action of dividing into parts is called splitting.

    Example: The Wooden floor had cracked and split in the heat. 

    Splitting of Strings : Python provides an in-built split() method which splits the strings into a List.

    The syntax is

    string.split()

    The return type of split() method is always List.

    The following example demonstrates the use of a split() method

    string="Cher Cher Tech"
    l=string.split()
    print(l)
    #The output is:
    ['Cher', 'Cher', 'Tech']

    The Default separator for the split() method is white space; if we want to split the given string according to any other separator, then we have to pass the separators in arguments.

    splitting-python

    date="05-04-2019"
    new_date=date.split("-")
    for x in new_date:
        print(x)
    #The output is:
    05
    04
    2019

    Even we can decide that the given string should be divided into a particular number of elements by setting the parameter. If we set the parameter to 1 then, python will return the list with two elements.

    txt = "apple#banana#cherry#orange"
    x=string.split("#",1)
    print(x)
    #the output is:
    ['apple', 'banana#cherry#orange']

    Joining: Connecting the two things together is called as joining.

    Example: The two pieces of cloth are joined with velcro

    Joining of String: The join() is a string method that returns the string when the elements of the string are joined with string separator.

    joining-image-one

    The syntax for the join() method is

    string= seperator.join(iterable)
    #iterable could be list, tuple, set, array

    The following example demonstrates the join() method

    mytuple=("cher", "cher", "tech")
    x="#".join(mytuple)
    print(x)

    joint-method-one

    Another example demonstrates the join() method

    date=['04', '05', '2019']
    string='-'.join(date)
    print(string)
    #The output is:
    04-05-2019

    Changing the Case of characters of the String

    Case sensitive: The differentiation between the entered characters, whether they are in uppercase or Lowercase.

    If your programming language is case sensitive, which expects you to enter an uppercase letter won't respond if you enter lowercase letters.

    • Uppercase letters: ABCDEFGH
    • Lowercase Letters: abcdefgh

    Python provides five types of methods to change the case of the string

    • upper(): to Convert all the characters to uppercase
    • lower() : to convert all the characters to lowercase
    • swapcase(): Convert all the lowercase characters to uppercase and convert all the uppercase characters to lowercase.
    • title(): To convert all character to title case, means the first character in every word should be upper case, and all remaining characters should be in lower case.
    • capitalize(): Only the first character will be converted to upper case, and all remaining characters can be converted to lower case.

    The following example demonstrates changing the case of characters of the string

    string = 'learning Python is very Easy'
    print(string.upper()) 
    print(string.lower()) 
    print(string.swapcase())  
    print(string.title())
    print(string.capitalize())

    The output is

    LEARNING PYTHON IS VERY EASY
    learning python is very easy
    LEARNING pYTHON IS VERY eASY
    Learning Python Is Very Easy
    Learning python is very easy
    

    A program to check whether the given two strings are equal or not by ignoring case

    string_one=input("Enter First string:")
    string_two=input("Enter Second String:")
    if striong_one==string_two
        print("Both strings are equal:")
    else:
        print("Both the strings are not equal")

    If the user enter Review and review as inputs then, python returns strings are not equal because these two strings are the same, but the case is different.

    Enter First string:Review
    Enter Second String:review
    Both the strings are not equal

    To overcome this problem, we have to convert the end user given strings into either uppercase or lower case and then compare the two strings as shown below

    string_one=input("Enter First string:")
    string_two=input("Enter Second String:")
    if string_one.lower()==string_two.lower():
        print("Both strings are equal")
    else:
        print("Both the strings are not equal")

    The output is

    Enter First string:Review
    Enter Second String:review
    Both strings are equal

    And, if we enter two different strings then, the output is

    Enter First string:Rain
    Enter Second String:drop
    Both the strings are not equal
    

    The program is to check whether the provided username and password are valid or not(username should not be case sensitive, but the password should be case sensitive.

    username=input("Enter user Name:")
    pwd=input("Enter Password:")
    if username.lower()=="dhanvik" and pwd=="arrow":
        print("Valid User")
    else:
        print("Invalid User")  

    The username is irrespective of case sensitive and password is the case sensitive

    valid-user-output

    output-of-valid-user-one

    If we enter the password as Arrow, then python will inform it is an invalid user.

    output-of-invalid-user

    The program to convert the first and last character as upper case and all remaining characters should be the lower case of the given string

    s=input("Enter any string:")
    output=s[0].upper()+s[1:len(s)-1].lower()+s[-1].upper()
    print(output)

    The output is

    case-sensitive-four

    Check to start and end part of the string

    There are two methods to check whether the given string starts with the substring

    • s.startswith(substring) : Returns true if the string starts with provided substring.
    • s.endswith(substring) : Returns true if the string ends with provided substring.

    The following example to

    s='Learning python is very easy'
    print(s.startswith('Learning'))
    print(s.endswith('easy'))
    

    The output is:

    checking-starting-and-end-part-of-the-string

    Checking the different types of characters present in the string

    Python provides seven types of Methods to check types of characters present in the string

    • isalnum(): Returns True if all characters are alphanumeric( a to z, A to Z, 0 to9 )
    • isalpha(): Returns True if all characters are only alphabet symbols(a to z, A to Z)
    • isdigit(): Returns True if all characters are digits only( 0 to 9)
    • islower(): Returns True if all characters are lower case alphabet symbols
    • isupper() : Returns True if all characters are upper case alphabet symbols
    • istitle() : Returns True if the string is in title case
    • isspace() : Returns True if the string contains only spaces

    The following example demonstrates the use of all the above-mentioned Methods

    print('Sun786'.isalnum())=>True
     print('east786'.isalpha()) =>False 
     print('west'.isalpha())=>True 
    print('bengal'.isdigit()) => False 
     print('786786'.isdigit()) =>True
     print('abc'.islower()) =>True 
    print('Abc'.islower())=> False 
     print('abc123'.islower()) =>True 
    print('ABC'.isupper()) => True 
     print('Learning python is Easy'.istitle())=> False 
     print('Learning Python Is Easy'.istitle()) => True 
     print('    '.isspace()) => True 
    • In the above program, the first line contains both alphabets and numbers and hence python return True
    • The next line should contain only alphabets, but here both alphabets and numbers are present and hence python returns False.
    • The west contains only alphabets, and hence python returns True.
    • The bengal contains only alphabets but not numbers; python returns False.
    • isdigit() method checks for only digits, and hence returns True.
    • islower() method checks for lowercase alphabets, and hence, python returns True.
    • isupper() method checks for upper case alphabets and returns True.
    • istitle() method checks for title case if the first character of every word in the string is in uppercase and then python returns True or else returns false.

    The following program to check the type of character entered from the keyboard

    string=input('Enter any character:')
    if&
    Comment / Suggestion Section
    Point our Mistakes and Post Your Suggestions