Python Data Types and Input/output

Python Keywords:- 
  • Python Keywords are special reserved words that convey a special meaning to the compiler/interpreter.
  • Each keyword has a special meaning and a specific operation.
  • These keywords can't be used as a variable.
Following is the List of Python Keywords.

Consider the following explanation of keywords.
    1.    True - It represents the Boolean true if the given condition is true, then it returns "True". Non-zero values are treated as true.
    2.    False - It represents the Boolean false; if the given condition is false, then it returns "False". Zero value is treated as false
    3.    None - It denotes the null value or void. An empty list or Zero can't be treated as None.
    4.    and - It is a logical operator. It is used to check multiple conditions. It returns true if both conditions are true.

    5.    or - It is a logical operator in Python. It returns true if one of the conditions is true. Consider the following truth table.

    6.    not - It is a logical operator and inverts the truth value. Consider the following truth table.

    7.    assert - This keyword is used as the debugging tool in Python. It checks the correctness of the code. It raises an AssertionError if found any error in the code and also prints the message with an error.


    8.    def - This keyword is used to declare the function in Python. If followed by the function name.


    9.    class - It is used to represent the class in Python. The class is the blueprint of the objects. It is the collection of the variable and methods. Consider the following class.

    10.    continue - It is used to stop the execution of the current iteration. Consider the following example.


    11.    break - It is used to terminate the loop execution and control transfer to the end of the loop. Consider the following example.


    12.    If - It is used to represent the conditional statement. The execution of a particular block is decided by the if statement. Consider the following example.


    13.    else - The else statement is used with the if statement. When if the statement returns false, then else block is executed. Consider the


    14.    elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the previous condition is false, then check until the true condition is found. Condition the following example.


    15.    del - It is used to delete the reference of the object. Consider the following example.


    16.    try, except - The try-except is used to handle the exceptions. The exceptions are run-time errors. Consider the following example.


    17.    raise - The raise keyword is used to through the exception forcefully. Consider the following example.


    18.    finally - The finally keyword is used to create a block of code that will always be executed no matter the else block raises an error or not. Consider the following example.


    19.    for, while - Both keywords are used for iteration. The for the keyword is used to iterate over the sequences (list, tuple, dictionary, string). A while loop is executed until the condition returns false. Consider the following example.

    20.    import - The import keyword is used to import modules in the current Python script. The module contains a runnable Python code.


    21.    from - This keyword is used to import the specific function or attributes in the current Python script.


    22.    as - It is used to create a name alias. It provides the user-define name while importing a module.


    23.    pass - The pass keyword is used to execute nothing or create a placeholder for future code. If we declare an empty class or function, it will through an error, so we use the pass keyword to declare an empty class or function.

    24.    return - The return keyword is used to return the result value or none to called function.


    25.    is - This keyword is used to check if the two-variable refers to the same object. It returns the true if they refer to the same object otherwise false. Consider the following example.


    26.    global - The global keyword is used to create a global variable inside the function. Any function can access the global. Consider the following example.


    27.    nonlocal - The nonlocal is similar to the global and used to work with a variable inside the nested function(function inside a function). Consider the following example.


    28.    lambda - The lambda keyword is used to create the anonymous function in Python. It is an inline function without a name. Consider the following example.


    29.    yield - The yield keyword is used with the Python generator. It stops the function's execution and returns value to the caller. Consider the following example.


    30.    with - The with keyword is used in the exception handling. It makes code cleaner and more readable. The advantage of using with, we don't need to call close(). Consider the following example.


    31.    None - The None keyword is used to define the null value. It is remembered that None does not indicate 0, false, or any empty data types. It is an object of its data type, which is Consider the following example.

PYTHON - IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module, or other objects.
The rules to name an identifier are given below.
  • The first character of the variable must be an alphabet or underscore ( _ ).
  • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9).
  • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
  • Identifier name must not be similar to any keyword defined in the language.
  • Identifier names are case sensitive; for example, myname, and MyName is not the same.
  • Examples of valid identifiers: a123, _n, n_9, etc.
  • Examples of invalid identifiers: 1a, n%4, n 9, etc.
PYTHON - STATEMENT
  • Instructions that a Python interpreter can execute are called statements.
  • For example, a = 1 is an assignment statement.
  • if statement, for statement, while statement, etc. are other kinds of statements which will be discussed later.
Multi-line statement: - In Python, the end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\).
  • This is an explicit line continuation. - In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.
  • For instance, we can implement the above multi-line statement as:
  • Here, the surrounding parentheses ( ) do the line continuation implicitly.
  • Same is the case with [ ] and { }.
  • For example:
  • We can also put multiple statements in a single line using semicolons, as follows:

LINES AND INDENTATION
  • Python provides no braces to indicate blocks of code for class and function definitions or flow control.
  • Blocks of code are denoted by line indentation, which is rigidly enforced.
  • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.
  • However, the following block generates an error −
  • Thus, in Python, all the continuous lines indented with the same number of spaces would form a block.
  • Indentation refers to the spaces at the beginning of a code line.
  • Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
  • Python uses indentation to indicate a block of code.
  • Python will give you an error if you skip the indentation:
  • The number of spaces is up to you as a programmer, but it has to be at least one.
  • You have to use the same number of spaces in the same block of code, otherwise, Python will give you an error:
MULTI-LINE STATEMENTS
  • Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −
  • Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
QUOTATION IN PYTHON
  • Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.
  • The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
BASIC FUNDAMENTALS:
This section contains the fundamentals of Python, such as:
  1. Tokens and their types.
  2. Comments
  1. Tokens:
    • The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
    • The token is the smallest unit inside the given program.
    • There are the following tokens in Python:
      • Keywords.
      • Identifiers.
      • Literals.
      • Operators.
  2. Comments :
    • Comments can be used to explain Python code.
    • Comments can be used to make the code more readable.
    • Comments can be used to prevent execution when testing code.
    • A hash sign (#) that is not inside a string literally begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
    • This produces the following result −
    • You can type a comment on the same line after a statement or expression −
    • You can comment on multiple lines as follows −
    • Following triple-quoted string is also ignored by the Python interpreter and can be used as a multiline comment:

PYTHON VARIABLES
  • Variables are containers for storing data values.
  • Unlike other programming languages, Python has no command for declaring a variable.
  • A variable is created the moment you first assign a value to it.
  • Variables do not need to be declared with any particular type and can even change type after they have been set.
  • String variables can be declared either by using single or double quotes:
  • Example Variables in Python:
  • Variable is a name that is used to refer to memory location.
  • Python variable is also known as an identifier and used to hold value.
  • In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get variable type.
  • Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore.
  • It is recommended to use lowercase letters for the variable name.
  • Example: Bca and bca both are two different variables.
IDENTIFIER NAMING
  • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
    • A variable name must start with a letter or the underscore character
    • A variable name cannot start with a number
    • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    • Variable names are case-sensitive (age, Age, and AGE are three different variables)
    • Remember that variable names are case-sensitive
DECLARING VARIABLES AND ASSIGNING VALUES
  • Python does not bind us to declare a variable before using it in the application. It allows us to create a variable at the required time.
  • We don't need to declare explicitly variables in Python. When we assign any value to the variable, that variable is declared automatically.
  • The equal (=) operator is used to assign a value to a variable.
ASSIGN VALUE TO MULTIPLE VARIABLES
  • Python allows you to assign values to multiple variables in one line:
  • And you can assign the same value to multiple variables in one line:
OUTPUT VARIABLES
  • The Python print statement is often used to output variables.
  • To combine both text and a variable, Python uses the + character:
  • You can also use the + character to add a variable to another
  • For numbers, the + character works as a mathematical operator:
  • If you try to combine a string and a number, Python will give you an error:
GLOBAL VARIABLES
  • Variables that are created outside of a function (as in all of the examples above) are known as global variables.
  • Global variables can be used by everyone, both inside of functions and outside.
  • Example: - Create a variable outside of a function, and use it inside the function
  • If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
  • Example: - Create a variable inside a function, with the same name as the global variable
  • Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
  • To create a global variable inside a function, you can use the global keyword.
  • Example: - If you use the global keyword, the variable belongs to the global scope:
  • Also, use the global keyword if you want to change a global variable inside a function.
  • Example: - To change the value of a global variable inside a function, refer to the variable by using the global keyword:

SCOPE OF VARIABLES
  • The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the other parts. In python, the variables are defined with the two types of scopes.
    • Global variables
    • Local variables
  • The variable defined outside any function is known to have a global scope, whereas the variable defined inside a function is known to have a local scope.
LOCAL SCOPE
  • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

FUNCTION INSIDE FUNCTION
  • As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function:
  • Example: The local variable can be accessed from a function within the function:
GLOBAL SCOPE
  • A variable created in the main body of the Python code is a global variable and belongs to the global scope.
  • Global variables are available from within any scope, global and local.
  • Example: A variable created outside of a function is global and can be used by anyone:

SCOPE OF VARIABLES
  • Consider the following example.
  • Example 1 Local Variable

NAMING VARIABLES
  • If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):
  • Example: The function will print the local x, and then the code will print the global x:

GLOBAL KEYWORD
  • If you need to create a global variable but are stuck in the local scope, you can use the global keyword.
  • The global keyword makes the variable global.
  • Example: If you use the global keyword, the variable belongs to the global scope:
  • Also, use the global keyword if you want to make a change to a global variable inside a function.

OBJECT REFERENCES
  • It is necessary to understand how the Python interpreter works when we declare a variable. The process of treating variables is somewhat different from many other programming languages.
  • Python is a highly object-oriented programming language; that's why every data item belongs to a specific type of class. Consider the following example.
  • The Python object creates an integer object and displays it to the console. In the above print statement, we have created a string object. Let's check the type of it using the Python built-in type() function.
  • In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name.
  • Let's understand the following example "a = 50"
  • In the above image, the variable a refers to an integer object.
  • Suppose we assign the integer value 50 to a new variable b. 
  • The variable b refers to the same object that points to because Python does not create another object.
  • Let's assign the new value to b. Now both variables will refer to the different objects.
  • Python manages memory efficiently if we assign the same variable to two different values.
OBJECT IDENTITY
  • In Python, every created object identifies uniquely Python. Python provides the guaranteed that no two objects will have the same identifier. The built-in id() function, is used to identify the object identifier. Consider the following example.
  • We assigned the b = a, a, and b both point to the same object. When we checked by the id() function it returned the same number. We reassign a to 500; then it referred to the new object identifier.
PYTHON DATA TYPES
  • In programming, the data type is an important concept.
  • Variables can hold values, and every value has a data type.
  • Variables can store data of different types, and different types can do different things.
  • Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it.
  • The interpreter implicitly binds the value with its type. "a = 5"
  • The variable a holds integer value five and we did not define its type.
  • Python interpreter will automatically interpret variables as an integer type.
STANDARD DATA TYPES
  • A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id must be stored as an integer.
  • Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.
  1. Numbers int, complex, float
  2. Dictionary
  3. Boolean bool
  4. Set set, frozenset
  5. Sequence Type strings, list, tuple
1.    NUMBERS
  • Number stores numeric values.
  • The integer, float, and complex values belong to a Python Numbers data type.
  • Python provides the type() function to know the data type of the variable.
  • Similarly, the isinstance() function is used to check an object belongs to a particular class.
  • Python creates Number objects when a number is assigned to a variable. For example;
  • Number objects are created when you assign a value to them.
  • For example −
  • You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
  • You can delete a single object or multiple objects by using the del statement. For example −
  • Python supports three types of numeric data.
    • Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer. Its value belongs to int
    • Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate up to 15 decimal points.
    • complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
2.    DICTIONARY
  • Dictionary is an unordered set of a key-value pair of items.
  • It is like an associative array or a hash table where each key stores a specific value.
  • Key can hold any primitive data type, whereas value is an arbitrary Python object.
  • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
  • The items in the dictionary are separated with the comma (,)
  • Consider the following example.
  • Dictionaries have no concept of order among elements.
  • It is incorrect to say that the elements are "out of order"; they are simply unordered.
  • Consider the following example.

3.    BOOLEAN
  • Boolean type provides two built-in values, True and False.
  • These values are used to determine the given statement true or false.
  • It denotes by the class bool.
  • True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
  • Consider the following example.

4.    SET
  • Python Set is the unordered collection of the data type.
  • It is iterable, mutable(can modify after creation), and has unique elements.
  • In set, the order of the elements is undefined; it may return the changed sequence of the element.
  • The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma.
  • It can contain various types of values.
  • Consider the following example.

5.    SEQUENCE TYPE
  • String-
    • The string can be defined as the sequence of characters represented in quotation marks. In Python, we can use single, double, or triple quotes to define a string.
    • String handling in Python is a straightforward task since Python provides built-in functions and operators to perform operations in the string.
    • In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python".
    • The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
    • The following example illustrates the string in Python.
    • Consider the following example of string handling.

  • List-
    • Python Lists are similar to arrays in C.
    • However, the list can contain data of different types.
    • The items stored in the list are separated with a comma (,) and enclosed within square brackets [].
    • We can use slice [:] operators to access the data of the list.
    • The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings.
    • Consider the following example.
  • Tuple
    • A tuple is similar to the list in many ways.
    • Like lists, tuples also contain the collection of items of different data types.
    • The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
    • A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
    • Let's see a simple example of the tuple.

DATA TYPE CONVERSION
  • Sometimes, you may need to perform conversions between the built-in types.
  • To convert between types, you simply use the type name as a function.
  • There are several built-in functions to perform conversion from one data type to another.
  • These functions return a new object representing the converted value.
  1. int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.
  2. long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.
  3. float(x) - Converts x to a floating-point number.
  4. complex(real [,image]) - Creates a complex number.
  5. str(x) - Converts object x to a string representation.
  6. repr(x) - Converts object x to an expression string.
  7. eval(str) - Evaluates a string and returns an object.
  8. tuple(s) - Converts s to a tuple.
  9. list(s) - Converts s to a list.
  10. set(s) - Converts s to a set.
  11. dict(d) - Creates a dictionary. d must be a sequence of (key,value) tuples.
  12. frozenset(s) - Converts s to a frozen set.
  13. chr(x)- Converts an integer to a character.
  14. unichr(x) - Converts an integer to a Unicode character.
  15. ord(x) - Converts a single character to its integer value.
  16. hex(x) - Converts an integer to a hexadecimal string.
  17. oct(x) - Converts an integer to an octal string.

PYTHON INPUT AND OUTPUT FUNCTIONS

  • Python provides numerous built-in functions that are readily available to us at the Python prompt.
  • Some of the functions like input() and print() are widely used for standard input and output operations respectively.
  • Let us see the output section first.

PYTHON OUTPUT USING PRINT() FUNCTION

  • We use the print() function to output data to the standard output device (screen).
  • We can also output data to a file, but this will be discussed later.
  • An example of its use is given below.
  • Another example is given below:
  • In the second print() statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it.
  • The actual syntax/Signature of the print() function is:
    • Here, objects is the value(s) to be printed. The Symbol * indicates that there may be more than one object.
    • The sep separator (optional) is used between the values and its defaults into a space character ‘ ’.
    • After all, values are printed, end (optional) is printed, and its defaults into a new line.
    • The file (optional) is the object where the values are printed and its default value is sys.stdout (screen).
    • flush (optional): If True, the stream is forcibly flushed and its default value is False.
  • Here is an example to illustrate this.
  • Output
  • Here is an example to illustrate this.
  • Output:
  • The below example use print() with separator and end parameters.
  • Output:

OUTPUT FORMATTING

  • Sometimes we would like to format our output to make it look attractive.
  • This can be done by using the str.format() method.
  • This method is visible to any string object.
  • Here, the curly braces {} are used as placeholders.
  • We can specify the order in which they are printed by using numbers (tuple index).
  • We can specify the order in which they are printed by using numbers (tuple index).
  • Output
  • We can even use keyword arguments to format the string.
  • We can also format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.

PYTHON INPUT

  • Up until now, our programs were static. The value of variables was defined or hardcoded into the source code.
  • To allow flexibility, we might want to take the input from the user.
  • In Python, we have the input() function to allow this.
  • The syntax for input() is:
  • Where prompt is the string we wish to display on the screen.
  • It is optional.
  • Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
  • This same operation can be performed using the eval() function.
  • But eval takes it further.
  • It can evaluate even expressions, provided the input is a string
  • examples of input() function to understand its functionality.
  • Output:
  • The input() method returns string value. So, if we want to perform arithmetic operations, we need to cast the value first.
  • See the example below.
  • Output:

PYTHON IMPORT

  • When our program grows bigger, it is a good idea to break it into different modules.
  • A module is a file containing Python definitions and statements.
  • Python modules have a filename and end with the extension .py.
  • Definitions inside a module can be imported to another module or the interactive interpreter in Python.
  • We use the import keyword to do this.
  • For example, we can import the math module by typing the following line:
  • We can use the module in the following ways:
  • Output
  • Now all the definitions inside the math module are available in our scope.
  • We can also import some specific attributes and functions only, using the from keyword. For example:
  • While importing a module, Python looks at several places defined in sys.path.
  • It is a list of directory locations.
  • We can also add our own location to this list.

Comments

Popular posts from this blog

Classes and Objects

File Management in python

Exception Handling