Python is used in various software domains some application areas are given below.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. o Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc. Python has a simple syntax as compared to other languages.
Python allows a developer to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, means that the code can be executed as soon as it is written. It helps to provide a prototype very quickly.
Python can be described as a procedural way, an object-orientated way or a functional way.
The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
Python was created by Guido van Rossum, and released in 1991.
It is a general-purpose computer programming language. It is a high-level, objectoriented language which can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures, combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial intelligence domain.
It is easy to learn and require less code to develop the applications.
It is widely used for:
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code for maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.
Python is Interpreted language
Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
It is Free and open source
Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded free of cost.
It is Extensible
Extensible: It is very flexible and extensible with any module.
Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.
It has Built-in data structure
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.
Readability
High-Level Language
Cross-platform
Portable: Python programs can run on cross platforms without affecting its performance.
Literals can be defined as a data which is given in a variable or constant.
Python supports the following literals:
There are two parameters passing mechanism in Python:
By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function as well. It indicates the original variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is modified to a = 20. Both the variables denote to the same value.
The pass by value is that whenever we pass the arguments to the function only values pass to the function, no reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different values, and original value persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an arbitrary number of arguments.
A function is a section of the program or a block of code that is written once and can be executed whenever required in the program. A function is a block of self-contained statements which has a valid name, parameters list, and body. Functions make programming more functional and modular to perform modular tasks. Python provides several built-in functions to complete tasks and also allows a user to create new functions as well.
There are three types of functions:
Built-In Functions: copy(), len(), count() are the some built-in functions.
User-defined Functions: Functions which are defined by a user known as user-defined functions.
Anonymous Functions: These functions are also known as lambda functions because they are not declared with the standard def keyword.
Example: A general syntax of user defined function is given below.
def function_name(parameters list):
#--- statements---
return a_value
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
The user can use the remove() function to delete a specific object in the list.
Example:
list_1 = [ 3, 5, 7, 3, 9, 3 ]
print(list_1)
list_1.remove(3)
print("After removal: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either use del or pop.
Example:
list_1 = [ 3, 5, 7, 3, 9, 3 ]
print(list_1)
del list_1[2]
print("After deleting: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]
Note: You don't need to import any extra module to use these functions for removing an element from the list.
We cannot use these methods with a tuple because the tuple is different from the list.
To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.
Example:
string = " javatpoint "
string2 = " javatpoint "
string3 = " javatpoint"
print(string)
print(string2)
print(string3)
print("After stripping all have placed in a sequence:")
print(string.strip())
print(string2.strip())
print(string3.strip())
Output:
javatpoint
javatpoint javatpoint
After stripping all have placed in a sequence: Javatpoint javatpoint javatpoint
This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the random module. So, we need to import it and then we can call the function. It shuffles elements each time when the function calls and produces different output.
Example:
# import the random module
import random
# declare a list
sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']
print("Original LIST1: ")
print(sample_list1)
# first shuffle
random.shuffle(sample_list1)
print("\nAfter the first shuffle of LIST1: ")
print(sample_list1)
# second shuffle
random.shuffle(sample_list1)
print("\nAfter the second shuffle of LIST1: ")
print(sample_list1)
Output:
Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']
After the first shuffle of LIST1:
['V', 'U', 'W', 'X', 'Y', 'Z']
After the second shuffle of LIST1:
['Z', 'Y', 'X', 'U', 'V', 'W']
A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.
To create a tuple, we can declare it as below.
Example:
# Declaring tuple
tup = (2,4,6,8)
# Displaying value
print(tup)
# Displaying Single value
print(tup[2])
Output:
(2, 4, 6, 8)
It is immutable. So updating tuple will lead to an error.
Example:
# Declaring tuple
tup = (2,4,6,8)
# Displaying value
print(tup)
# Displaying Single value
print(tup[2])
# Updating by assigning new value
tup[2]=22
# Displaying Single value
print(tup[2])
Output:
tup[2]=22
TypeError: 'tuple' object does not support item assignment (2, 4, 6, 8)
The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.
Here, os and os.path - modules include a function for accessing the filesystem while shutil - module enables you to copy and delete the files.
In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode("utf8") function.
Example:
unicode_1 = ("\u0123", "\u2665", "\U0001f638", "\u265E", "\u265F", "\u2168")
print (unicode_1)
Output:
unicode_1: ('ģ', '♥', '😸', '♞', '♟', 'Ⅸ')
Global Variables:
Variables declared outside a function or in global space are called global variables.
If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we need to declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global keyword.
Global variables are accessible anywhere in the program, and any function can access and modify its value.
Example:
A = "JavaTpoint"
def my_function():
print(A)
my_function()
Output:
JavaTpoint
Local Variables
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local.
Local variables are accessible within local body only.
Example:
def my_function2():
K = "JavaTpoint Local"
print(K)
my_function2()
Output:
JavaTpoint Local
The namespace is a fundamental idea to structure and organize the code that is more useful in large projects. However, it could be a bit difficult concept to grasp if you're new to programming. Hence, we tried to make namespaces just a little easier to understand.
A namespace is defined as a simple system to control the names in a program. It ensures that names are unique and won't lead to any conflict.
Also, Python implements namespaces in the form of dictionaries and maintains nameto-object mapping where names act as keys and the objects as values.
| Criteria | Java | Python |
| Ease of use | Good | Very Good |
| Coding Speed | Average | Excellent |
| Data types | Static type | Dynamic type |
| Data Science and Machine learning application | Average | Very Good |
The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It provides a convenient way to associate the documentation.
String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".
String literals occurring immediately after another docstring are called "additional docstrings".
Python uses triple quotes to create docstrings even though the string fits on one line.
Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special chars.
Example:
# One-line docstrings
def hello():
"""A function to greet."""
return "hello"
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
Help() function: The help() function is used to display the documentation string and also facilitates us to see the help related to modules, keywords, and attributes.
Dir() function: The dir() function is used to display the defined symbols.
The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.
Example:
list_1 = ["A","B","C"]
s_1 = "Javatpoint"
# creating enumerate objects
object_1 = enumerate(list_1) 5. object_2 = enumerate(s_1)
print ("Return type:",type(object_1))
print (list(enumerate(list_1)))
print (list(enumerate(s_1)))
Output:
Return type:
[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7, 'i'), (8, 'n'), (9, 't')]
The __init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
Example:
class Employee_1:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E_1 = Employee_1("pqr", 20, 25000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E_1.name)
print(E_1.age)
print(E_1.salary) Output:
pqr 20
25000
PYTHONPATH is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate.
They have certain limitations: they don't support "vectorized" operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
NumPy is not just more efficient; it is also more convenient. We get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and we get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.
python is an interpreted language
Copyrights © 2024 letsupdateskills All rights reserved