0% found this document useful (0 votes)
2 views

PYTHON

Python is a versatile, high-level programming language known for its clear syntax and dynamic typing, making it popular among developers. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and features like garbage collection and a rich standard library. Python allows for easy variable declaration and management, with local and global variable scopes, and is widely used across various sectors due to its open-source nature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PYTHON

Python is a versatile, high-level programming language known for its clear syntax and dynamic typing, making it popular among developers. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and features like garbage collection and a rich standard library. Python allows for easy variable declaration and management, with local and global variable scopes, and is widely used across various sectors due to its open-source nature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

What is Python

Python is a general-purpose, dynamically typed, high-level, compiled and interpreted,


garbage-collected, and purely object-oriented programming language that supports
procedural, object-oriented, and functional programming.

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 High-level - High-level language means human readable code.

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 Garbage Collected - Memory allocation and de-allocation are automatically


managed. Programmers do not specifically need to manage the memory.

o Purely Object-Oriented - It refers to everything as an object, including numbers and


strings.

o Cross-platform Compatibility - Python can be easily installed on Windows, macOS,


and various Linux distributions, allowing developers to create software that runs
across different operating systems.

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.

o Open Source - Python is an open-source, cost-free programming language. It is


utilized in several sectors and disciplines as a result.

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 The variable's first character must be an underscore or alphabet (_).

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.

o Examples of valid identifiers: a123, _n, n_9, etc.

o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

o Python doesn't tie us to pronounce a variable prior to involving it in the application.


It permits us to make a variable at the necessary time.

o In Python, we don't have to explicitly declare variables. The variable is declared


automatically whenever a value is added to it.

o The equal (=) operator is utilized to assign worth to a variable.

Object References

When we declare a variable, it is necessary to comprehend how the Python interpreter


works. Compared to a lot of other programming languages, the procedure for dealing with
variables is a little different.

Python is the exceptionally object-arranged programming language; Because of this, every


data item is a part of a particular class. Think about the accompanying model.

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.

Let's understand the following example

1. 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.

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

Consider the following valid variables name.

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.

11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, n


a56me)

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.

The multi-word keywords can be created by the following method.

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.

1. Assigning single value to multiple variables

Eg:

1. x=y=z=50

2. print(x)

3. print(y)

4. print(z)

Output:

50

50

50

2. Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15

2. print a

3. print b

4. print c

Output:

10

15

The values will be assigned in the order in which variables appear.

Python Variable Types

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():

3. # Defining local variables. They has scope only within a function

4. a = 20

5. b = 30

6. c=a+b

7. print("The sum is:", c)

8.

9. # Calling a function

10. add()

Output:

The sum is: 50

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()

2. # Accessing local variable outside the function

3. print(a)

Output:

The sum is: 50

print(a)

NameError: name 'a' is not defined

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 -

1. # Declare a variable and initialize it

2. x = 101

3.

4. # Global variable in function

5. def mainFunction():

6. # printing a global variable

7. global x

8. print(x)

9. # modifying a global variable

10. x = 'Welcome To Javatpoint'

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:

Traceback (most recent call last):

File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in

print(x)

NameError: name 'x' is not defined

Maximum Possible Value of an Integer in Python

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 -

1. # A Python program to display that we can store

2. # large numbers in Python

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.

There is no special data type for storing larger numbers in Python.

Print Single and Numerous Factors in Python

We can print numerous factors inside the single print explanation. The examples of single
and multiple printing values are provided below.

Example - 1 (Printing Single Variable)

1. # printing single value

2. a = 5

3. print(a)

4. print((a))

Output:

Example - 2 (Printing Multiple Variables)

1. a = 5

2. b = 6

3. # printing multiple variables

4. print(a,b)

5. # separate the variables by the comma

6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:

56

12345678

Basic Fundamentals:

This section contains the fundamentals of Python, such as:

i)Tokens and their types.

ii) Comments

a)Tokens:

o The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.

o The token is the smallest unit inside the given program.

There are following tokens in Python:

o Keywords.

o Identifiers.

o Literals.

o Operators.

Python Data Types

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

Current Time 0:22


/

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'>

Standard data types

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

2. print("The type of a", type(a))

3.

4. b = 40.5

5. print("The type of b", type(b))

6.

7. c = 1+3j

8. print("The type of c", type(c))


9. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>

The type of b <class 'float'>

The type of c <class 'complex'>

c is complex number: True

Python supports three kinds of numerical data.

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.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

The Python string is demonstrated in the following example.

Advertisement

Example - 1

1. str = "string using double quotes"

2. print(str)

3. s = '''''A multiline
4. string'''

5. print(s)

Output:

string using double quotes

A multiline

string

Look at the following illustration of string handling.

Example - 2

1. str1 = 'hello javatpoint' #string str1

2. str2 = ' how are you' #string str2

3. print (str1[0:2]) #printing first two character using slice operator

4. print (str1[4]) #printing 4th character of the string

5. print (str1*2) #printing the string twice

6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he

hello javatpointhello javatpoint

hello javatpoint how are you

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 (*).

Look at the following example.

Example:

1. list1 = [1, "hi", "Python", 2]

2. #Checking type of given list

3. print(type(list1))
4.

5. #Printing the list1

6. print (list1)

7.

8. # List slicing

9. print (list1[3:])

10.

11. # List slicing

12. print (list1[0:2])

13.

14. # List Concatenation using + operator

15. print (list1 + list1)

16.

17. # List repetation using * operator

18. print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]

[2]

[1, 'hi']

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

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.

Let's look at a straightforward tuple in action.

Example:
1. tup = ("hi", "Python", 2)

2. # Checking type of tup

3. print (type(tup))

4.

5. #Printing the tuple

6. print (tup)

7.

8. # Tuple slicing

9. print (tup[1:])

10. print (tup[0:1])

11.

12. # Tuple concatenation using + operator

13. print (tup + tup)

14.

15. # Tuple repatation using * operator

16. print (tup * 3)

17.

18. # Adding value to tup. It will throw an error.

19. t[2] = "hi"

Output:

<class 'tuple'>

('hi', 'Python', 2)

('Python', 2)

('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>

t[2] = "hi";

TypeError: 'tuple' object does not support item assignment

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.

Look at the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

2.

3. # Printing dictionary

4. print (d)

5.

6. # Accesing value using keys

7. print("1st name is "+d[1])

8. print("2nd name is "+ d[4])

9.

10. print (d.keys())

11. print (d.values())

Output:

1st name is Jimmy

2nd name is mike

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

dict_keys([1, 2, 3, 4])

dict_values(['Jimmy', 'Alex', 'john', 'mike'])

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.

Look at the following example.

1. # Python program to check the boolean type

2. print(type(True))

3. print(type(False))

4. print(false)

Output:

<class 'bool'>

<class 'bool'>

NameError: name 'false' is not defined

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.

Look at the following example.

1. # Creating Empty set

2. set1 = set()

3.

4. set2 = {'James', 2, 3,'Python'}

5.

6. #Printing Set value

7. print(set2)

8.

9. # Adding element to the set

10.

11. set2.add(10)

12. print(set2)
13.

14. #Removing element from the set

15. set2.remove(2)

16. print(set2)

Output:

{3, 'Python', 'James', 2}

{'Python', 'James', 3, 2, 10}

{'Python', 'James', 3, 10}

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.

Introducing Python Keywords

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.

False await else import

None break except in

True class finally is


and continue for lambda

as def from nonlocal

assert del global not

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

1. # Python program to demonstrate the application of iskeyword()

2. # importing keyword library which has lists

3. import keyword

4.

5. # displaying the complete list using "kwlist()."

6. print("The set of keywords in this version is: ")

7. print( keyword.kwlist )

Output:

The set of keywords in this version is :

['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']

By calling help(), you can retrieve a list of currently offered keywords:

Code

1. help("keywords")

How to Identify Python 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.

You might also like