PYTHON

PYTHON

Python Introduction :

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

What can Python do:

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development.

Python Basics:

1.Write a code in python
    Input:Hello, World!
    Output:Hello, World
  
  print("Hello, World!")
     Output:Hello, World!
2. Input : I LOVE My INDIA, LOVE MY Nation
    Output:I LOVE My INDIA, LOVE MY Nation
     
    print("I LOVE My INDIA, LOVE MY Nation")
          Output:I LOVE My INDIA, LOVE MY Nation
3.Input :Kiet1245, kaKiNada
   Output :Kiet1245, kaKiNada  
     
      print("Kiet1245, kaKiNada")
          Output: Kiet1245, kaKiNada

Try it your self:

1.Input :RajaTHe , Great:
   Output : RajaTHe , Great:
2.Input: For number in numbers !
   output : For number in numbers!
3.Input :Telugu && english
   Output :Telugu && english

Printing Methods in Python :

Great! We have seen how to print some really easy things. Let's explore more about the print method and see some really useful techniques

format() method

The format() method is useful when we want to construct a string by substituting values.
For example:
    print("{0} is a good {1}".format("Sachin","player"))
Output Sachin is a good player
For example:
                                    name = "Sachin"
                          position = "player"
                                     print("{0} is a good {1}".format(name, position))
                   Output : Sachin is a good player
Note that we started the text (called string in programming) with - this denotes that is a f-string.
The f-string constructs a new string by substituting the values given in the curly brackets {} with the appropriate values.

end parameter

You might have noticed that, up till now, every time we used the print statement it would print the text and then move to a new line.
However, sometimes we don't want it to move to a new line. In such cases, we make use of the end parameter to define a custom ending to the text.
For example:
print("Hello", end = "! ")
print("My", end = " ")
print("name is edyst")
The output of the above code is:
Hello! My name is edyst
Here, the is printed at the end of Hello. A space is printed after 'My', and a new line is printed after 'name is edyst'

Escape Characters

Till now, all of the statements we have printed did not include a or ' in their final output. What is we want to print those characters? How will we tell Python to not think of it as end of string, but rather think of it as part of the string?
This is where escape characters come in. Have a look at the following and their uses:
Escape SequenceDescriptionExampleOutput
\\Prints Backslashprint("\\")\
\Prints single-quoteprint("\'")'
\"Pirnts double quoteprint("\"")"
\tASCII horizontal tab (TAB)print("\t* hello")* hello
For example:
print("She asked, \"What's your name?\"")
# Output: She asked, "What's your name?"
Notice how we escaped the quotes in order to print them
Another example:
print("Python is \\awesome\\")
# Output: Python is \awesome\
In the above code, we have escaped the backslash

Try it your self:

1.Using the concept of f-strings, print the following statement by substituting the name of countries and capitals:
   
Input:New Delhi is the capital of India
Madrid is the capital of Spain
2.Using the concept of escape sequences, print the following statement:
She asked, "What's your name?"
3.Using the concept of escape sequences, print the following statement:
Python is \awesome\
4.Using the format method, print the following statement by substituting the name of friends:
Alex, Laxmi and Jay went to the party
5.Using the concept of f-strings, print the following statement by substituting the ages:
Riya's age is 5
Mahesh is 10
And their best friend, Arjun, is 12

Python Main Function with Examples: Understand __main__

Before we jump more into Python coding, we get familiarize with Python Main function and its importance.
Consider the following code
def main():
     print ("hello world!")
print ("KIET")
Here we got two pieces of print one is defined within a main function that is "Hello World" and the other is independent which is "KIET". When you run the function def main ():
  • Only "KIET" prints out
  • and not the code "Hello World."
Learn Python Main Function with Examples: Understand __main__
It is because we did not declare the call function "if__name__== "__main__".
  • When Python interpreter reads a source file, it will execute all the code found in it.
  • When Python runs the "source file" as the main program, it sets the special variable (__name__) to have a value ("__main__").
  • When you execute the main function, it will then read the "if" statement and checks whether __name__ does equal to __main__.
  • In Python "if__name__== "__main__" allows you to run the Python files either as reusable modules or standalone programs.
Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways
  • import: __name__= module's filename
    if statement==false, and the script in __main__ will not be executed
  • direct run:__name__=__main__
    if statement == True, and the script in _main_will be executed
  • So when the code is executed, it will check for module name with "if."
It is important that after defining the main function, you call the code by if__name__== "__main__" and then run the code, only then you will get the output "hello world!" in the programming console as shown below.
Learn Python Main Function with Examples: Understand __main__
Note: Make sure that after defining a main function, you leave some indent and not declare the code right below the def main(): function otherwise it will give indent error.
def main():
  print("Hello World!")
  
if __name__== "__main__":
  main()

print("KIET")
OUTPUT : Hello World
KIET
def main():
  print("Hello World!")
  
main()
print("KIET")
OUTPUT : Hello World
KIET

Python Variables: Declare, Concatenate, Global & Local 

What is a Variable in Python?

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc.
In this tutorial, we will learn,

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


  • Delete a variable
  • How to Declare and use a Variable

    Let see an example. We will declare variable "a" and print it.
    a=100 
    print a

    Re-declare a Variable

    You can re-declare the variable even after you have declared it once.
    Here we have variable initialized to f=0.
    Later, we re-assign the variable f to value "guru99"
    Variables in Python

    Concatenate Variables

    Let's see whether you can concatenate different data types like string and number together. For example, we will concatenate "Guru" with the number "99".
    Unlike Java, which concatenates number with string without declaring number as string, Python requires declaring the number as string otherwise it will show a TypeError.
    Variables in Python
    For the following code, you will get undefined output -
    a="Guru"
    b = 99
    print a+b
    
    Once the integer is declared as string, it can concatenate both "Guru" + str("99")= "Guru99" in the output.
    a="Guru"
    b = 99
    print(a+str(b))

    Local & Global Variables

    In Python when you want to use the same variable for rest of your program or module you declare it a global variable, while if you want to use the variable in a specific function or method, you use a local variable.
    Let's understand this difference between local and global variable with the below program.
    1. Variable "f" is global in scope and is assigned value 101 which is printed in output
    2. Variable f is again declared in function and assumes local scope. It is assigned value "I am learning Python." which is printed out as an output. This variable is different from the global variable "f" define earlier
    3. Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of "f" is it displays the value of global variable f=101
    Variables in Python
    Example
    # Declare a variable and initialize it
    f = 101
    print(f)
    # Global vs. local variables in functions
    def someFunction():
    # global f
        f = 'I am learning Python'
        print(f)
    someFunction()
    print(f)
    Using the keyword global, you can reference the global variable inside a function.
    1. Variable "f" is global in scope and is assigned value 101 which is printed in output
    2. Variable f is declared using the keyword global. This is NOT a local variable, but the same global variable declared earlier. Hence when we print its value, the output is 101
    3. We changed the value of "f" inside the function. Once the function call is over, the changed value of the variable "f" persists. At line 12, when we again, print the value of "f" is it displays the value "changing global variable"
    Variables in Python
    Python 2 Example
    f = 101;
    print f
    # Global vs.local variables in functions
    def someFunction():
      global f
      print f
      f = "changing global variable"
    someFunction()
    print f 
    Python 3 Example
    f = 101;
    print(f)
    # Global vs.local variables in functions
    def someFunction():
      global f
      print(f)
      f = "changing global variable"
    someFunction()
    print(f)

    Delete a variable

    You can also delete variable using the command del "variable name".
    In the example below, we deleted variable f, and when we proceed to print it, we get error "variable name is not defined" which means you have deleted the variable.
    Variables in Python
    f = 11;
    print(f)
    del f
    print(f)

    Summary:

    • Variables are referred to "envelop" or "buckets" where information can be maintained and referenced. Like any other programming language Python also uses a variable to store the information.
    • Variables can be declared by any name or even alphabets like a, aa, abc, etc.
    • Variables can be re-declared even after you have declared them for once
    • In Python you cannot concatenate string with number directly, you need to declare them as a separate variable, and after that, you can concatenate number with string
    • Declare local variable when you want to use it for current function
    • Declare Global variable when you want to use the same variable for rest of the program
    • To delete a variable, it uses keyword "del".

    Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase

    In Python everything is object and string are an object too. Python string can be created simply by enclosing characters in the double quote.
    For example:
    var = "Hello World!"
    In this tutorial, we will learn -
    • Accessing Values in Strings
    • Various String Operators
    • Some more examples
    • Python String replace() Method
    • Changing upper and lower case strings
    • Using "join" function for the string
    • Reversing String
    • Split Strings
    • Accessing Values in Strings

      Python does not support a character type, these are treated as strings of length one, also considered as substring.
      We use square brackets for slicing along with the index or indices to obtain a substring.
      var1 = "Guru99!"
      var2 = "Software Testing"
      print ("var1[0]:",var1[0])
      print ("var2[1:5]:",var2[1:5])

      Various String Operators

      There are various string operators that can be used in different ways like concatenating different string.
      Suppose if a=guru and b=99 then a+b= "guru99". Similarly, if you are using a*2, it will "GuruGuru". Likewise, you can use other operators in string.

      OperatorDescriptionExample
      []Slice- it gives the letter from the given indexa[1] will give "u" from the word Guru as such ( 0=G, 1=u, 2=r and 3=u)
      x="Guru"
      print x[1]
      [ : ]Range slice-it gives the characters from the given rangex [1:3] it will give "ur" from the word Guru. Remember it will not consider 0 which is G, it will consider word after that is ur.
      x="Guru" 
      print x[1:3]
      
      inMembership-returns true if a letter exist in the given stringu is present in word Guru and hence it will give 1 (True)
      x="Guru" 
      print "u" in x
      
      not inMembership-returns true if a letter exist is not in the given stringl not present in word Guru and hence it will give 1
      x="Guru" 
      print "l" not in x
      
      r/RRaw string suppresses actual meaning of escape characters.Print r'\n' prints \n and print R'/n' prints \n
      % - Used for string format%r - It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for displayThe output of this code will be "guru 99".
      name = 'guru'
      number = 99
      print'%s %d' % (name,number)	
      +It concatenates 2 stringsIt concatenate strings and gives the result
      x="Guru" 
      y="99" 
      print x+y
      *RepeatIt prints the character twice.
      x="KIET" 
      y="99" 
      print x*2
      

    Some more examples

    You can update Python String by re-assigning a variable to another string. The new value can be related to previous value or to a completely different string all together.
    x = "Hello World!"
    print(x[:6]) 
    print(x[0:6] + "Guru99")
    Note : - Slice:6 or 0:6 has the same effect

    Python String replace() Method

    The method replace() returns a copy of the string in which the values of old string have been replaced with the new value.
    oldstring = 'I like Guru99' 
    newstring = oldstring.replace('like', 'love')
    print(newstring)

    Changing upper and lower case strings

    In Python, you can even change the string to upper case or lower case.
    string="python at guru99"
    print(string.upper())
    
    Likewise, you can also do for other function as well like capitalize
    string="python at guru99"		
    print(string.capitalize())
    You can also convert your string to lower case
    string="PYTHON AT GURU99"
    print(string.lower())

    Using "join" function for the string

    The join function is a more flexible way for concatenating string. With join function, you can add any character into the string.
    For example, if you want to add a colon (:) after every character in the string "Python" you can use the following code.
    print(":".join("Python"))	

    Reversing String

    By using the reverse function, you can reverse the string. For example, if we have string "12345" and then if you apply the code for the reverse function as shown below.
    string="12345"		
    print(''.join(reversed(string)))

    Split Strings

    Split strings is another function that can be applied in Python let see for string "guru99 career guru99". First here we will split the string by using the command word.split and get the result.
    word="guru99 career guru99"		
    print(word.split(' '))
    To understand this better we will see one more example of split, instead of space (' ') we will replace it with ('r') and it will split the string wherever 'r' is mentioned in the string
    word="guru99 career guru99"		
    print(word.split('r'))
    Important Note:
    In Python, Strings are immutable.
    Consider the following code
    x = "Guru99"
    x.replace("Guru99","Python")
    print(x)
    will still return Guru99. This is because x.replace("Guru99","Python") returns a copy of X with replacements made
    You will need to use the following code to observe changes
    x = "Guru99"
    x = x.replace("Guru99","Python")
    print(x)

    Summary:

    Since Python is an object-oriented programming language, many functions can be applied to Python objects. A notable feature of Python is its indenting source statements to make the code easier to read.
    • Accessing values through slicing - square brackets are used for slicing along with the index or indices to obtain a substring.
      • In slicing, if range is declared [1:5], it can actually fetch the value from range [1:4]
    • You can update Python String by re-assigning a variable to another string
    • Method replace() returns a copy of the string in which the occurrence of old is replaced with new.
      • Syntax for method replace: oldstring.replace("value to change","value to be replaced")
    • String operators like [], [ : ], in, Not in, etc. can be applied to concatenate the string, fetching or inserting specific characters into the string, or to check whether certain character exist in the string
    • Other string operations include
      • Changing upper and lower case
      • Join function to glue any character into the string
      • Reversing string
      • Split string



    Comments

    1. Thankyou for sharing this blog this is really helpful and informative. Great Share! Else anyone interested in Python Couse, Contact Us On 9311002620 or You can Visit our Website : https://www.htsindia.com/Courses/python/python-training-institute-in-south-delhi

      ReplyDelete

    Post a Comment