0% found this document useful (0 votes)
11 views48 pages

Python basic

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views48 pages

Python basic

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 48

Python Programming

(The beginning)
Dr. Adarsh Anand
Assistant Professor
Department of Operational Research
University of Delhi, Delhi 110007
adarsh.anand86@gmail.com
What is Python??
Python is an interpreted, object oriented, high level
programming language with dynamic semantics.

Its Syntax are easy compared to other languages.


Brief History of Python
• Invented in the Netherlands, in 1989 by Guido Van Rossum
• Named after Monty Python
• First Version of Python released in 1991
• In 1994, Python 1.0 was released with new features with map, filter and lambda
• Python 2.X also added some features like comprehensions, garbage collection
system
• After Python 2.X, Python 3.X was released in 2008
• Current version is Python 3.10.1
Features of Python
• Simple and Easy to Learn
• Free and Open Source
• Broad Standard Library (Like for ML-we can make
use of Pandas, NumPy and Matplotlib)
• Cross Platform (Portable)
• Interactive and Interpreted
• Multi-Paradigm Language
• High-level Language
• Extendable
• Expressive Language
• GUI Programming Support 4
Limitations of Python

Parallel processing can be done in Python but not as elegantly as done in some other languages (like JavaScript
and Go Lang).
• Being an interpreted language, Python is slow as compared to C/C++. Python is not a very good choice for
those developing a high-graphic 3d game that takes up a lot of CPU.
• As compared to other languages, Python is evolving continuously and there is little substantial documentation
available for the language.
• As of now, there are few users of Python as compared to those using C, C++ or Java.
• It lacks true multiprocessor support.
• It has very limited commercial support point.
• Python is slower than C or C++ when it comes to computation heavy tasks and desktop applications.
• It is difficult to pack up a big Python application into a single executable file. This makes it difficult to
distribute Python to non-technical. 5
Application of Python
Network Programming

Data Analysis

Robotics

Website and Application Development

Games Development
Application of Python
Web Scraping

Data Visualization

Scientific Calculations

Machine Learning and Artificial


Intelligence

Audio and Video Software Development


Some Companies using Python
Low Level vs High Level Language

Features Low Level High Level


Abstraction Negligible abstraction with the computer Strong abstraction with the computer
language language
Use of Interpreters Does not make use of compilers or Use autocode as compilers to convert the
interpreter instructions into machine language
Flexibility Difficult to use since as it requires It is readable and machine friendly and can
elaborate technical details at each steps be easily interpreted and executed
Execution Faster execution of programs Slow execution of programs
Platform Dependencies These are platform dependent. i.e., These are platform independent. i.e.,
programs can run on same hardware with programs can run on different hardware
same configuration with different configuration
Compiling and interpreting
• Many languages require you to compile (translate) your program into a form
that the machine understands. compile execute
source code byte code output
Hello.java Hello.class

• Python is instead directly interpreted into machine instructions.


interpret
source code output
Hello.py
Decide your tool as per your level
•Beginner — IDLE (or Online Python Editors) is perfect choice for the first steps
in python language. PyCharm is also good but takes the help of some
experienced person while using this.

•Intermediate — PyCharm, Sublime, Atom, Vs Code.

•Advanced — PyCharm, Vim, Emacs, Sublime, Atom, Vs Code.

What is Your Environment/OS?


•Linux, macOS — PyCharm, Sublime, Atom, Vim, Jupyter

•Windows — Sublime, VS Code, Eclipse + PyDev, PyCharm

•Multiple/mixed OS — PyCharm, Sublime, Atom


Modes
• Python has two basic modes: script and interactive.
• The normal mode is the mode where the scripted and finished .py files are run in the
Python interpreter.
• Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory.
Writing a Program
• When we want to write a program, we use a text editor to write the Python
instructions into a file, which is called a script.
• Python scripts have names that end with .py
• To execute the script, you can run the script by going "Run --> Run Module"
or simply by hitting F5 (on some systems, Fn + F5)
Syntax Errors: These are the first errors you
What could possibly will make and the easiest to fix. A Syntax error
go wrong? means that you have violated the “grammar”
rule of python.

Logical Errors: A logical error is when your


program has a good syntax but there is a mistake
in the order of the statements that relates to one
another

Sementic Errors: A sementic error is when


your description of the steps to take is
syntactically perfect and in the right direction,
but there is simply a mistake in the program.
(meaning of the program alters)
Expressions
• expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
• Arithmetic operators we will use:
• + - * / addition, subtraction/negation, multiplication, division
• % modulus, a.k.a. remainder
• ** exponentiation
• precedence: Order in which operations are computed  (PEMDAS)
• * / % ** have a higher precedence than + -
• Parentheses can be used to force a certain order of evaluation.
Integer division
• When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
• The % operator computes the remainder from a division of integers.
• 14%4 is 2
Math commands
• Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
logarithm, base e
log(value)
To use many of these
log10(value) logarithm, base 10 commands, you must write the
max(value1, value2) larger of two values following at the top of your
min(value1, value2) smaller of two values Python program:
round(value) nearest whole number from math import *
sin(value) sine, in radians
sqrt(value) square root
Keywords
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
• In Python, keywords are case sensitive.
Variables
• variable: A named piece of memory that can store a value.
• Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.
• assignment statement: Stores a value into a variable
• Syntax: Examples: x = 5
gpa = 3.14
A variable that has been given a value can be used in expressions.
name = value x + 4 is 9
Example: Declaring and assigning a value to a
variable
• you can use the assignment operator = to assign a value to a variable.

• In the above program, we assigned a value apple.com to the variable website.


Then we print the value assigned to website i.e., apple.com
Identifiers
• An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore
• Examples: myClass, var_1, print_this_to_screen
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in our identifier.
• Identifier can be of any length.
Identifier Vs Variable
BASIS FOR COMPARISON IDENTIFIER VARIABLE
Use Identifier is used to name a Variable is used to name a
variable, function, class, structure, memory location, which holds a
union etc. value.
Purpose Created to give a unique name to Allots a unique name to a
an entity. particular memory location.
Range All identifiers are not variable. All variables names are identifier.
Example int a; int a;
or or
int a(){ // } float a;
Data Types
• We need different data types to store different types of values in the variables.
• The basic types are numbers and strings.
• The five standard data types supported by Python includes-
• numbers,
• strings,
• list,
• tuple, and
• dictionary
Python Output Using print() function
• print : Produces text output on the console
• Syntax:
print ("Message “)
print (Expression)
• Prints the given text message or expression value on the console, and moves the cursor
down to the next line.

print (Item1, Item2, ..., ItemN)


• Prints several messages and/or expressions on the same line.
The actual syntax of the print() function
• print(object(s), sep = ‘’, end = ‘\n’)
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed
sep (Optional) Specify how to separate the objects, if there is more than one. Default is ' '
end (Optional) Specify what to print at the end. Default is '\n' (line feed)
Input Operation
To take input from the users, Python makes use of the input() function. The input() function prompts the
user to provide some information on which the program can work and give the result. However, we must
always remember that the input function takes user’s input as a string.

Example:

26
Comments
Comments are the non-executable statements in a program. They are just added to describe the
statements in the program code. Comments make the program easily readable and understandable by
the programmer as well as other users who are seeing the code. The interpreter simply ignores the
comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All characters following
the # and up to the end of the line are part of the comment

Example:

27
Indentation
Whitespace at the beginning of the line is called indentation . These whitespaces or the indentation are
very important in Python. In a Python program, the leading whitespace including spaces and tabs at the
beginning of the logical line determines the indentation level of that logical line.

Example:

28
Basic Operators in Python
Gates
Binary of a: 0000 1010 (10)
Binary of b: 0000 0100 (4)
Bitwise a & b: 0000 0000 (0)
Bitwise a | b: 0000 1110 (14)
Not operator works only on signed data types conversion is
done using two’s compliment
Right shift : a>> 2 : 0000 0010 (2)
Left shift : a<< 2 : 00 101000 (40)
Operations on Strings

Examples:

39
Slice Operations on Strings
You can extract subsets of strings by using the slice operator ([ ] and [:]). You need to specify index or
the range of index of characters to be extracted. The index of the first character is 0 and the index of the
last character is n-1, where n is the number of characters in the string.
If you want to extract characters starting from the end of the string, then you must specify the index as a
negative number. For example, the index of the last character is -1.
Examples:

40
Lists
Lists are the most versatile data type of Python language. A list consist of items separated by commas
and enclosed within square brackets The values stored in a list are accessed using indexes. The index of
the first element being 0 and n-1 as that of the last element, where n is the total number of elements in
the list. Like strings, you can also use the slice, concatenation and repetition operations on lists.
Examples:

41
Tuples
A tuple is similar to the list as it also consists of a number of values separated by commas and enclosed
within parentheses. The main difference between lists and tuples is that you can change the values in a list
but not in a tuple. This means that while tuple is a read only data type, the list is not.

Examples:

42
Dictionary
Python’s dictionaries stores data in key-value pairs. The key values are usually strings and value can be
of any data type. The key value pairs are enclosed with curly braces ({ }). Each key value pair separated
from the other using a colon (:). To access any value in the dictionary, you just need to specify its key in
square braces ([]).Basically dictionaries are used for fast retrieval of data

Example:

43
Python Type Conversion and Type Casting
• Type Conversion: The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called type conversion.
Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion:
• In Implicit type conversion, Python automatically converts one data type to
another data type. This process doesn't need any user involvement.

Converting integer to float


Addition of string(higher) data type and
integer(lower) datatype

• In the above program,


• we add two variables num_int and num_str.
• As we can see from the output, we got typeerror. Python is not able use Implicit Conversion in such
condition.
• However Python has the solution for this type of situation which is know as Explicit Conversion.
Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc.
• This type conversion is also called typecasting because the user casts (change) the
data type of the objects.
• Syntax:
• (required_datatype)(expression)
• Typecasting can be done by assigning the required data type function to the
expression.
Addition of string and integer using explicit
conversion

You might also like