0% found this document useful (0 votes)
9 views49 pages

Basics of Pyhton

PYTHON
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views49 pages

Basics of Pyhton

PYTHON
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Python

1
• INTRODUCTION TO FUNCTION
• MODULES AND PACKAGES
• FILE OPERATIONS
• CLASSES AND OBJECTS
• EXCEPTION HANDLING
• INTRODUCTION TO OOPS
• DATABASE
• GUI PROGRAMMING
• MULTITHREADING
• REGULAR EXPRESSIONS
• PYTHON MODULES
• PYTHON MATPLOTLIB 2
contents
• GETTING STARTED
• PYTHON FUNDAMENTALS
• DATA HANDLING
• STRING MANIPULATION
• LIST MANIPULATION
• TUPLES
• DICTIONARIES
• SET AND FROZENSET
• OPERATORS
• PROGRAM CONTROL FLOW
3
1. GETTING STARTED
1.1 History and need of python
1.2 Applications of python
1.3 Advantages of python
1.4 Disvantages of python
1.5 Installing python
1.6 program structure
1.7 Interactive Shell
1.8 Executable or script files
1.9 Userinterface or IDE

4
History of python

• Python is an programming language,It was created by Guido van Rossum, and released
in 1991.
• Python is an interpreted high-level general-purpose programming language. Its design
philosophy emphasizes code readability with its use of significant indentation. Its
language constructs as well as its object-oriented approach aim to help programmers
write clear, logical code for small and large-scale projects.
• Guido van Rossum began working on Python in the late 1980s, as a successor to the ABC
programming language, and first released it in 1991 as Python 0.9.0. Python 2.0 was
released in 2000 and introduced new features, such as list comprehensions and a
garbage collection system using reference counting. Python 3.0 was released in 2008
and was a major revision of the language that is not completely backward-compatible.
Python 2 was discontinued with version 2.7.18 in 2020.

• Python consistently ranks as one of the most popular programming languages.


5
• fun fact: The Name python is inspired from an BBC comedy series “monty python’s flying
car”. Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python.

• Python is dynamically-typed and garbage-collected. It supports multiple programming


paradigms, including structured (particularly, procedural), object-oriented and functional
programming. It is often described as a "batteries included" language due to its
comprehensive standard library.

• Since 2003, Python has consistently ranked in the top ten most popular programming
languages in the TIOBE Programming Community Index where, as of February 2021, it is
the third most popular language (behind Java, and C). It was selected Programming
Language of the Year (for "the highest rise in ratings in a year") in 2007, 2010, 2018, and
2020 (the only language to do so four times).
6
An empirical study found that scripting languages, such as Python, are more
productive than conventional languages, such as C and Java, for programming
problems involving string manipulation and search in a dictionary, and determined
that memory consumption was often "better than Java and not much worse than C
or C++".

Large organizations that use Python include Wikipedia, Google, Yahoo!, CERN,
NASA, Facebook, Amazon, Instagram, Spotify and some smaller entities like ILM
and ITA. The social news networking site Reddit was written mostly in Python.

7
1.2 Application of python

The applications are:


i. Web and internet development
ii. Games
iii Language development
iv. Operating system
v. Image processing and graphic design application
vi. Scientific and computational applications
vii. Business application development

8
1.3 Advantages of python

The advantages are:


a)Interpreted
b)Free and open source
c)Extensible
d)Object oriented
e)Built-in data structure
f)Readability
g)High-level language
h)Cross platform
1.4 Disadvantages of python
Disadvantages of Python are:
Speed
Python is slower than C or C++. But of course, Python is a high-level language, unlike C or
C++
it's not closer to hardware.

Mobile Development
Python is not a very good language for mobile development . It is seen as a weak language
for mobile computing. This is the reason very few mobile applications are built in it like
Carbonnelle.

Memory Consumption
Python is not a good choice for memory intensive tasks. Due to the flexibility of the
data-types, Python's memory consumption is also high. 10
Database Access
Python has limitations with database access . As compared to the
popular technologies like JDBC and ODBC, the Python's database
access layer is found to be bit underdeveloped and primitive .
However, it cannot be applied in the enterprises that need
smooth interaction of complex legacy data .

Runtime Errors
Python programmers cited several issues with the design of the
language. Because the language is dynamically typed , it requires
more testing and has errors that only show up at runtime .
11
1.5 Installing python

To install python ,we need to go to python’s official site.


step1 :visit https://www.python.org/ , In their we can see an option download from there we
can get the latest version of python.
step 2: after download Install that pacakage and make it run.
step3 : To check if all are done correctly, go to commad prompt in your pc.
step4: type python --version , we will get version of the python if it is installed.
And if we type python , we can run python command their too, for checking purpose.

12
1.6 program structure
Attributes and Imports:
The structure Python Program consists of three files such as : aa.py,bb.py and cc.py. The
file model aa.py is chosen for high level file . it is known as a simple text file of
statements. And it can be executed from bottom to top when it is launched. Files bb.py
and c.py are modules. They are calculated as better text files of statements as well. But
they are generally not started Directly. Identically this attributes define Programming
structure of Python.

Functions:
For example bb.py defines a function called spam. For external use. bb.py has python def
statement to start the function.later operated by passing one or more values like the
below.
Def spam(text): print text, ‘spam’
If aa.py wants to use spam, it has python statements like below
Import bb bb.spam (‘gumby’)
13
Statements:
Python import statement gives file aa.py access to file bb.py. it shows that “load
filebb.py” and gives access to all its attributes by name bb” import statements will
execute and implement other file for at run-time. In python cross file module is not
updated until import statements are executed .
The next part is statements will call the function spam. module b used by object
attribute notation. bb.spam means get value of name spam within object bb. And
we can implement a string in parenthesis if these files run by aa.py.
In regular if we see object. Attribute in total python scripts. Many objects have
attributes traced by “python operators".
The process of Importing considered as general in total python. Any sort of file can
get tools from any file. Getting of chains can be go as deep as you can . By this
Instance you will get it notified module aa can import bb and bb can Import cc, and
cc again Imports bb. correspondingly this statements include Programming
structure of Python.
14
Modules :
If we take this as a part , python serves as biggest company structure. Modules
are having top end of code. By coding components in module files.used in any
program files.If we take an example function bb.spam is regular purpose tool. We
can again implement that in a different program. This is simply known as bb.py
from any other program files.
Standard library files:
Python has large collection of modules known as standard library.it contains 200
modules at last count. It is platform independent common programming works.
Such as GUI Design, Internet and network scripting. Text design matching,
Operating system Interfaces. So, Comparatively all the Above will explain
Programming structure of Python.

15
1.7 Interactive Shell

The Python interpreter can be used from an interactive shell.

The interactive shell is also interactive in the way that it stands between the commands or actions
and their execution. In other words, the shell waits for commands from the user, which it executes
and returns the result of the execution. Afterwards, the shell waits for the next input.
open cmd then type “python”.
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
after that this command will be appearing , and your shell is started.
we can write python commands and to exit that we can type exit()

16
1.8 Executable or Script files

The file with extension .py are python files, which has python scripits or program to execute
some problem or anything as an output.

The most basic and the easy way to run Python scripts is by using the python command. You
need to open a command-line and type the word python followed by the path to your script
file, like this: python first_script.py Hello World! Then you hit the ENTER button from the
keyboard and that's it.

17
1.9 User Interface or IDE

IDE stands for Integrated Development Environment. It’s a coding tool which allows you to
write, test, and debug your code in an easier way, as they typically offer code completion
or code insight by highlighting, resource management, debugging tools,… And even
though the IDE is a strictly defined concept, it’s starting to be redefined as other tools such
as notebooks start gaining more and more features that traditionally belong to IDEs.

• popular IDE
• Visual studio code
• pycharm
• Jupiter etc...

18
2. PYTHON FUNDAMENTALS

2.1 Working with Interactive Mode.


2.2 Working with script mode.
2.3 Python character set.
2.4 Python Token, keywords, Identifiers,Literals,Operators variables,Assignments
2.5 Input and output in python

19
2.1 Working with Interactive Mode

The interactive mode involves running your codes directly on the Python shell which
can be accessed from the terminal of the operating system.

The code executes via the Python shell, which comes with Python installation.
Interactive mode is handy when you just want to execute basic Python commands or
you are new to Python programming and just want to get your hands dirty with this
beautiful language.

To access the Python shell, open the terminal of your operating system and then type
"python". Press the enter key and the Python shell will appear. This is the same Python
executable you use to execute scripts, which comes installed by default on Mac and
Unix-based operating systems.

20
The >>> indicates that the Python shell is ready to execute and send your commands to the Python
interpreter. The result is immediately displayed on the Python shell as soon as the Python
interpreter interprets the command.
eg1:
>>> print("Hello World")
Hello World
>>>
eg2:
>>> 122
122
>>> print(4 * 20)
80
>>> "py" * 5
'pypypypypy'
>>>
21
The following are the advantages of running your code in interactive mode:

•Helpful when your script is extremely short and you want immediate results.
•Faster as you only have to type a command and then press the enter key to get the
results.

•Good for beginners who need to understand Python basics.

The following are the disadvantages of running your code in the interactive mode:

•Editing the code in interactive mode is hard as you have to move back to the
previous commands or else you have to rewrite the whole command again.

•It's very tedious to run long pieces of code. 22


2.2 working with Script mode

In script mode, You write your code in a text file then save it with a .py
extension which stands for "Python". Note that you can use any text editor for
this, including Sublime, Atom, notepad++, etc.

If you are in the standard Python shell, you can click "File" then choose "New"
or simply hit "Ctrl + N" on your keyboard to open a blank script in which you
can write your code. You can then press "Ctrl + S" to save it.

After writing your code, you can run it by clicking "Run" then "Run Module" or
simply press F5.

23
Let us create a new file from the Python shell and give it the name "hello.py". We need to
run the "Hello World" program. Add the following code to the file:

print("Hello World")

Click "Run" then choose "Run Module". This will run the program:

Hello World

Other than executing the program from the graphical user interface, we can do it from
the terminal of the operating system. However, you must be aware of the path to the
directory where you have saved the file.

Open the terminal of your operating system then navigate to the location of the file. Of
course, you will use the "cd (change directory)" command for this.

24
Once you reach the directory with the file, you will need to invoke the
Python interpreter on the file. This can be done using the following syntax:

> python <filename>

To run the Python file from the terminal, you just have to type the python
keyword followed by the name of the file. In our case, we need to run a file
named "hello.py". We need to type the following on the terminal of the
operating system:

> python hello.py

Hello World
25
The following are the advantages of running your code in script mode:

• It is easy to run large pieces of code.


• Editing your script is easier in script mode.
• Good for both beginners and experts.

The following are the disadvantages of using the script mode:

• Can be tedious when you need to run only a single or a few lines of code.
• You must create and save a file before executing your code.
26
Difference between script mode and Interactive mode.

• The interactive mode involves running your codes directly on the Python shell which can be
accessed from the terminal of the operating system.

• In the script mode, you have to create a file, give it a name with a .py the extension then
runs your code.

• The interactive mode is suitable when running a few lines of code.


• The script mode is recommended when you need to create large applications.

27
2.3 Python character set

Character set is the set of valid characters that a language can recognize. A
character represents any letter, digit or any other symbol.
Python has the following character sets:
· Letters – A to Z, a to z
· Digits – 0 to 9
· Special Symbols - + - * / etc.
· Whitespaces – Blank Space, tab, carriage return, newline, form feed
· Other characters – Python can process all ASCII and Unicode characters as part of
data or literals.

28
Tokens

In a passage of text, individual words and punctuation marks are called tokens
lexicalunite or lexical elements.
The smallest individual unit in a program is called token.
Python has the following tokens:
(i) Keyword (ii) Identifiers
(iii) Literals (iv) Operators
(v) Punctuators

29
Reserved words

•Reserved words also called


keywords are defined with
predefined meaning and syntax in
python language. These keywords
have to be used to develop
programming instructions.
• Reserved words can’t be used as
identifiers for other programming
elements like name of variable,
function etc.

30
Reserved words in python

31
Variables or identifiers

•A variable is created the moment we first assign a value to it. A variable is a


name given to a memory location. It is the basic unit of storage in a program.

•The value stored in a variable can be changed during program execution.


•A variable is only a name given to a memory location, all the operations done
on the variable effects that memory location.

32
we can declare a variable by assigning a value to it.

At the moment of assigning a value to that letter, that letter became a variable.

assignment operator

variable x=6 value


print(x)

output :
6

choosing a name of an variable is very important in a python program or any


program.
33
Rules for creating variables
• A variable name must start with a letter or the
underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
• Variable names are case-sensitive (name, Name and
NAME are three different variables).
• The reserved words(keywords) cannot be used
naming the variable.

34
we can name the variable in three ways which is,
complex way- In this way a normal user can even guess whats happening in the program.
eg: aseuikDFCS45Ghnd = 795
aseuikDFFG23Ghjd = 26
axzvmbnmlopys89 = aseuikDFCS45Ghnd * aseuikDFFG23Ghjd
print(axzvmbnmlopys89 )
easier way - It is the simplest form of our variable name.
eg: x = 795
y = 26
z=x*y
print(z)

both are the same problem but a viewer view too. so from second he gets whats the program is, but is
it understandable. lets see next way too
35
eg:
payment_per_day = 795 multiplication operator
days_of_working = 26
total_salary = payment_per_day * days_of_working
print(total_salary)

so, this will be readeable form or understandable form.


we can store various types of values in a variable and we can store a
multiple values in a variable.
and we can assign(reference) a value to multiple variables and viceversa.

36
eg:
x,y,z = “fruits”,”markets”,”computer”
Print (x,y,z)
eg:
x,y,z = “orange”
Print(x)
Print(y)
Print(z)

we can assign a various types of data inside the variables.


so we comes to our next topic which is “types”.

37
Literals
Literals can be defined as a data which isgiven in a variable or
constant.Python supports the following literals.
i.String literals
ii.Numeric literals
iii.Boolean literals
iv.Collection
v.special

38
comments(#)

Comments can be used to explain Python code.


Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
These are like taking notes while you code. This is for make more
readable of your code.
A Comment start with #. in this one line of comment can be written.

print(“hello python”) #this prints hello python. (comment)

39
we can write comments of so many line like this,
"""
This is a comment
written in
more than just one line"""

print("Hello, World!")

40
DATA HANDLING

41
Data types
Data types are the classification or categorization of data items. It represents the kind of value that tells what
operations can be performed on a particular data. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

There are 7 built in datatypes in python.

Numbers
There are integers, float and complex numbers ,which we can use in python.

Strings
These are set of letters which are inside double quotes or single quote.It is a main topic in python which we
discuss in later chapters.

Lists
This is one of the sequence type data, which we use in various part of our program or in solving problem. 42
Tuples
This is also like lists, but it has different character.
Dictionary
This is mapping type, which is it shows and saves as key-value pair.
set
This are from set types, which is similar to list and tuple but it also have its own character.
Frozenset
The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes
them immutable. Simply it freezes the iterable objects and makes them unchangeable.
Bool
The bool() method is used to return or convert a value to a Boolean value i.e., True or False, using
the standard truth testing procedure.
Mutable and Immutable
Mutable means changeable and Immutable means unchangeable.

43
Datatypes
Python has 7 built in data types. Which is:
Text str
Type:
Numeric int, float, complex
Types:
Sequenc list, tuple, range
e Types:
Mapping dict
Type:
Set set, frozenset
Types:
Boolean bool
Type:
Binary bytes, bytearray, memoryview
Types:

In every programming language , data types is an important concept. We can assign


different types of datatypes in variable.
44
As we said earlier we can assign various type of values in a variable,
eg: x = “hello python”
y = 123
z = 1.23
a = true
b = “1234”
print(x,y,z,a,b)
In this example,
x is a string type, y is an integer, z is float, a will be boolean, b is string
if we need the type of this to print then we can use an reserved word, that will be
type().
print(type(y))
output will be:
Class int

45
we use operators like +,-,*,/,% inside some variables to get some value and
assigning to that .
these are basic Arithmetic operators which we use in python programing
languages.
each has a specific function which we use when we do programming.
+ for addition.
- for subtraction.
* for multiplication.
/ for division.
% for getting reminder which is called modulus operator.

we will deal detailed view of operators in later classes.

46
we will see about conversion .

on the image we can see the


conversion methods.
eg :
x = 123
print(x)

this will be an integer output,what if the first command we use,which is

print(str(x))

then we get an string output. we can check what type it is, with type().

47
let's use some operators inside the variables.
adding of two string
x = “hello”
y = “python” # both x and y is type string
var = x+y #this will be called concatinating of two string.
print(var)
print(type(var))

output will be: hello python

what if we add string with integer or a float value.


sure we get an error “traceback ........” some thing start with this word.

48
But we can do that by converting a string into integer and we can add them.
eg:
x = “13345”
y = 12345
z = int(x)
a = z+y
print(a)

so by this method we can add a string to integer. But we can’t do this, which is,
x = “hello”
z = int(x) # this will be an error.

we an change an actual string into integer.

49

You might also like