PYTHON
PYTHON
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version
of Python 0.9.0 was released in 1991. Since its release, Python started gaining popularity.
According to reports, Python is now the most popular programming language among
developers because of its high demands in the tech realm.
Features of Python:
o Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal
language for both beginners and experienced programmers. This simplicity can lead
to faster development and reduce the chances of errors.
o Dynamically Typed - The data types of variables are determined during run-time. We
do not need to specify the data type of a variable during writing codes.
o Compiled and Interpreted - Python code first gets compiled into bytecode, and then
interpreted line by line. When we download the Python in our system form org we
download the default implement of Python known as CPython. CPython is
considered to be Complied and Interpreted both.
o Rich Standard Library - Python comes with several standard libraries that provide
ready-to-use modules and functions for various tasks, ranging from web
development and data manipulation to machine learning and networking.
Python Variables
A variable is the name given to a memory location. A value-holding Python variable is also
known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable,
we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in
the program. The standards to name an identifier are given underneath.
o Every one of the characters with the exception of the main person might be a letter
set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the identifier
name. ^, &, *).
o Identifier name should not be like any watchword characterized in the language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName isn't
something very similar.
Object References
1. print("John")
Output:
John
The Python object makes a integer object and shows it to the control center. We have
created a string object in the print statement above. Make use of the built-in type() function
in Python to determine its type.
1. type("John")
Output:
<class 'str'>
In Python, factors are an symbolic name that is a reference or pointer to an item. The factors
are utilized to indicate objects by that name.
1. a = 50
1. a = 50
2. b = a
The variable b refers to the same object that a 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.
1. a = 50
2. b =100
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no
two items will have a similar identifier. The object identifier is identified using the built-in id()
function. consider about the accompanying model.
1. a = 50
2. b = a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id() function that we used
to check returned the same number. We reassign a to 500; The new object identifier was
then mentioned.
Variable Names
The process for declaring the valid variable has already been discussed. Variable names can
be any length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and
highlight character(_). Take a look at the names of valid variables in the following example.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
Output:
ABCDEDEFGFI
We have declared a few valid variable names in the preceding example, such as name,
_name_, and so on. However, this is not recommended because it may cause confusion
when we attempt to read code. To make the code easier to read, the name of the variable
ought to be descriptive.
o Camel Case - In the camel case, each word or abbreviation in the middle of begins
with a capital letter. There is no intervention of whitespace. For example -
nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital.
For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example
- name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single
statement, is a feature of Python.
We can apply different tasks in two ways, either by relegating a solitary worth to various
factors or doling out numerous qualities to different factors. Take a look at the following
example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
10
15
There are two types of variables in Python - Local variable and Global variable. Let's
understand the following variables.
Local Variable
The variables that are declared within the function and have scope within the function are
known as local variables. Let's examine the following illustration.
Example -
1. # Declaring a function
2. def add():
4. a = 20
5. b = 30
6. c=a+b
8.
9. # Calling a function
10. add()
Output:
Explanation:
We declared the function add() and assigned a few variables to it in the code above. These
factors will be alluded to as the neighborhood factors which have scope just inside the
capability. We get the error that follows if we attempt to use them outside of the function.
1. add()
3. print(a)
Output:
print(a)
We tried to use local variable outside their scope; it threw the NameError.
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole
program. Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable. Python
gives the worldwide catchphrase to utilize worldwide variable inside the capability. The
function treats it as a local variable if we don't use the global keyword. Let's examine the
following illustration.
Example -
2. x = 101
3.
5. def mainFunction():
7. global x
8. print(x)
11. print(x)
12.
13. mainFunction()
14. print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to it. We then created
a function and used the global keyword to access the declared variable within the function.
We can now alter its value. After that, we gave the variable x a new string value and then
called the function and printed x, which displayed the new value.
=
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in
future.
Example -
1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
print(x)
Python, to the other programming languages, does not support long int or float data types.
It uses the int data type to handle all integer values. The query arises here. In Python, what
is the maximum value that the variable can hold? Take a look at the following example.
Example -
3.
4. a = 10000000000000000000000000000000000000000000
5. a = a + 1
6. print(type(a))
7. print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number worth to variable x
and really look at its sort. It printed class <int> not long int. As a result, the number of bits is
not limited, and we are free to use all of our memory.
We can print numerous factors inside the single print explanation. The examples of single
and multiple printing values are provided below.
2. a = 5
3. print(a)
4. print((a))
Output:
1. a = 5
2. b = 6
4. print(a,b)
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
56
12345678
Basic Fundamentals:
ii) Comments
a)Tokens:
o The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.
o Keywords.
o Identifiers.
o Literals.
o Operators.
Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing
it. The interpreter binds the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data
types.
PauseNext
Mute
Duration 18:10
Loaded: 6.97%
Fullscreen
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can contain a variety of values. On the other hand, a person's id must be stored as
an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every
single one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a
place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
Advertisement
1. a = 5
3.
4. b = 40.5
6.
7. c = 1+3j
Output:
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with
int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Advertisement
Example - 1
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
A multiline
string
Example - 2
Output:
he
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put
away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
3. print(type(list1))
4.
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
13.
16.
Output:
[2]
[1, 'hi']
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Example:
1. tup = ("hi", "Python", 2)
3. print (type(tup))
4.
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
11.
14.
17.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
t[2] = "hi";
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
2.
3. # Printing dictionary
4. print (d)
5.
9.
Output:
dict_keys([1, 2, 3, 4])
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used
to create the set. It can contain different kinds of values.
2. set1 = set()
3.
5.
7. print(set2)
8.
10.
11. set2.add(10)
12. print(set2)
13.
15. set2.remove(2)
16. print(set2)
Output:
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any
Python program are Python keywords.
This tutorial will give you a basic overview of all Python keywords and a detailed discussion
of some important keywords that are frequently used.
Python keywords are unique words reserved with defined meanings and functions that we
can only apply for those functions. You'll never need to import any keyword into your
program because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods
and classes are constantly present; however, they are not as limited in their application as
keywords.
Assigning a particular meaning to Python keywords means you can't use them for other
purposes in our code. You'll get a message of SyntaxError if you attempt to do the same. If
you attempt to assign anything to a built-in method or type, you will not receive a
SyntaxError message; however, it is still not a smart idea.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we
have shown a complete list of Python keywords for the reader's reference.
async elif if or
In distinct versions of Python, the preceding keywords might be changed. Some extras may
be introduced, while others may be deleted. By writing the following statement into the
coding window, you can anytime retrieve the collection of keywords in the version you are
working on.
Code
3. import keyword
4.
7. print( keyword.kwlist )
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
Code
1. help("keywords")
Python's keyword collection has evolved as new versions were introduced. The await and
async keywords, for instance, were not introduced till Python 3.7. Also, in Python 2.7, the
words print and exec constituted keywords; however, in Python 3+, they were changed into
built-in methods and are no longer part of the set of keywords. In the paragraphs below,
you'll discover numerous methods for determining whether a particular word in Python is a
keyword or not.