Python Basic Tutorials

Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more

Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c

To make everything easy: We refer CPython as Python

Python Basic Concepts

Simple operations using python. [Console calculation]

One of the basic features of the python interpreter is you can use it as a simple calculator. In the python console, if you write an appropriate mathematical expression, it will show its result there. For example, If you write 3+3 then 6 will be displayed in the shell. Similarly, you can easily perform various operations using python. Examples Given below.

>>3+3
6
>>3+9
12
>>2/1
2
>>2**3
8

Syntax and Rules

  1. Identifier Rules
  2. Python identifiers are the name given to entities like class, functions, variables, etc whose values are assigned to them.
    • Identifiers can be the combination of letters(not case sensitive) or digits or an underscore_. The below examples are valid.
    • myvar=1
      my_var=1
      __name="Ram"
      myvar_1="hello"
    • An identifier can't be started with a digit. For example, 2Name is invalid but Name2 is a valid name.
    • We cannot use reserved keywords as an identifier. for example, writing def="name" will show an error message.
    • We cannot use any special symbols like! @,#,$,%, etc in the identifier name.
    • An identifier of any length is valid in python.
  3. Reserved words.
  4. The python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.

    Keywords are case-sensitive in python. Some keywords like None, False, True are case insensitive.
    In python 3.9, there are 33 reserved keywords, These are:

    False True as or with
    def elif except pass if
    in lambda yield raise try
    with break None and assert
    for del else finally class
    import is nonlocal from return
    while not global
  5. Lines and Indentations
  6. The group of the code is known as a block. Each block of the code is regarded as the grouping of the statements of code for a specific purpose. Most of the other programming languages like C, C++, Java uses {braces} to define a block of code. Unlike these languages, Python has its own rule to define the block of code i.e, Indentations. Whitespaces are used for the indentations in python. If nested indentations are needed, it is simply indented more towards the right.

    for i in range(10):
        print(i) #this line has indentation.
    a=2,b=3
    if a>b:
        print("a is greater.") # this line also has indentation.
    
    If the block of code is not indented properly, Then the interpreter throws the following error message: "IndentationError: expected an indented block"
  7. Comments in python.
  8. Comments are those parts that are ignored by the interpreter while interpreting the source code in python. These are written in order to enhance the readability and the understandability of the code in the future. There are two kinds of comments in python. The first one is single-line comments and another one is multiline comments(doc strings).

    Single line comments are created using '#' and multiline comments are created using triple quotation("""comment""").

    print("Single line comment") # This is single line comment.
    a=2
    b=3
    print("The sum of ",a,", ",b," is ",a+b)
    
    """This is the example of a multiline comment...
    In the above example, 2 and 3 are assigned to a and b respectively.
    And at last, its sum is displayed"""
    
    # multiline comments are also written using # on everylines
    # multiline comments1
    # multiline comments2
    # multiline comments3
  9. Newlines(Linebreak) and tabs.
  10. In Python strings,the backslash "\"is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a new line, and "\r" is a carriage return.

    \t-->tab
    \n-->newline
    \r-->carriage return
    >>print("Hello \n world")
    # output:
      Hello
      world
    
    >>print("Hello \t world")
    # output:
      Hello   world
    
    >>print("Hello \r world")
    # output:
      world
    
    

Python I/O and import

Python Input

Input means the data which may include strings, numbers, characters, etc that we ask the user to enter. If we want the user to enter any input, In python there's an input() function to allow this.


    input([Prompt])  # Returns the input as a string.

Let us take an example of programs that ask user to enter his age:

>>age=input("Enter your age: ")
Enter your age: 20
>>>print(age)
   20
>>>print(type(age)) # will output the type of variable that is "str"

By default input() function takes the input in string format. So if you want to change it to Integer or float you can simply convert this using float() and int() function.


>>>age=input("Enter your age:")
   Enter your age: 18 #default output is "str"
>>> #lets convert this to a integer
>>> age = int(age) # now the output is of "int" class

>>> # now  lets convert this to a float in a single line
>>>age=float(input("Enter your age:"))
    Enter your age: 18 #now this 18 is float.

Another way we can calculate the simple expression is by using an eval() function. It takes an expression as a string but calculates and gives the result in integer format for this particular example

>>>eval("2+3")
   5
>>>eval("2*3*4")
   32

Python Import

If we have to write large lines of code or if our program is big then we can divide programs into small programs and these divided small programs are regarded as a module. Modules are similar to small python programs.

Sometimes we need to get access to all the methods and functions that are written within a module to the main program. In this case, we can simply import these modules by using the "from" and 'import' keywords.

For example, if we need different mathematical functions to be accessed to the main program we can import and use the built-in math module as follows.


>>>import math # importing built in math module/library
>>>print(math.pi)
   3.141592653589793

We can define our own modules as well which are known as user-defined python modules. Let us define a module that contains a simple function sum, and we'll try to access that function from the main program.


#sum.py
def sum(a,b):
    return a+b

let us take two numbers from the user and find its sum using the sum function inside the sum.py module.


#main.py
from sum import sum# from the file we just created import the sum function
x=int("Enter the first number:")
y=int("Enter the second number:")
print("Sum is--> ",sum.sum(x,y))
Output:

Enter the first number: 30
Enter the second number: 20
Sum is--> 50

Python Output

we use print() function to display the output in python. For example, let's print something in python.

print() function can take n numbers of arguments


>>> # Example 1
>>>print("This is the message to be printed in the screen")
This is the message to be printed in the screen


# Example 2
>>>name="PythonTheRightWay"
>>>print("Hello, ",name)
   Hello, PythonTheRightWay


# Example 3
>>>part1="Python"
>>>part2="TheRightWay"
>>>print(part1,part2)
   Python TheRightWay

Output Formatting.

Output formatting is another way of printing the message on the screen which makes the code more attractive too.

Example:

>>> #Example 1
>>>a="PythonTheRightWay"
>>>print("Good Morning, {}.".format(a))
   Good Morning, PythonTheRightWay.

>>> #Example 2
>>>a=2
>>>b=3
>>>c=a+b
>>>print("The sum of {} and {} is {}.".format(a,b,c)) 
The sum of 2 and 3 is 5.
Python f-strings

Formatted String literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.

Lets take the similar example as above:


>>>a=2
>>>b=3
>>>c=a+b
>>>print(f"The sum of {a} and {b} is {c}.")
   The sum of 2 and 3 is 5.

Python Namespaces and scopes

Let's say, in real-life names are used to identify a person. Likewise, In programs, names are used to identify an object that is why they are called an identifier. So, now what is namespaces? A namespace is basically a system that controls all the names which we use in our program. It will assure all the names that we use in our program is unique and won't lead to any conflict. Sometimes there is a chance the name of the variable you are going to use is already existing as the name of another variable or as the name of another function or another method. In such situations, python namespaces come into play which handles such situations.

Types of Namespaces:

  1. Local Namespace:
  2. All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs.
  3. Global Namespace:
  4. This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the local namespace.
  5. Built-in Namespace:
  6. This is the highest level of the namespace which is available with default names available as part of the python interpreter that is loaded as the programming environment. It encompasses Global Namespace which in turn encompasses the local namespace.