echo '' ;

Python

  • Python is a scripting programming language.
  • Python is free and easy to learn.
  • Python is powerful object oriented programming
  • Comparable to Perl, Ruby, Scheme, or Java
  • Code can be grouped into modules and packages
  • Applications : Web applications, Automation, Scientific modelling, Big data applications and many more.

Python Modules

Many modules are available like math, os, time ,etc . please refer the link : https://docs.python.org/3/py-modindex.html


Python Real time using Applications

The Most Popular Python and Django Websites are listed Below

  • YouTube (python + django)
  • Dropbox (python +django)
  • Google (python +django)
  • Quora (python +django)
  • Instagram (python +django)
  • Spotify (python +django)
  • Reddit (python +django)
  • Yahoo map (python +django)
  • Hibmunk (python +django)


Python interpreter software

Install in windows

Note : tested on windows 10, 64bit with python 3.6.5.

  • Download & Install official python software from this link.
  • Once Installations done, now going to test the first getting started with hello world print sting example.

Install Android App

Get Start : Hello World Example

  • Open a new file with .py  extension. Ex : Hello-World.py .
  • Then write the Simple code print(“ArunEworld”) , and save that.
  • Now right click the file Hello-World.py  , you can see Edit with IDLE option. Open your file with that option.
  • Now Click the Run –> Run Module  in tab or click F5  Button.
  • Now another pop will open. that is the output windows the you can see you output or result also can see if any error in your program.
  • This example is a simple and just print the ArunEworld  word in the output screen using print  function.


Python IDE

PyCharm IDE



Install PIP : Install pip using this below link



Remember This

  • In c language like don’t need to put  ; Semicolon  command every end of the line. Because Python inter predictor run every line by line also paragraph. Ex print(“ArunEworld”)  this will execute with out error in python


Skip command

  • Single Line Skip : # (Hash). Example :  A = 0 #A is int Variable
  • Paragraph Skip : “””  (Triple Quat). Example :  “”” ArunEworld is a educational organization


Python Keyword

Totally 33 Keywords

  • ‘False’,
  • ‘None’,
  • ‘True’,
  • ‘and’,
  • ‘as’,
  • ‘assert’,
  • ‘break’,
  • ‘class’,
  • ‘continue’,
  • ‘def’,
  • ‘del’,
  • ‘elif’,
  • ‘else’,
  • ‘except’,
  • ‘finally’,
  • ‘for’,
  • ‘from’,
  • ‘global’,
  • ‘if’,
  • ‘import’,
  • ‘in’,
  • ‘is’,
  • ‘lambda’,
  • ‘nonlocal’,
  • ‘not’,
  • ‘or’,
  • ‘pass’,
  • ‘raise’,
  • ‘return’,
  • ‘try’,
  • ‘while’,
  • ‘with’,
  • ‘yield’
#!/usr/bin/env python3

"""
Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of the python source tree after building the interpreter and run:
./python Lib/keyword.py
"""

__all__ = ["iskeyword", "kwlist"]

kwlist = [
    # --start keywords--
    'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield',
    # --end keywords--
]

iskeyword = frozenset(kwlist).__contains__

def main():
    import sys
    import re

    args = sys.argv[1:]
    iptfile = args and args[0] or "Python/graminit.c"
    if len(args) > 1:
        optfile = args[1]
    else:
        optfile = "Lib/keyword.py"

    # load the output skeleton from the target, taking care to preserve its
    # newline convention.
    with open(optfile, newline='') as fp:
        format = fp.readlines()
        nl = format[0][len(format[0].strip()):] if format else '\n'

    # scan the source file for keywords
    with open(iptfile) as fp:
        strprog = re.compile('"([^"]+)"')
        lines = []
        for line in fp:
            if '{1, "' in line:
                match = strprog.search(line)
                if match:
                    lines.append(" '" + match.group(1) + "'," + nl)
        lines.sort()

    # insert the lines of keywords into the skeleton
    try:
        start = format.index("#--start keywords--" + nl) + 1
        end = format.index("#--end keywords--" + nl)
        format[start:end] = lines
    except ValueError:
        sys.stderr.write("target does not contain format markers\n")
        sys.exit(1)

    # write the output file
    with open(optfile, 'w', newline='') as fp:
        fp.writelines(format)

if __name__ == "__main__":
    main()


Python Functions


Print Function

  • Print function returns
  • Example 1 : print the strings with format specifier.

mystring = “ArunEworld” print(“String: %s” % mystring)

  • Example 2: You don’t need to declare the type of the variable with format spcifier print(“ArunEworld”)

Print the variables and numbers

myint = 7 print(myint) myfloat = 7.0 print(myfloat) myfloat = float(7) print(myfloat)

Print the Strings

mystring = ‘hello’ print(mystring) mystring = “hello” print(mystring) mystring = “Don’t worry about apostrophes” print(mystring) one = 1 two = 2 three = one + two print(three) hello = “hello” world = “world” helloworld = hello + ” ” + world print(helloworld) a, b = 3, 4 print(a,b

Error May Come

Error : Missing operator

# This will not work! one = 1 two = 2 hello = “hello” print(one + two + hello)

Error : for above program Traceback (most recent call last): File “<stdin>”, line 6, in <module> print(one + two + hello) TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Error : NameError

  • Code : if run like this print(ArunEworld)then the below error will come.
  • Error : NameError: name ‘ArunEworld’ is not defined .

Input function

How to make python to wait for a pressed key?

  • To use input() function to wait a  your python application coed
  • Ex : input(“Press Enter to continue…”)

Python Loops

  • If Loop
  • while loop

if loop

x = 1 if x == 1: # indented four spaces print(“x is 1.”)

While Loop

  • Repeat execute the your program based on the while condition if true.
  • Syntax while expression: statement(s)
    • Expression : True – Any non zero value or false (Any combination condition)
    • Statements : Your application code, Its may be single line of code or  multiple block of code.

Example

  • if the below example print the value 0 to 8 and then exits from while loop

count = 0 while (count < 9): print ‘The count is:’, count count = count + 1 print “Counter reach 9 value. !” print “ArunEworld”

output The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Counter reach 9 value ArunEworld

Infinite Loop using while

  • code : while true : print(“ArunEworld”)
  • output : ArunEworld  print infinite time, printing speed is based on system frequency.


Python List

  • Lists are very similar to arrays.
  • They can contain any type of variable, and they can contain as many variables as you wish.
  • Lists can also be iterated over in a very simple manner.
  • Here is an example of how to build a list.

mylist.append(1) mylist.append(2) mylist.append(3) print(mylist[0]) # prints 1 print(mylist[1]) # prints 2 print(mylist[2]) # prints 3 # prints out 1,2,3 for x in mylist: print(x)

List  : Accessing an index which does not exist generates an exception (an error).

mylist = [1,2,3] print(mylist[10])



Python Tuples

  • Tuples are listed items, But its can’t edited.


Python Basic Operators

Arithmetic Operators

number = 1 + 2 * 3 / 4.0 print(number)

Modulo Operators

remainder = 11 % 3 print(remainder)

Multiplication Operator

remainder = 11 % 3 print(remainder)

Using Operators with Strings

helloworld = “hello” + ” ” + “world” print(helloworld)

Python also supports multiplying strings to form a string with a repeating sequence:

lotsofhellos = “hello” * 10 print(lotsofhellos)

Using Operators with Lists

even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers print(all_numbers)

  • Another example

print([1,2,3] * 3)



User Defined Functions

Function Declaration:

Syntax : Def FunctionName(parameters) : ‘fucntion_docstring’ function_suite return [expression]

  • Def – Keyword (in python fuctions begin with keyword)
  • FunctionName – Function call name
  • () – Paranthsis
  • parameters – Any input perameters (Ardument replaed with this paranthesis
  • fucntion_docstring – Documentation fucntion of the string (Optional)
  • : – The code start every function
  • function_suite – Code Block
  • return [expression] – return statement of the function. With no arguments as same on.

Note : parameters, return expression and documentation strings are optional

Examples : A sample function named ‘square’ is defined here.

def square(n) : “Returns square of a given number” return n**2 print(square.__doc__) print(square(3)) print(square(10))

Result Returns square of a given number 9 100 >>>

  • def – keyword
  • square(n) : – Square is function Name
  • “Returns square of a given number” – Function Document contains the doc strings, will store in Special variable called “__doc__ “
  • return n**2 – Returns the square value using return statement
  • print(square.__doc__) – Doc string will be stored in special variable “__doc__” associative with function, and it can be access by using “.” Dot operator, as shown in the print statement.
  • print(square(3)) – By calling the square function with in the 3 argument value, The output will be the square of 9
  • print(square(10)) – By calling the square function with in the 100 argument value, The output will be the square of 10 is 100

Note : Any function can be called by passing required arguments inside the parenthesis within after the function name

Function call :

  • Function call generally 4 different arguments like Required Arguments, Keyword Arguments, Default Arguments, variable Length Arguments.

Note : Any function can be called by passing required arguments inside the parenthesis within after the function name

Function call type :

A function can be called using the following types of formal arguments

  • Required Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable length Arguments
Required Arguments
  • Required arguments are the non keyword arguments

Example def showname(name, age) : “This is fucntion displays the arguments passed” print(“Name : “, name) print(“Age : “, age) showname(“ArunEworld”, 21) showname(21, “ArunEworld”)

Results

  • In the example “showname” is the function withh two parameters as “name” and “age”.
  • This function is called twise with same non keyword arguments passed in different order.
  • In each of the calls the arguments which associated with paramete it involved which thier defined.
  • Here we observe the different when two calls.

(‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, 21) (‘Age : ‘, ‘ArunEworld’)

Keyword Arguments
  • Keyword arguments is use when function call.
  • Keyword arguments are identified by parameter name.
  • Keyword arguments can be called any order.

Example def showinfo(name, age) : ”’ This is fucntion displays passed values of a person name and age ”’ print(“Name : “, name) print(“Age : “, age) showinfo(“ArunEworld.com”, 21) showinfo(age = 21, name = “ArunEworld”)

Results (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21)

Default Arguments
  • A default argument is an argument that assumes a default value if a value is not provided in the function call for that arguments.

Example def showinfo_2(name, age=10 ) : ”’ This is fucntion displays passed values of a person name and age ”’ print(“Name : “, name) print(“Age : “, age) showinfo_2(“ArunEworld.com”) showinfo_2(age = 21, name = “ArunEworld”) showinfo_2(“ArunEworld”, age = 2) #showinfo_2(21, name = “ArunEworld”) # when its run get error like invalid function call

Results

  • Note : (very Important ) -> python does not allow passing non-keyword arguments after keyword arguments.

(‘Name : ‘, ‘ArunEworld.com’) (‘Age : ‘, 10) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 25)

Variable length Arguments

Example def showifo(name, *vartuple, ** vardict) : “”” this function displays all passed arguments””” print(“Nmae : “, name) for arg in vartuple: print(“variable non_kwd argument : “, arg”) for key in vardict: print(“variable kwd argument : “, vadict[key]) showinfo(“ArunEworld”) showinfo(“ArunPrakash”, 21, ‘M’, ‘Fb/ArunEworld’) showinfo(“ArunEworld”, 25, city=”bangalore”, sex=”M”


pdf2image 0.1.0



Python Interview Questions

Q : What are the key features of Python

  • Python is interpreted language.
  • Write your code or make your application with python is very easy and fast but running its very slow compared to compiled c programming.
  • Its Dynamically typed : No need to declare variable type. you can do with out error : x=5 , x=”ArunEworld”
  • Object Oriented programming like C++, – Allows define classes along with the composition and inheritance.
  • functions are first-class objects – This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
  • Applications : web applications, automation, scientific modelling, big data applications and many more

Q : What is the difference between list and tuples?

  • List : Its listed but can edited.
  • tuples : It’s are listed but can’t edited


Reference

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.