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

PYTHON Notes1

The document provides an introduction to Python, detailing its history, features, and applications. It covers essential concepts such as keywords, identifiers, variables, data types, and data structures like lists, tuples, sets, and dictionaries. Additionally, it explains the syntax and usage of these elements in Python programming.

Uploaded by

rahulvenkat.465
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PYTHON Notes1

The document provides an introduction to Python, detailing its history, features, and applications. It covers essential concepts such as keywords, identifiers, variables, data types, and data structures like lists, tuples, sets, and dictionaries. Additionally, it explains the syntax and usage of these elements in Python programming.

Uploaded by

rahulvenkat.465
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

G-TECH EDUCATION

Python
Introduction
❖ Python is a general-purpose and high-level programming language.
❖ Python was developed by Guido Van Rossam in 1989 while working at National Research
Institute at Netherland
❖ But Officially python was made available to public in 1991. The official date of birth of the
python is: Feb 20th 1991.

Why Python?
❖ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, and more).
❖ Python has a simple syntax similar to the English language.
❖ Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
❖ Python 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.
❖ Python can be treated in a procedural way, an object-oriented way or a functional way

Where do we use Python?

❖ Application Automation
❖ Data Analytics
❖ Scientific app
❖ Web application
❖ Web scrapping
❖ GUI
❖ Gaming
❖ Business Applications
❖ Animation
❖ Machine Learning and more
G-TECH EDUCATION

Keywords, Identifiers & Variable


Keywords in Python

❖ Keywords are the reserved words in Python.


❖ We cannot use a keyword as 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.

There are 33 keywords in Python

All the keywords except True, False and None are in lowercase and they must be written as they
are. The list of all the keywords is given below.

FALSE Await Else Import pass


None Break Except In raise
TRUE Class finally Is return
And Continue For Lambda try
As Def From nonlocal while
assert Del Global Not with
async Elif If Or yield

Identifiers in Python

An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate 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 _. Names like myClass, var_1 and print_this_to_screen, all are valid
example.
❖ An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
❖ Keywords cannot be used as identifiers.
G-TECH EDUCATION

Variables

A variable is a quantity that may change within the context of a mathematical problem or experiment.
Typically, we use a single letter to represent a variable. The letters x, y, and z are common generic
symbols used for variables.

Example: x= 5
y= 10
name = ‘python’
name = “python”

Providing multiple variables to same input value or object.

Data Types
Programming languages supports too different varieties of data types

Static data types:

❖ In Static data types supported languages programmer should define the data type to the
variable explicitly.
❖ In static data types supported languages one variable can store one variety of data.
❖ C, C++, JAVA, .NET languages are supporting static data types.

Dynamic data types:

❖ In dynamic data types supported languages programmer should not define the data type to
variable explicitly.
❖ At the time of execution of the program based on the data which is assigned to the variable,
data type of the variable is decided.
❖ Python, java script languages are supporting dynamic date types.
❖ Every data type in python language is internally implemented as a class

Data Types in “Python”


❖ None ❖ Set
❖ Numeric ❖ String
❖ List ❖ Range
❖ Tuple ❖ Dictionary
G-TECH EDUCATION

None Data Type

❖ None in Python means no value is associated.


❖ None is also an object in python.

Example

a = 10 → “value 10 is stored in a”
b = None
print(b)
print(type(b))

Output:
None
<class ‘None Type>

Numeric Data Type

Numeric

int float complex bool


Examples 10.5
a=10 <class 'float'> Complex
print(a) Boolean a=10
print(type(a)) a=10 b=15
Float b=15 c=complex(a,b)
b=10.5 c=a>b print(c)
print(b) print(c) print(type(c))
print(type(b)) print(type(c)) Output:
Output: Output: (10+15j)
10 False <class 'complex'>
<class 'int'> <class 'bool'>
G-TECH EDUCATION

List

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [].

Example: x = [10,15,20,25]
y = [‘python’, ‘sql’, ‘dbms’]
z = [10, ‘python’, 9.5]

Functions used in List


❖ append ❖ sort ❖ clear
❖ insert ❖ min ❖ reverse
❖ extend ❖ max ❖ len
❖ remove ❖ sum
❖ pop ❖ del

Example

a = [10,20,30,40,50]
print(a)

Adding the values


a.append(70) # Single value is added at the end of the list
print(a)
a.insert(2,100) # Single value is added based on the position number
print(a)
a.extend([110,120,130]) # Multiple values added in the end of the list
print(a)
a = [10,20,30,40,50,60,70,80,90,100]
print(a)

Deleting the values from the list


a.remove(50) # Single value is removed from the list
print(a)
a.pop(1) # Based on position number value is removed
print(a)
a.pop() # It removes values which is their in the end of list
print(a)
del(a[2:5]) # Delete multiple values using slicing concept
print(a)
a.clear() # It removes all values in the list whereas variable exist.
print(a)
del(a) # Variable gets deleted
G-TECH EDUCATION

a = [10,20,30,40,50,60,10,20,30]
print(a)

a.sort() # Ascending order


print(a)

a.reverse() # It flip the value we can use it for descending order


print(a)

print(min(a)) # Minimum value in the list


print(max(a)) # Maximum value in the list
print(sum(a)) # Sum of values in the list
print(len(a)) # Count of values in the list

Tuple

❖ Tuple items are ordered, unchangeable, and allow duplicate values.


❖ Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
❖ Tuple are written with round brackets ().

a = (10,20,30,40,50)
a = tuple(10,20,30,40,50)

Functions used in Tuple

❖ min ❖ sum ❖ len


❖ max ❖ del

Set
❖ Sets are used to store multiple items in a single variable.
❖ A set is a collection which is both unordered and unindexed.
❖ Sets are written with curly brackets {}.

Method: 1
a={10,22,55,66,22}

Method: 2
a=set([10,22,55,66,22])
G-TECH EDUCATION

Functions used in Set

❖ add ❖ min ❖ del


❖ update ❖ pop ❖ len
❖ remove ❖ max
❖ discard ❖ sum

Example

a = {10,20,30,40,50,60,70}
a.add(100) # add single value in to the set
a.update([1,2,3,4]) # add multi values in to the set
a.remove(50) # remove the single value if value is not available it throws error
a.discard(100) # remove the single value even though value is not available it does
not throw error.
a.pop() # randomly value is removed from the set
del(a) # total data set is deleted.

Union of Sets: Union of concatenation of two or more sets in to a single set.

a={1,2,3}
b={10,20,30}
c={'a','b','c'}

Method 1 (Pipeline)

print(a|b) - {1, 2, 3, 20, 10, 30}


print(a|b|c) - {1, 2, 3, 10, 'c', 'a', 20, 30, 'b'}

Method 2 (Concatenate)

print(a.union(b)) - {1, 2, 3, 20, 10, 30}


print(a.union(b,c)) - {1, 2, 3, 'b', 10, 'a', 20, 'c', 30}

Intersection of SET: Intersection of two or more sets form a new set consisting of only the common
elements present in those sets.

a={1,2,3,4,1,2,'abc'}
b={2,3,10,20,1,2,'abc'}
c={2,20,3,'abc'}
G-TECH EDUCATION

Method 1: Using “&”

print(a&b) - {1, 2, 3, 'abc'}


print(a&b&c) - {2, 3, 'abc'}

Method 2:

print(a.intersection(b)) - {1, 2, 3, 'abc'}


print(a.intersection(b,c)) - {2, 3, 'abc'}

Difference of Sets Symmetric Difference Frozen Set: A frozen set in


a={1,2,3,4} a={1,2,3,4} python is a set whose values
b={1,2,3,5,6} b={1,2,3,5,6} cannot be modified.
Method : 1 Method : Frozen set can be created
print(a.difference(b)) print(a^b) using the frozen set()
print(b.difference(a)) Output
method.
Method : 2 {4,5, 6}
print(a-b) Example
print(b-a) a={1,2,3,4}
Output a=frozenset(a)
print(a)
{4}
{5, 6}

Range

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.

Syntax:
range(start, stop)
range(0,10)

Syntax :
range(start, stop, step)
G-TECH EDUCATION

range(0,10,2)

a = range(1,10)
b = list(range(1,10))
c = tuple(range(1,10))
d = set(range(1,10))

Dictionary
❖ Dictionaries are used to store data values in (key : value) pairs.
❖ A dictionary is a collection which is ordered, changeable and does not allow duplicates.
❖ Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
❖ Keys in a dictionary doesn’t allows Polymorphism.

Method 1: a = {1: 'c', 2: 'c++', 3:'Java'}


Method 2: b = dict([(1,'C'),(2,'C++'),(3,'Java')])

Accessing Elements from Dictionary

❖ While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [] or with the get() method.
❖ If we use the square brackets [], Key Error is raised in case a key is not found in the dictionary.
❖ On the other hand, the get() method returns None if the key is not found.

a = {'name': ‘Raju', 'age': 26} Print(a.get('age'))


print(a['name']) Output: 26
Output: Raju print(a.get('address'))→Output: None
Get Keys()
It returns all keys in the dictionary
a = {'name': "raju", 'age': 26}
print(a.keys())

Get Values
It returns all values in the dictionary
a = {'name': "Raju", 'age': 26}
print(a.values())
G-TECH EDUCATION

Updating and Adding Dictionary keys and values

❖ Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.
❖ If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.

a = {'name': 'Raju', 'age': 26}

update value
a['age'] = 27
print(a) → Output: {'age': 27, 'name': 'Raju'}

add item
a['address'] = “Kamala Nagar”
print(a) → Output: {'address': ' Kamala Nagar ', 'age': 27, 'name': 'Raju'}

fromkeys()

It returns a dictionary from the given sequence of elements with a value provided by the user.

x = ('a','b','c')
y=1
z = dict.fromkeys(x, y)
print(z)
Out put : {'a': 1, 'b': 1, 'c': 1}
x = ('a','b','c')
z = dict.fromkeys(x)
print(z)
Output : {'a': None, 'b': None, 'c': None}

Items()

It returns a list containing a tuple for each key value pair

Admissions = {"CSE": 60,"ECE": 90,"EEE": 60}


a= Admissions.items()
print(a)

Output:
dict_items([('CSE', 60), ('ECE', 90), ('EEE', 60)])
G-TECH EDUCATION

Removing elements from Dictionary

❖ We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
❖ The popitem() method can be used to remove and return an arbitrary (key, value) item pair
from the dictionary. All the items can be removed at once, using the clear() method. The del()
keyword can also delete the dictionary completely
❖ We can also use the del keyword to remove individual items or the entire dictionary itself.

Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4)) → Output:16
print(squares) → Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares.popitem()) → Output: (5, 25)
print(squares) → Output: {1: 1, 2: 4, 3: 9}
squares.clear()
print(squares) → Output: {}
A = {1,2,3}
del(A)

String
❖ A string in Python is a sequence of characters.
❖ Strings in python are surrounded by either single quotation(‘ ‘) marks, or double quotation (“ “)
marks.
❖ Python does not have a character data type, a single character is simply a string with a length
of 1.
Example
print(“python")
print(‘python')
Multi line string
We can assign a multiline string to a variable by using three quotes (“”” “””) (‘ ‘ ‘ ‘ ‘ ‘ )
Strings are Arrays
❑ Strings in Python are arrays of bytes representing uni-code characters.
❑ Python does not support a character type these are treated as strings of length one.
❑ Square brackets can be used to access elements of the string.
Slicing a string
a='python‘
G-TECH EDUCATION

print(a[0]) p

print(a[1:]) ython

print(a[1:4]) yth

print(a[-5:-1]) ytho

print(a[-5:]) ython

Check String

Check string is used check if a certain phrase or character is present in a string, we can use the
keyword “in”.
Example
str = "python is high-level language"
print("python" in str)
Output: True
str = "python is high-level language"
print(“Java" in str)
Output: False.

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword “not in”.
Example
star = "python is high-level language"
print("Java" not in star)
Output: True
String Length
To get the length of a string, use the Len() function.
a = "Python"
print(Len(a))
Output: 6
converting text in lower case
a="PYTHON"
print(a.lower())

converting text in upper case


a='python'
print(a.upper())
Repalce the old text with new text
a="python"
G-TECH EDUCATION

print(a.replace("p","P"))
splits the string into substrings
a="Good Morning , Raju"
print(a.split(","))
Remove White space
a=" Good Morning Raju "
print(a.strip())
concatenate or adding
a = "Hello "
b= "Good morning"
c= a+b
print(c)
Multiply the string
a="python "
print(a*4)

Format String

format() is a function used to replace, substitute, or convert the string with placeholders with valid
values in the final string.
Concatenate the different data types by using format method
a = "I am Raju my age is {}."
age = 25
print(a.format(age))
Output : I am Raju my age is 25.
Concatenate by using index number in format method
name = 'Raju'
bankaccountnumber = '123456'
balance = 50485.8
accountbal = "My name is {2}, my account number is {1} available balance is {0}"
print(accountbal.format(balance, bankaccountnumber, name))
Output : My name is Raju, my account number is 123456 available balance is 50485.8
Methods in String

Method Description

capitalize() It converts the first character to upper case

title() It converts the first character of each word to upper case

casefold() It converts string into lower case


G-TECH EDUCATION

swapcase() It swaps cases, lower case becomes upper case and vice versa

count() It returns the number of times a specified value occurs in a string

endswith() It returns true if the string ends with the specified value

startswith() It returns true if the string starts with the specified value

It searches the string for a specified value and returns the position of
find() where it was found

isalnum() It returns true if all characters in the string are alphanumeric

isalpha() It returns true if all characters in the string are in the alphabet

islower() It returns true if all characters in the string are lower case

isupper() It returns true if all characters in the string are upper case

join() It joins the elements of an iterable to the end of the string

zfill() It fills the string with a specified number of 0 values at the beginning

Type Conversion / Casting


Implicit type conversion ---> we don't need to write manually
Explicit type conversion ---> We have to write code manually

val1 = 10 #int
val2 = 10.9 #float
val3 = val1+val2 # float ---> Implicit
val4 = int(val3) # int --> Explicit
print(val3)
print(val4)
print(type(val3))
print(type(val4))
G-TECH EDUCATION

❖ int , float, complex -- primitive data types


❖ str, list, tuple -- sequential data types
❖ str -- int or float -- numeric values

val1 = 5.2
val2 = str(val1)
print(type(val1))
print(type(val2))
val3 = '5'
val4 = int(val3)
val5 = float(val3)
print(type(val3))
print(type(val4))
print(type(val5))

Str to list , str to tuple


val1 = 'python'
print(val1)
print(type(val1))
val2 = list(val1)
print(val2)
print(type(val2))
val3 = tuple(val1)
print(val3)
print(type(val3))

Operators
Operators are used to perform operations on variables and values.

Types of Operators

❖ Arithmetic operators
❖ Assignment operators
❖ Relational operators
❖ Logical operators
❖ Identity operators
❖ Membership operators
❖ Bitwise operators
G-TECH EDUCATION

Arithmetic operators

These are used to perform mathematical operations like addition, subtraction, multiplication and
division.

OPERATOR DESCRIPTION SYNTAX


Addition (+) Adds two operands a+b
Subtraction (-) Subtracts two operands a-b
Multiplication(*) Multiplies two operands a*b
Division float (/) Returns quotient. It prints exact a/b
value
Division floor (//) Returns quotient. It prints only a//b
integer value
Modulus (%) Returns the remainder a%b

Assignment operators
Assignment operators are used to assign values to the variables.

OPERATOR SYNTAX
= a=5
+= a+=5
-= a-=5
*= a*=5
/= a/=5
//= a//=5
%= a%=5
**= a**=5
G-TECH EDUCATION

Relational Operators
Relational operators are used to compare between two values.

Operator Syntax
Equal (==) a==b

Not equal (!=) a!=b


Greater than (>) a>b
Less than (<) a<b
Greater than or equal to ( >=) a>=b
Less than or equal to (<=) a<=b

Note: The output will be either True or False.

Logical Operators
Logical operators are used for conditional statements are true or false.

Operator Description Syntax

AND Returns True if both statements a<b and b<c


are true

OR Returns True if one of the a<b or b<c


statements is true

NOT Reverse the result, returns False if not(a<b)


the result is true

Note: The output will be either True or False.


G-TECH EDUCATION

Identity Operators

These are used to compare the whether two objects are same or not.
It returns True if memory location of two object are same else it returns False.

Operator Description Syntax Example Output

Is Returns True if both a is b a = 10 True


variables are the same b = 10
object print(a is b)
Is not Returns True if both a is not b a = 10 True
variables are not the b = 15
same object print(a is not b)

Note: The output will be either True or False.

Membership Operators

These are used to check whether a value/variable exists in the sequence like string, list, tuples, sets,
dictionary or not.

Operator Description Syntax Example Output

in Returns True if a sequence a in b a = (2,3) True


with the specified value is b = (2,3,4)
present in the object print(2 in a)

not in Returns True if a sequence a not in b a = (2,3) False


with the specified value is b = (2,3,4)
not present in the object print(4 not in b)

Note: The output will be either True or False.


G-TECH EDUCATION

Bitwise Operators

Operator Description Example (a=4, b=5) Output


Binary AND (&) Operator copies a bit to the result if it exists in c=a&b 4
both operands
Binary OR (|) It copies a bit if it exists in either operand. d=a|b 5
Binary XOR (^) It copies the bit if it is set in one operand but e=a^b 1
not both.
Binary It is unary and has the effect of flipping bits. It
f = ~a -5
Complement(~) gives negative value.
Binary Left Shift The left operands value is moved left by the g = a<<1 8
(<<) number of bits specified by the right operand.
Binary Right The left operands value is moved right by the h = a>>1 2
Shift(>>) number of bits specified by the right operand.

You might also like