0% found this document useful (0 votes)
32 views79 pages

Python Programming Overview and Basics

The document provides an overview of Python, a general-purpose programming language created by Guido van Rossum, highlighting its applications in web development, data science, and automation. It covers Python's syntax, differences between Python 2 and 3, basic programming concepts, data types, operators, and decision-making structures. Additionally, it includes exercises for practical understanding and usage of Python programming.
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)
32 views79 pages

Python Programming Overview and Basics

The document provides an overview of Python, a general-purpose programming language created by Guido van Rossum, highlighting its applications in web development, data science, and automation. It covers Python's syntax, differences between Python 2 and 3, basic programming concepts, data types, operators, and decision-making structures. Additionally, it includes exercises for practical understanding and usage of Python programming.
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

Yogananda School of AI Computer and Data

Science

Python Application Programming


(CSU1162)
What is Python?
• Guido van Rossum created it and first released on February 20, 1991.
• General-purpose programming language.
• Used in a variety of fields like AI, ML, DS, DA, and web development etc.
• Most trending programming language (easy, simple syntax, readable
code).
• Write less and get more.
• Interpreted (executes code line by line), object-oriented programming,
and high-level programming language.
• Can be used to create any type of software or website.
• Python has powerful libraries to work with a variety of different fields like
mathematics, engineering, data science, artificial intelligence, machine
learning, etc.
Scope of Python
• Web Development: Python web frameworks like Django, Flask, and Pyramid
are popular choices for building dynamic websites and web applications.
• Data Science and Machine Learning: Python is widely used in data analysis,
machine learning, and artificial intelligence projects due to its extensive
libraries like NumPy, pandas, scikit-learn, TensorFlow, and PyTorch.
• Scripting and Automation: Python's ease of use and versatility make it a
preferred language for writing scripts, automating repetitive tasks, and
developing system administration tools (OpenCV, Selenium).
• Game Development: Python's simplicity and flexibility make it suitable for
game development, with libraries like Pygame providing the necessary tools
and functionality.
• Desktop GUI Applications: Python offers GUI frameworks like Tkinter, PyQt,
and wxPython for building cross-platform desktop applications with
graphical user interfaces.
Examples Of Software / App / Website
Developed In Python
• YouTube: Backend services and infrastructure are largely built
using Python.
• Instagram: Initially developed using Python and Django.
• Spotify: Uses Python for data analysis and backend services.
• Dropbox: Uses Python for server-side logic and automation.
• Google: Many of Google's internal tools and services are built
with Python.
• NASA: Python is used extensively for scientific computing and
data analysis in various NASA projects.
Python Syntax
• Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.

print("Hello, World!")

How this works?


• print() is a built-in function in Python that tells the program to display something on the
screen. We need to add the string in parenthesis of print() function that we are
displaying on the screen.
• “Hello, World!” is a string text that we want to display. Strings are always enclosed in
quotation marks.
Syntax Comparison

C++ Python

#include <iostream> print("Hello, World!")

int main() {
cout << "Hello, World!" << endl;
return 0;
}
Difference between Python2 and Python3
• Created by: Guido van Rossum in 1989
Released in: 1991 (Python 1.0)

• Major Versions:
• Python 2.x (2000) – Introduced various features.
• Python 3.x (2008 - Present) – Major improvements (latest
3.13.5)
Difference between Python2 and Python3
Python 2.x Python 3.x

print “hello world” print(“hello world”)

print(5/2 ) -> 2 (integer division) print(5/2) -> 2.5 (true division)


If either number is a float, then it does true division. To achieve integer division in Python 3, you can use
print(5.0 / 2) -> 2.5 the // operator.

Python 2 treats strings as sequences of bytes by Python 3 fully embraces Unicode as the default
default string type.
ASCII is used to store string UNICODE is used to store string

User input: raw_input() User input: input()

Integer size is upto 32bits Integer size is unlimited

Xrange method Range method


Python Programming Basic Concepts
What is a Program?
• A program in Python is a set of instructions written in the Python language that performs
a specific task or achieves a desired outcome.
• A Python program can consist of one or more files containing code written in a text
editor or an Integrated Development Environment (IDE).
• The program is executed by the Python interpreter, which reads and executes the code
sequentially.

Statements:
• Statements in Python are instructions that the interpreter can execute.
• Examples include assignment statements, function calls, and conditional statements.
• Each statement typically ends with a newline character, but multiple statements can be
written on the same line using a semicolon ; as a separator, although this practice is
discouraged for readability reasons.
Python Programming Basic Concepts
Comments:
• Comments in Python are used to annotate code and provide explanations for better
understanding.
• The Python interpreter ignores them and are solely for human readers.
• Comments can be single-line or multi-line and are preceded by the #.

Indentation:
• Indentation is crucial in Python for indicating the structure of code blocks such as loops,
conditional statements, and function definitions.
• Unlike many other programming languages that use curly braces { } to define code blocks,
Python uses indentation to delimit blocks of code.
• Standard practice is to use four spaces for each level of indentation.
Python Programming Basic Concepts
Input and Output functions:
• Input and output functions play a vital role in any programming
language, facilitating interaction with the user and displaying
information.
• In Python, input functions allow users to provide data to the
program, while output functions display results and
messages.
Exercise:
• Prompt the user to enter their name and greet them with a
personalized message.
• Calculating Area of a Rectangle
• Write a python program to take marks from the user to check
whether user able to get admission in the college or not. If marks is
less than 60 then it do not allow to take admission.
• Convert Celsius to Fahrenheit.
• Write a python program to take age from the user to check whether
they are eligible for voting or not.
• Write a python program that accepts three length of a triangle as
inputs. The program output should indicate whether the triangle is a
right triangle.
Keywords
• Keywords are the
reserved words in
python.
• We cannot use a
keyword as function
names, variable
names, or any other
identifier
• Keywords are case
sensitive.
Identifiers
• Identifier is the name given to
entities like class, functions,
variables etc. in Python. It helps
differentiating one entity from
another.
• Rules for Writing Identifiers:
- 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 (_).
- An identifier cannot start with a digit.
1variable is invalid, but variable1 is
perfectly fine.
- Keywords cannot be used as
identifiers.
• We cannot use special symbols like
!, @, #, $, % etc. in our identifier.
Escape Sequence
• These are the special characters that are used for specific tasks.
• They begin with a backslash (\) followed by a character code.
Escape Sequence continue…
Variables
• A variable is a container in which we store any value (later we will use
that value).
• These values can be of various types, such as numbers, strings, or
complex data structures.
• Variables allow programmers to manipulate and work with data
dynamically within a program.
• Rules to Declare a Variable:
- Start with a Letter or Underscore
- Consist of Letters, Numbers, or Underscores
- Case-Sensitive
- Avoid Keywords
- Use Descriptive Names
Variables continue…
• Declaration: When we write the name of a variable according to
rules and regulations without providing a value, it is called the
declaration of a variable.
• Initialization: After declaration, you need to provide a value to the
declared variable. Assigning a value to a variable is called
initialization.
• But in Python, we did not need to declare a variable separately at
the time of declaration; we provide a value to that variable.
Variables continue…

C++ Python

int a; //declaration a = 10 # declaration and


a = 10; //initialization initialization
Variables continue…
Variables continue…
• Types of Variables:
- Local Variables: Variables defined within a function or method
have local scope and are accessible only within that function or
method.
- Global Variables: Variables declared outside of any function or
method have global scope and can be accessed from anywhere
within the program.
- Instance Variables: Variables that are unique to each instance of
a class and are defined within the class's methods.
- Class Variables: Variables that are shared among all instances of
a class and are defined within the class but outside of any
method.
Data Types
• Every value in Python has a datatype. Since everything is an object
in Python programming, data types are actually classes and
variables are instance (object) of these classes.
• Python data types:

- Boolean
Boolean represents the truth
values False and True
Data Types continue…
- Numbers
Integers, floating point numbers
and complex numbers falls
under Python numbers
category. They are defined as
int, float and complex class in
Python.
We can use the type() function
to know which class a variable
or a value belongs to and the
isinstance() function to check if
an object belongs to a
particular class.
Data Types continue…
- Strings
A string in Python consists of a
series or sequence of
characters - letters, numbers,
and special characters.
Strings can be indexed - often
synonymously called
subscripted as well. The first
character of a string has the
index 0.
Data Types continue…
- List
List is an ordered sequence of
items. It is one of the most used
datatype in Python and is very
flexible. All the items in a list do
not need to be of the same type.
Declaring a list is , Items
separated by commas are
enclosed within brackets [ ] .
Data Types continue…
- Tuple
Tuple is an ordered sequence of
items same as list. The only
difference is that tuples are
immutable. Tuples once
created cannot be modified.
Declaring a tuple is , Items
separated by commas are
enclosed within brackets ( ) .
Data Types continue…
- Set
Set is an unordered collection
of unique items. Set is defined
by values separated by comma
inside braces { }. Items in a set
are not ordered.
Data Types continue…
- Dictionary
Dictionary is an unordered
collection of key-value pairs. In
Python, dictionaries are defined
within braces {} with each item
being a pair in the form
key:value. Key and value can be
of any type.
Data Types continue…
• Conversion between data types:
• We can convert between different data types by using different
type conversion functions like int(), float(), str() etc.
Data Types continue…
• Conversion between data types:
Data Types continue…
• Conversion between data types:
Operators
• Operators are the symbols that perform a operation on operand.
• Example:
a+b
Where a and b is the operand and + is the symbol (operator)

x=3
y = 12
x<y
Where < (less than) is the operator, x and y are the operands
Operators continue…
Arithmetic Operators: In Python, these operators are used as
arithmetic operators
• Addition +
• Subtraction -
• Division /
• Multiplication *
• Modulus %
Operators continue…
Relational or Comparative Operators: In Python, to compare two
values we use comparison (relational) operator. Or, to find a
relation between two values, we also use such operators.
They return Boolean value (False or True)
These operators are:
• Equality ==
• Not equality !=
• Greater than >
• Greater than or equal to >=
• Less than <
• Less than or equal to <=
Operators continue…
Logical Operators: There are some operators, that are used as
logical in python.
They return a Boolean value (False or True)
These operators are:
• and (&&) operator
• or (||) operator
• not (!) operator
Operators continue…
Bitwise Operators: It convert integers into binary at first, then
perform operations, then again converts to decimal and gives result
to user.
These operators are:
Symbol Name Example
& AND a&b
| OR a|b
^ XOR a^b
~ NOT ~b
>> Right shift a>>
<< Left shift b<<
Operators continue…
Compound / Assignment Operators: In Python, = is the assignment operator,
that is used to assign a value to variable.
a = 5 is a simple assignment operator that assigns the value 5 on the right to
the variable a on left variable
There are two operators in compound operators as the assignment operator
and the arithmetic operator.

These operators are:


• Addition assignment operator +=
• Subtraction assignment operator -=
• Multiplication assignment operator *=
• Division assignment operator /=
• Modulus assignment operator %=
Operators continue…
Special Operators:
• Identity Operators: is and is not
are the identity operators in python
• They are used to check if two
values (or variables) are located on
the same part of the memory.
Operators continue…
Special Operators:
• Membership Operators: in and
not in are the membership
operators in python.
• They are used to test whether a
value or variable is found in a
sequence (string, list, tuples, set
and dictionary)
Exercise:
• Write a Python program to get 4 numbers from the user, subtract the
first two, add the second two numbers, then find the multiplication
of both results.
• Write a Python program to check a valid username and password.
• Write a Python program to perform left and right shift bitwise
operations.
• Write a Python program to ask the user for two numbers and show
their binary form and all bitwise results.
• Write a Python program to extract and display the hundreds, tens,
and one's digits of a given three-digit number
• Write a Python program to find the occurrence of a specific color
from a list.
Exercise:
• Write a Python program to get a number from user to check, it
is divisible by 2 and 3.
• Write a Python program to check a year, whether it is a leap
year or not
Decision making structure
• The structure in which we provide a condition, and on the basis of
the condition, a statement or set of statement is execute.
• Display a message “Congratulations, you can participate in this
program”, if person age is 10 or greater than 10.
• Display message “Welcome” if day is Monday.
• Types of decision-making structure:
• if statement
• if…else statement
• Nest if statement
• if elif else statement
if statement in Python
• It takes a condition, if the condition is true, then it executes a
statement or set of statements.
• If the condition is false, nothing to display
• Syntax:
if (test expression/condition):
statement(s)

marks = 81
if marks > 80:
print(“You are pass…”)
if-else statement in python
• It take a condition, if the condition is true, then it executes a
statement or set of statement. If the condition is false, it will
display a false like statement or set of statements.
• Syntax:
if (test expression/condition):
statement(s)
else:
statement(s)
Nested if statement in python
• Nested if statement means, if statement inside another if
statement block
• Syntax:
if (test expression 1/condition 1):
if (test expression 2/condition 2):
statement(s)
else:
statement(s)
Nested if statement in python continue…
When condition 1 is true then condition 2 will be checked, and
inside 2nd if statement block, all the statement or set of statement
will be executed if both condition become true.
Example:
num = 18
if (num%2 ==0):
if (num%3 == 0):
print(“number is divisible by 3 and 2”)
if-elif-else statement in python
• elif is used between if and else block
• We use elif, where we have to make multiple condition after if
statement
• It is alternative of else if (condition)
• Syntax:
if (test expression/condition):
statement(s)
elif (test expression/condition):
statement(s)
else:
statement(s)
Exercise:
• Write a Python program to get a number from user and display
message “number is even”, if number is even.
• Write a Python program to check if the number is positive, negative,
or zero.
• Write a Python program to find the largest element among three
numbers.
• Write a Python program to get a name from the user and display it.
The name should contain 5 characters or fewer than 10, and the
name should start with the “a” character.
• Write a Python program to get age and marks from user. The system
should 1st select that user which have greater than or equal to 18
year of age and 2nd marks should be greater than 80 and less than
100.
Loops in Python
• Programming instruction executes linearly in the order in which
we declare. But we can alter that sequence using different way.
One of them is looping.
• Loop: If you want to repeat any statement for specific time, or if
you want to generate a number according to your instruction, you
can use loop.
• while loop
• for loop
Loops in Python continue…
• while Loop: It’s the loop which repeat a statement or set of
statement as long as condition is true.
• Most of the time, we use while loop in the situation, in which we
don’t know about total number of iterations.
• Components to remember in every loop:
• Initialization
• Condition
• Increment or decrement
• Statement(s)/ loop body
Loops in Python continue…
• Syntax: It’s the loop which repeat a statement or set of statement
as long as condition is true.
while condition:
body of the loop
(statement or set of statement)
increment or decrement
Example-1 Example-2
i=0 i = 10
while i < 10: while i > 0:
print(i) print(i)
i += 1 i -= 1
Exercise:
• Write a Python program to generate number from 100 to 1 only
odd number.
• Write a Python program to generate number from 10 to 50 and
add all the generated number. Solve this using while loop.
• Get starting and ending number from user to generate a
sequence of number. You should check at first, starting
number should be less than ending number
• Prompt the user to enter a number. Use a while loop to print
the multiplication table of the entered number from 1 to 10.
Loops in Python continue…
• for Loop: It’s the loop used to iterate over a sequence (list, tuple,
string) or other iterable objects.
• Iterating over a sequence is called traversal.
• Syntax:
for element in sequence:
body of for

Here, element is the variable that takes the value of the item inside
the sequence on each iteration.
Loop continues until we reach the last item in the sequence.
Loops in Python continue…
• range() function: We can generate a sequence of numbers using
range() function. range(10) will generate numbers from 0 to 9 (10
numbers).
• We can also define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided.
• This function does not store all the values in memory, it would be
inefficient. So it remembers the start, stop, step size and
generates the next number on the go.
Loops in Python continue…
• for loop with else: A for loop can have an optional else block as
well. The else part is executed if the items in the sequence used in
for loop exhausts.
• Example:
numbers = [1,2,3]
for item in numbers:
print(item)
else:
print(“no item left in the list”)
break and continue
• In Python, break and continue statements can alter the flow of a
normal loop.
• Loops iterate over a block of code until test expression is false,
but sometimes we wish to terminate the current iteration or even
the whole loop without checking test expression.
• The break and continue statements are used in these cases.
Exercise:
• Write a python program to generate number from 50 to 1, only
odd numbers and find their sum.
• Write a Python program to display all prime numbers within an
interval
Data Structures
• A data structure is an organized collection of data elements such
as numbers, characters, or even other data structures arranged in
a specific way, for instance, by assigning positions or indices. In
Python, the simplest type of data structure is a sequence.
List
• List is a type of sequence data structure.
• Lists can hold multiple items, including strings, integers, or even
other lists.
• Lists are defined using square brackets [ ].
• Every item in a list has a unique index.
• Items in a list are separated by commas.
• Lists are mutable, meaning their elements can be modified after
creation.
List continue…

List Creation
List continue…

List append
List continue…

List insert
List continue…

List extend
List continue…

List Delete: (remove, del, pop)


List continue…

List Delete: (remove, del, pop)


List continue…

List reverse
List continue…

List Sorting
List continue…

List Sorting
List continue…

List Sorting
List continue…

List Sorting
List continue…

List count
List continue…

String split to create a list


List continue…

List indexing
• Each item in the list has an assigned index value starting from 0.
• Accessing elements in a list is called indexing.
List continue…

List Slicing
• Accessing parts of segments is called slicing.
• The key point to remember is that the :end value represents the
first value that is not in the selected slice.
List continue…

List extend using “+”


List continue…

List Comprehension
• List comprehensions provide a concise way to create lists.
• Common applications are to make new lists where each element
is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those
elements that satisfy a certain condition.
List continue…

List Comprehension
List continue…

Nested List
Exercise:
• Separate even and odd numbers into two lists.
• Count how many times each element appears.
• Reverse a list without using the reverse() method.
• Take two shopping lists from two family members and merge
them into one.
• Take a list of integers from user and split into positives,
negatives, and zeros.
• Take input of contact names, allow user to add, delete, and
display contacts using list operations.
• Transpose a matrix using list comprehension.

You might also like