0% found this document useful (0 votes)
30 views39 pages

Python Programming Basics and Data Types

This document provides an overview of Python programming, covering its types, data structures, and key concepts such as variables, operators, and control statements. It explains the workings of high-level programming languages, particularly Python's syntax and its applications in web development and data analysis. Additionally, it details fundamental data types, structures like lists and dictionaries, and control flow mechanisms such as loops and conditional statements.

Uploaded by

ashaalva70
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)
30 views39 pages

Python Programming Basics and Data Types

This document provides an overview of Python programming, covering its types, data structures, and key concepts such as variables, operators, and control statements. It explains the workings of high-level programming languages, particularly Python's syntax and its applications in web development and data analysis. Additionally, it details fundamental data types, structures like lists and dictionaries, and control flow mechanisms such as loops and conditional statements.

Uploaded by

ashaalva70
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

Python

Notes

T A J A M U L K H A N
Contents
• Programming Language
Types, Examples, Working
• Python
Use, Working, Types, Use, Why Python
• Data Types
Numerical, Character, Bool (Type Conversion, Escape
Character, String Methods)

• Data Structure
List, Tuple, Dictionary, Sets
n n
h a
• Variable

ul k
Types, Lifetime, Naming Conventions, Types of Cases

a m
aj
• Operators

T
Mathematical, Assignment, Comparison, Special, Logical
@ and Slicing
• Indexing
Zero base Concept, Negative Indexing, Slicing, Skip
Intermediate, Index Function

• Conditional Statements
If else, if elif else, While Loop, For Loop

• Python Functions
Used Defined functions
Lambda functions
Inbuilt Functions

@[Link] @Tajamulkhann
Programming Language
Programming Language is a computer language which is used to write a computer program in
order to give instructions to our computer.

Computer Normally understands Binary Language e.g., 0101

Types
High Level languages: require the use of a compiler or an interpreter for their translation into the
machine code.

• Very Close to English like Python, JS

n n
• Easy to Understand

h a
ul k
Low Level Languages: requires an assembler for directly translating the instructions of the

m
machine language.

aj a
Very Close to ML e.g., Assembly Language

T
Direct Computer Memory Data Access

@
Middle Level Languages: The middle-level language lies in between the low-level language and
high-level language

• Have access to HLL and also computer memory/data like C, C++


• Both Programming for Writing OS and Application Programming

Working of a High-Level Programming Language


Source Code → Interpreter/Compiler → Byte Code → Cpython VM → Machine language

Compilation Method (Compiler) Entire file is executed or all lines into binary to execute whole
file at once
Interpretation Method (Interpreter) Line by Line and executes one line before going to next line

@[Link] @Tajamulkhann
Python
• Python is a High-Level programming language, which makes use of an Interpreter. It
• was created by Guido van Rossum in 1991. Python is famous for its readability
• because of its simple syntax similar to English language. which makes it easy and fast
to code and increases developer productivity.

→ Working of Python

Source Code → Interpreter → Byte Code (Closer to ML → CPython VM) → ML (Binary


Code)

n n
h a
Types ul k
m

Python 2.0

aj a Python 3.0
released in 2000

outdated
@ T
→ older syntax
released in 2008

In demand → includes Typing System


Python is used for:

• web development (server-side),


• software development, handle big data (Data Visualization) and perform
• complex mathematics, system scripting.

Why Python?

• works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).


• simple syntax similar to the English language. syntax that allows developers to write
• programs with fewer lines compared to other PLs. Runs on an interpreter system, meaning
• that code can be executed as soon as it is written. This means that prototyping can be very
quick.

@[Link] @Tajamulkhann
Data Types
is a classification of data which tells the compiler or
interpreter how the programmer intends to use the data
→ Fundamental Data Types:
• Numeric Data Types: complex, float, int
• Character Data Type: str
• Boolean Data Type: bool

1. Numeric Data Types


Integers (int) are whole numbers e.g., 8, 0, -12
syntax = print (type (8)) = <class 'int>
Floating Point Numbers are numbers that contain floating decimal points e.g., 0.1, 2.0
syntax = print (type (5/2) = <class 'float'>
Complex Numbers consist of two parts — a real number & an imaginary number. e.g., 3 + 2j

n
syntax = print (type (3 + 2j) = <class 'complex'>

2. Character Data Types


a n
k h
ul
String (str) is a sequence of characters, Surrounded by ‘ ‘ or “ “
• Long Strings use triple quotation marks. " " "

a m
print (“Tajamul is my name”) = <class 'str'>

aj
Note: Strings are immutable

@ T
3. Boolean Data Types
Bool () represents one of two values: True or False.
1 = True; (bool (1)) = True
2 = False; (bool (0)) = False
→ Type Conversion Means converting one data type into other
→ If x = 5.5 → x = float (x) = floating point number → type(x) = float
int can be converted into str

but str cannot be converted to an int

→ Escape Character or Sequence: is used to insert characters that are illegal in a string

An escape character is a backslash \ followed by the character you want to insert.


print ('women\'s clothing') --> women's clothing
\n = new line \b = backspace \r = Carriage Return
\t = add tab \\ = backslash \’s = apostrophe s

@[Link] @Tajamulkhann
String Methods

[Link] (@) inside ‘tajamulk@[Link]’

In Split we can specify split end

n n
h a
Use Case
ul k
a m
T aj
@

@[Link] @Tajamulkhann
Data Structure
We know that variables can store only 1 value at a time.


Fundamental Data Structures:

n n
a
List (Mutable) Dictionary (Mutable)
Tuple (Non-Mutable) Set

k h
→ List
m ul
aj a
is a data structure which is Mutable and ordered sequence of elements

T
• A value in a list is generally referred to as an item or an element.

@
• A Python list is created using the square brackets [].
• Each item in a Python list is separated by a comma.

syntax = List = [10, 2, 30]


List[1] = 20 , List = [20,2,30] = Mutable

@[Link] @Tajamulkhann
→ List Methods

Len( ) = to see how many items are stored in a list

syntax = Len (List Name)

Count( ) = to count the number of times an element appears in the List


syntax = List_name. count (item_ Name)

Append( ) Adds an element at the end of the list (needs new list)
syntax = [Link](100)

Pop( ) Removes the element at the specified position or index e.g. pop(0) or pop (1)
syntax = [Link][index no.]

Remove( ) Removes the item with the specified value


syntax = [Link][element name]

n n
h a
ul k
a m
T aj
@

@[Link] @Tajamulkhann
→ Tuple

• A Python Tuple is created using the round brackets or Parentheses ().


• Tuple is normally used when No Changes are needed in List.
syntax = Tuple = (10, 2, 30)
Tuple[1] = 20 , Error = Immutable

→ Dictionary

n n
h
• A Python Dict is created using the curly brackets or Braces {}.
a
ul k
syntax = Dict = {‘Name’ : ‘Tajamul’ , ‘Job’ : ‘Data-Scientist’}
Dict[‘Name’] = KK = Mutable

a m
T aj
@

@[Link] @Tajamulkhann
→ Dictionary Methods

→ Tuple Unpacking

n n
h a
ul k
a m
T aj
@
→ Tuple Methods

@[Link] @Tajamulkhann
→ Sets

• A Python Set is created using the curly brackets or Braces {}.

syntax = Set = {1,2,2,3,3,4,4} = {1,2,3,4}

Variable
are containers for storing data values.

n n
→ Types of Variables

h a


Local
Global
ul k
a m
T aj Local Variable
@
Global Variable

→ Lifetime of a Variable

The lifetime of a variable is the period throughout which the variable exists in the memory. The
lifetime of variables inside a function is as long as the function executes.

They are destroyed once we return from the function. Hence, a function does not remember the value
of a variable from its previous calls

@[Link] @Tajamulkhann

Naming Conventions for Variables

• A Variable must always start with either a letter or an underscore (_) For example: _str, str,
Str, STR are all valid name for the variables.
• A Variable cannot start with a number.
• A Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
• Variable name is case sensitive in Python which means taju and TAJU are two different
variables in python.

Ideally variable should be in small case and CONSTANT in UPPER CASE


Types of Cases

= Each word, except the first, starts with a capital letter: hiThereFrey

n
= Each word starts with a capital letter: HiThereFrey

a n
h
= Each word is separated by an underscore character: hi_there_Frey

Operators
ul k
a m
are special symbols that carry out arithmetic or logical computation.

T
Mathematical Operators:
aj
* The value that the operator operates on is called the operand.

@

are used to perform mathematical operations e.g.
+-*/ Addition, Subtraction, Multiplication, % Modulus = Gives Remainder

Division
** To the Power // Division gives least in both +ve and -ve
i.e., a = 10; b = -3; a//b = -4 Also; a = 10; b = 3; a//b = 3

Comparison Operators

comparing two operands and returns Boolean Value;
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to

@[Link] @Tajamulkhann
→ Assignment Operators

→ Special Operators

n n
h a
ul k
a m
T aj
@
a1 = ‘Hi’; a2 = ‘HI’;
print (a is b) = True
print (a1 is not a2) = True

Store = [‘tajamul’, ‘khan’, ‘Hassan’]


tajamul in Store = True

@[Link] @Tajamulkhann
→ Logical Operators

Indexing n n
h a
ul k
a m
T aj
@

syntax = Print (planet [0]) = Mercury

@[Link] @Tajamulkhann
→ Negative Indexing
indicates the location of an element in the list in reverse order and starts with
-n and ends with -1. -1 indicates the last item

syntax = Print (planet [-1] = Item 6

n n
Slicing
h a
list is mutable unlike strings
ul k
a m
amazon = [ 'vegies', 'fruits', 'nuts']

aj
print (amazon [0:2]) = vegies, nuts

@
Mutability e. g
T
amazon [0] = 'juice'
print(amazon) = ['juice', 'fruits', 'nuts']

@[Link] @Tajamulkhann
0:4 means Start from 0 and End before 4

→ Skip Intermediate Indexing means start Index: End Index: Skip Numbers

Note: By Default, Python skips by 1 number

List_name [start index: end_index:num_of_items_to_be_skipped]


syntax = List_name [0:4:2]

→ Index of an Item To find Index Number of an element in a list


syntax = List_name. Index(‘element’) = 0

Conditional Statements
Conditional test, get value based on if true or False

There are two types


• If-else
• If-elif-else
n n
→ If - else
h a
ul k
One condition if true, it will execute a block of statements else it will execute

m
another block of statements. E.g.

a
T aj
@

@[Link] @Tajamulkhann
Live Example of If-else

Scenario: If Die_roll = 1, the outcome =1; else not 1

n n
→ If - elif else:
h a
ul k
Multiple conditions; e.g., If, elif, elif, elif, else

a m
T aj
@

@[Link] @Tajamulkhann
Live Example of If-elif-else
Scenario: If Die_roll = 2, 3, 5 = Outcome is prime number; else Outcome is not Prime

n n
h a
ul k
a m
aj
Self Example

@ T

@[Link] @Tajamulkhann
While Loop
used to iterate a block of code Condition based as long as (condition) is True.
syntax = While (condition):

n n
h a
ul k
a m
T aj
Natural Numbers from 2011-2021

@
→ Break Keyword
Another way to stop a loop whether it is an infinite loop or a finite loop. A finite loop executes
for a fixed number of times. To stop an infinite loop, use the break keyword.

@[Link] @Tajamulkhann
→ Nested While Loop
means a while loop inside another while loop.

Similarly, we can print the complete multiplication table of 2, 3 and 4 using


nested while loop.

n n
h a
ul k
a m
T aj
@

@[Link] @Tajamulkhann
For Loop
to repeat or iterate elements in a sequence i.e., list, tuple, dictionary, set for a fixed
number of times.

Syntax= for a in range (1,6): or for each change in elements = statements


Print (a)

The code can be read as for every

number in the range of 1 to 6 and


except 6, print a number. So, in the
range of 1 to 6 and except 6, there

are 5 numbers starting from 1 to 5.


So, all these numbers in this range
will get printed one-by-one.

Natural Numbers from 2011-2021

n n
h a
ul k
a m
T aj
@
for loop for lists (sequence)

@[Link] @Tajamulkhann
→ Nested for Loop
means a for loop inside another for loop.

for each value change in outer loop, inner loop should complete 1 full cycle

→ Use of for loop / while loop

n n
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for

h a
statement consumes the initialization, condition and increment/decrement in one line

ul k
thereby providing a shorter, easy to debug structure of looping.

m
In general, you should use a for loop when you know how many times the loop should

a
aj
run. If you want the loop to break based on a condition other than the number of times

T
it runs, you should use a while loop.

@
Range Function
used to generate a range of numbers.
Syntax: range (start, end)

@[Link] @Tajamulkhann
Python Functions
A function is a block of code. Which is used to perform some particular actions

It only runs when it is called

n n
h a
ul k
a m
T aj
@
→ Types of Python Functions
There are two Types of Python Functions
• User Defined Functions (def and Lambda)
• In-Built Functions

→ Def functions:
User Defined Functions
To create a user-defined function, we use a keyword called def followed by the name of
the function, followed by common brackets, followed by the colon (:) symbol.
The input(s) to the function is/are provided within the common brackets.

Syntax: def function_name (input1, input2, ..., inputN):


Return +=

@[Link] @Tajamulkhann
Note:

The function attributes must be written in the subsequent lines after leaving two blank

spaces between the code cell and the code. To exit the function, remove the blank spaces
between the code cell and the code in the subsequent lines.

The function name must begin with a lowercase letter.

n n
h a
ul k
m
Let us understand different categories of User defined functions.
a
T aj
@

@[Link] @Tajamulkhann
→ Return Statement
The return statement is used to get the output of a user defined function

Syntax = return [expression_list]

→ Examples of User Defined Function

n n
h a
→ Statement and Expression ul k
a m
T aj
@

This statement can contain an expression that gets evaluated and the value is returned. If there is

no expression in the statement or the return statement itself is not present inside a function,

then the function will return the None object.

@[Link] @Tajamulkhann
Example of def Function, Return, Statement and Expression

→ Lambda functions:
¯ˀz̄ Lambda Functions are anonymous function means that the function is without a
name. As we already know that the def keyword is used to define a normal

n n
function in Python. Also, the lambda keyword is used to define an anonymous fx in
Python

h a
ul k
Syntax = lambda arguments: [expression_list]

• This function can have any number of arguments but only one expression, which is
evaluated and returned.

a m

aj
One is free to use lambda functions wherever function objects are required.

T


@
You need to keep in your knowledge that lambda functions are syntactically restricted to a
single expression.

It has various uses in particular fields of programming besides other types of expressions

in functions.

@[Link] @Tajamulkhann
→ Built-in functions:

→ Python 3.6 uses the input () method.


Python 2.7 uses the raw input () method.

Input Function
n n
h a
Mistake = input("do you smoke")
yes ='You are going to die'
ul k
m
print (f ' {yes} soon’)

aj a
by default, input function converts Everything in it as string



@ T
e.g., Therefore, for Input, either convert integer to string or type x = [‘12’, ‘13’, ‘14’]
syntax = print (f ‘{x}, are you okay’)

→ Data Structure Functions

@[Link] @Tajamulkhann
→ Map Function
Map in Python is a function that works as an iterator to return a result after applying a
function to every item of an iterable (tuple, lists, etc.)
Syntax = List (Function and Iterable)

n n
h a
ul k
a m
T aj
@
→ Filter Function
The filter () function returns an iterator where the items are filtered through a function
to test if the item is accepted or not.
Syntax = List (Filter (Function and Iterable))

@[Link] @Tajamulkhann
Important Tips
• Object oriented = which makes use of concept of classes and Objects.
• Print to Display all Results
• By default, alternate Index escape = 1
• while loop = Thumb Rule = print () and then num +=1 (initialize, while
condn, print, increment/decrement at the end)
• List = [ ], list. Append (10,20)
• End = “ ’’= print in same line in for loop

n n
h a
ul k
a m
T aj
@

@[Link] @Tajamulkhann
Important Tips
• Object oriented = which makes use of concept of classes and Objects.
• Print to Display all Results
• By default, alternate Index escape = 1
• while loop = Thumb Rule = print () and then num +=1 (initialize, while
condn, print, increment/decrement at the end)
• List = [ ], list. Append (10,20)
• End = “ ’’= print in same line in for loop

n n
h a
ul k
a m
T aj
@

@[Link] @Tajamulkhann
Best
Resources

T A J A M U L K H A N
Best Data
Ebooks

[Link] [Link]

[Link] [Link]

[Link] [Link]
Best Data
Science Kits

[Link] [Link]

[Link] [Link]
Ace Interviews
like a boss!

Interview Kit
[Link]

Best Resume
[Link]
Data Science
Cheat Sheets

Get it Now!
Leave a Testimonial
Free Data
Resources

Resources Data Posts Data Projects


Click Here Click Here Click Here

Job Help Free Notes


Click Here Click Here
I Can Help!

[Link]

[Link]

[Link]
Why Me?
Education Topmate

[Link]
Experience
Preplaced

[Link]

100K+ Followers

20K+ Followers
Drop your Review!

Tajamul Khan

You might also like