Python Vs Java Comparison Python Java
Python Vs Java Comparison Python Java
Python Vs Java
Comparison Python Java
Performance Speed Fast Not as much as Python
Indentation Must be followed Using proper flower braces is enough
Typing Dynamically typed Static typed
Accessability Simple and compact Not as much as Python
Platforms Not compatible to many Platform independent
Database Access Weak compared to JAVA Strong (JDBC)
Q2. How is Python executed?
Python files are compiled to bytecode. which is then executed by the host.
Alternate
Answer:
Type python .pv at the command line.
.py files are Python source files. .pyc files are the compiled bvtecode files that is generated by the
Python compiler
Q4. How do you invoke the Python interpreter for interactive use?
python or pythonx.y where x.y are the version of the Python interpreter desired.
By indents or tabs. This is different from most other languages which use symbols to define blocks.
Indents in Python are significant.
Try, except and finally blocks are used in Python error handling. Code is executed in the try block
until an error occurs. One can use a generic except block, which will receive control after all errors,
or one can use specific exception handling blocks for various error types. Control is transferred to
the appropriate except block. In all cases, the finally block is executed. Raise may be used to raise
your own exceptions.
Accelerate your career with PYTHON TRAINING and become expertise Python developer.
Code Example:
try:
….#This can be any code
except:
…# error handling code goes here
finally.
…# code that will be executed regardless of exception handling goes here.
Q10. What happens if an error occurs that is not handled in the except block?
Functions are defined using the def statement. An example might be def foo(bar):
Classes are created using the class statement. An example might be class aa rdva rk(fooba r):
It overrides the any initialization from an inherited class, and is called when the class is instantiated.
Q16. How does a function return values?
Q17. What happens when a function doesn’t have a return statement? Is this valid?
Yes, this is valid. The function will then return a None object. The end of a function is defined by the
block of code being executed (i.e., the indenting) not by any explicit keyword.
The lambda operator is used to create anonymous functions. It is mostly used in cases where one
wishes to pass functions as parameters. or assign them to variable names.
Local namespaces are created within a function. when that function is called. Global name spaces
are created when the program starts.
Triple quotes „‟”” or „“ are string delimiters that can span multiple lines in Python. Triple quotes are
usually used when spanning multiple lines, or enclosing a string that has a mix of single and double
quotes contained therein.
Q23. Under what circumstances would von use a while statement rather than for?
The while statement is used for simple repetitive looping and the for statement is used when one
wishes to iterate through a list of items, such as database records, characters in a string, etc.
Q24. What happens if.ou put an else statement after after block?
The code in the else block is executed after the for loop completes, unless a break is encountered in
the for loop execution. in which case the else block is not executed.
When processing a particular item was complete; to move on to the next, without executing further
processing in the block. The continue statement says, “I‟m done processing this item, move on to the
next item.”
When the loop has served its purpose. As an example. after finding the item in a list searched for,
there is no need to keep looping. The break statement says, I‟m done in this loop; move on to the
next block of code.”
for in : … The ellipsis represents a code block to be executed, once for each item in the sequence.
Within the block the item is available as the current item from the entire list.
while : … The ellipsis represents a code block to be executed. until the condition becomes false. The
condition is an expression that is considered true unless it evaluates to o, null or false.
Q30. Use a for loop and illustrate how you would define and print the characters in a string
out, one per line.
Q31. Given the string “I LoveQPython” use afor loop and illustrate printing each character tip
to, but not including the Q.
Q32. Given the string “I Love Python” print out each character except for the spaces, using a
for loop.
inyString = I Love Python”
for myCizar in myString:
fmyChar == „‟ „‟:
continue
print myChar
i=1
while i < 10:
Q34. How to use GUI that comes with Python to test your code?
That is just an editor and a graphical version of the interactive shell. You write or load code and run
it, or type it into the shell.
There is no automated testing.
Python is a high-level general-purpose programming language that can be applied to many different
classes of problems.
The language comes with a large standard library that covers areas such as string processing like
regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP,
FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing,
logging, profiling, parsing Python code, and operating system interfaces like system calls, file
systems, TCP/IP sockets.
If you can‟t find a source file for a module, it may be a built-in or dynamically loaded module
implemented in C, C++ or other compiled language. In this case you may not have the source file or
it may be something like mathmodule.c, somewhere in a C source directory (not on the Python
Path). There are (at least) three kinds of modules in Python:
Modules written in Python (.py);
Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
Modules written in C and linked with the interpreter; to get a list of these, type;
Import sys print sys.builtin_module_names;
The most common problem is that the signal handler is declared with the wrong argument list. It is
called as:
handler (signum, frame)
So it should be declared with two arguments:
def handler(signum, frame):
Use the standard library module smtplib. Here‟s a very simple interactive mail sender that uses it.
This method will work on any host that supports an SMTP listener.
import sys, smtplib
fromaddr = raw_input(“From: “)
toaddrs = raw_input(“To: “).split(„,‟)
print “Enter message, end with ^D:”
msg = ”
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# The actual mail send
server = smtplib.SMTP(„localhost‟)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A UNIX-only alternative uses send mail. The location of the send mail program varies between
systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The send mail manual page
will help you out. Here‟s some sample code:
SENDMAIL = “/usr/sbin/sendmail” # sendmail location
import os
p = os.popen(“%s -t -i” % SENDMAIL, “w”)
p.write(“To: receiver@example.comn“)
p.write(“Subject: testn”)
p.write(“n”) # blank line separating headers from body
p.write(“Some textn”)
p.write(“some more textn”)
sts = p.close()
if sts != 0:
print “Sendmail exit status”, sts
Q43. How can I mimic CGI form submission (METHOD=POST)? I would like to retrieve web
pages that are the result of posting a form. Is there existing code that would let me do this
easily?
Q44. Why is that none of my threads are not running? How can I make it work?
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly,
giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that‟s long enough for all the threads to
finish:
import threading, time
def thread_task(name, n):
for i in range(n): print name, i
for i in range(10)
Download the required 3.6.1 python, executable installer file from the www.python.org.com website.
Installation Process:
Click on the downloaded executable installer
Click On „Run‟
Click on Customize Installation
Click on „Next‟
Select the installation location by clicking on browse button
Click on „Install‟
Click on „Yes‟
Click on „Close‟
Path: Path is an environment variable of operating system by using e=which we can make it
available the softwares which are installed in the directory to all other directions of the operating
system.
To set Path:
Right click on my computer
Click on properties
Click on Advanced system setting
Click on advanced
Click on environment variables
Go to system variables, select „path‟
Click on „edit‟
Copy the installation folder location of python software in the begging of the variable value
Click on „OK‟
Now path setting is secured.
Batch Mode:
In the concept of writing the group of python statements in a file, save the file with extension .py and
submit that entire file to the python interpreter is known as Batch Mode.
In Order to develop the python files we use editors or IDE‟s
Different editors are notepad, notepad++, edit+,nano, VI, gedil and so on.
Open the notepad and write the following code
Example:
X=1000
Y=2000
Print(x+y, x-y, x*y)
Save the file in D drive mindmajix python folder with the demo.py
Open command prompt and execute following commands
Python D:/mindmajix python/Demo.py
3000
-1000
2000.000
Save another method if we correctly set the path
D:
D:/>d mindmajix python
D:/mindmajix Python>python Demo.py
3000
-1000
2000.000
Mutable Objects:
1. The Objects which allows to modify the contents of those objects are known as „Mutable Objects‟
2. We can create two different mutable objects with same content
Program:
x=[10,20,30]
print(x)
print(type(x))
print(id(x))
y=[10,20,30]
print(y)
print(type(y))
print(id(y))
Output:
List, set, dict classes objects are mutable objects
Mutable objects performance is low when compared to immutable objects
Applying Iterations mutable objects takes huge time
By default python program execution starts from first line, execute each and every statements only
once and transactions the program if the last statement of the program execution is over.
Control flow statements are used to disturb the normal flow of the execution of the program.
Dictionary objects can be created by using curly braces {} or by calling dictionary function
Dictionary objects are mutable objects
Dictionary represents key value base
Each key value pair of Dictionary is known as a item
Dictionary keys must be immutable
Dictionary values can be mutable or immutable
Duplicate keys are not allowed but values can be duplicate
Insertion order is not preserved
Heterogeneous keys and heterogeneous values are allowed
A function which doesn‟t contain any name is known as a anonymous function lambda function
Syntax:
Lambda arguments:expression
Lambda function we can assign to the variable & we can call the lambda function through the
variable
Example:
myfunction=lambda x:x*x
a=myfunction(10)
print(a)
Output: 100
>>>
By default python interpreter search for the imported modules in the following locations:
Current directory (main module location)
Environment variable path
Installation dependent directory
If the imported module is not found in the any one of the above locations. Then python interpreter
gives error.
Built-in attributes of a module:
By default for each and every python module some properties are added internally and we call those
properties as a built-in-attribute of a module
File is a named location on the disk, which stores the data in permanent manner.
Python language provides various functions and methods to provide the communication between
python programs and files.
Python programs can open the file, perform the read or write operations on the file and close the file
We can open the files by calling open function of built-in-modules
At the time of opening the file, we have to specify the mode of the file
Mode of the file indicates for what purpose the file is going to be opened(r,w,a,b)
The concept of terminating the program in the middle of its execution without executing last
statement of the main module is known as a abnormal termination
Abnormal termination is undesirable situation in programming languages.
The concept of binding or grouping related data members along with its related functionalities is
known as a Encapsulation.
The concept of removing unused or unreferenced objects from the memory location is known as a
Garbage Collection.
While executing the program, if garbage collection takes place then more memory space is available
for the program and rest of the program execution becomes faster.
Garbage collector is a predefined program, which removes the unused or unreferenced objects from
the memory location
Any object reference count becomes zero then we call that object as a unused or unreferenced
object
Then no.of reference variables which are pointing the object is known as a reference count of the
object.
While executing the python program if any object reference count becomes zero, then internally
python interpreter calls the garbage collector and garbage collector will remove that object from
memory location.
DML Commands are used to modify the data of the database objects
Whenever we execute DML Commands the records are going to be modified temporarily
Whenever we run “rollback” command the modified records will come back to its original state
To modify the records of the database objects permanently we use “commit” command
After executing the commit command even though we execute “rollback” command, the modified
records will not come back to its original state
Create the emp1 table in the database by using following command
Create table emp1 as select * from emp;
Whenever we run the DML commands through the python program, then the no.of records which are
modified because of that command will be stored into the rowcount attribute of cursor object
After executing the DML Command through the python program we have to call commit method of
cursor object.
Thread Is a functionality or logic which can execute simultaneously along with the other part of the
program
Thread is a light weight process
Any program which is under execution is known as process
We can define the threads in python by overwriting run method of thread class
Thread class is a predefined class which is defined in threading module
Thread in module is a predefined module
If we call the run method directly the logic of the run method will be executed as a normal method
logic
In order to execute the logic of the run method as a we use start method of thread class.
Example
Import threading
Class x(threading.Thread):
Def run(self):
For p in range(1, 101):
print(p)
Class y(threading.Thread):
Def run(self):
For q in range(1, 101):
print(q)
x1=x()
y1=y()
x1.start()
y1.start()
Q65. What is scheduling?
Among multiple threads which thread as to start the execution first, how much time the thread as to
execute after allocated time is over, which thread as to continue the execution next this comes under
scheduling
Scheduling is highly dynamic
For loop takes the given object, convert that object in the form of iterable object & gets the one by
one element form the iterable object.
While getting the one by value element from the iterable object if stop iteration exception is raised
then for loop internally handle that exception
Q68. OS Module
OS Module is a predefined module and which provides various functions and methods to perform
the operating system related activities, such as creating the files, removing the files, creating the
directories removing the directories, executing the operating system related commands, etc.
Example:
Import os
cwd=os.getwd()
print(“1”, cwd)
os.chdir(“samples”)
print(“2”, os.getcwd())
os.chdir(os.pardir)
print(“3”,os.getcwd())
Output:
The concept of inheriting the properties from one class into multiple classes separately is known as
hierarchical inheritance.
Example:
Class x(object):
Def m1(self):
print(“in m1 of x”)
Class y(x):
Def m2(self):
print(“in m2 of y”)
Class z(x):
Def m3(self):
print(“in m3 of z”)
y1=y()
y1.m1()
y1.m2()
a=y1.--hash--()
print(a)
z1=z()
z1.m1()
z1.m3()
b=z1.hash--()
print(b)
Output:
M m1 of X
In m2 of Y
2337815
In m1 of X
In m3 of Z
2099735
>>>
Q70. What Are Applications of Python?
Applications of Python
Applications of Python Java .Net
Automation App NO NO
Data Analytics NO NO
Scientific App NO NO
Web App Yes Yes
Web Scrapping NO NO
Test Cases Yes Yes
Network with JOT Yes NO
Admin Script NO NO
GUI Yes Yes
Gaming Yes Yes
Animation NO NO