0% found this document useful (0 votes)
77 views30 pages

Pyrhon For Beginners

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

Pyrhon For Beginners

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

Python for Beginners

Srinivasa.R
Bangalore, India
Table of contents
Basic overview
Strings in Python are surrounded by either single quotation marks, or double quotation marks.
’Hello’ is the same as ”Hello”.
You can assign a multiline string to a variable by using three quotes or three single quotes Hello
you write Python (.py) les in a text editor
Comments starts with a #, and Python will ignore them: for multiple Ctrl+/
+0 1 2 3 4 5
ASCII table - Table of ASCII codes, characters and symbols -6 5 4 3 2 1
Python - String Methods

Escape Characters
\' Single Quote 15 decimal places
\\ Backslash Python
ASCII value
\n New Line Editors:
Case sensitive
\r Carriage Return Python IDLE
\t Tab Visual Studio
Types
\b Backspace Code
1x=1 #int
\f Form Feed Spyder
2 y = 2. 8 #float
\ooo Octal value Visual Studio
3 z = 3 + 2 j # complex
\xhh Hex value PyCharm
4 x = ‘Hello’ # string
Wing Python
Data Variables
Python Variables are memory spaces that hold information, such as numbers or text, that
the Python Code can later use to perform tasks.
1. The variable name should start with an underscore or letter.
Example: _educba, xyz, ABC
2. Using a number at the start of a variable name is not allowed.
Examples of incorrect variable names: 1variable, 23alpha, 390say
3. The variable name can only include alphanumeric characters and underscore.
Example: learn_educba, c5, A777_21
4. Variable names in Python are case-sensitive.
Examples of different variable names: educba, Educba, EDUCBA
5. Reserved words in Python cannot be a variable name.
Example: while, if, print, while
Data Types
•Numeric Types:
•int: Represents whole numbers (integers), e.g., 5, -10.
•float: Represents numbers with a decimal point (floating-point numbers), e.g., 3.14, -0.5.
•complex: Represents complex numbers with a real and imaginary part, e.g., 1 + 2j.
•Sequence Types:
•str: Represents sequences of characters (strings), enclosed in single or double quotes, e.g., "hello", 'Python'.
•list: Represents ordered, mutable sequences of items, enclosed in square brackets, e.g., [1, 2, "three"].
•tuple: Represents ordered, immutable sequences of items, enclosed in parentheses, e.g., (1, "two", 3.0).
•range: Represents an immutable sequence of numbers, often used in loops.
•Mapping Type:
•dict: Represents unordered collections of key-value pairs (dictionaries), enclosed in curly braces,
e.g., {"name": "Alice", "age": 30}.

•Set Types:
•set: Represents unordered collections of unique, mutable elements, enclosed in curly braces, e.g., {1, 2, 3}.
•frozenset: Represents unordered collections of unique, immutable elements.
•Boolean Type:
•bool: Represents truth values, either True or False.
•Binary Types:
•bytes: Represents immutable sequences of bytes.
•bytearray: Represents mutable sequences of bytes.
•memoryview: Provides a memory-efficient way to access the internal data of an object without copying it.
Data Operators
Assignment
Compariso + Addition x+y = Operators
x=5 x=5

== Equal n x == y - Subtraction x - y Arithmetic += x += 3 x=x+3
!= Not equal x != y * Multiplication x * y -= x -= 3 x=x-3
> Greater than x>y / Division x/y *= x *= 3 x=x*3
< Less than x<y % Modulus x%y /= x /= 3 x=x/3
>= Greater than or equal to x >= y ** Exponentiation x ** y %= x %= 3 x = x % 3
<= Less than or equal to x <= y // Floor division x // y //= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
in Returns True if a sequence with the specified
Membershivalue is present in the object x in y &= x &= 3 x = x & 3
not in Returns True if a sequence with the specified
p value is not present in the object x not in y
|= x |= 3 x=x|3
& AND Sets each bit to 1 if both bits are 1 x&y Bitwis ^= x ^= 3 x=x^3
| OR Sets each bit to 1 if one of two bits is 1 x|y >>= x >>= 3 x = x >> 3
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y e
~ NOT Inverts all the bits ~x
<<= x <<= 3 x = x << 3
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2 := print(x := 3) x = 3
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the
rightmost bits fall off x >> 2 •Arithmetic operators
•Assignment operators
is Returns True if both variables are the same object x is y Identity
•Comparison operators
is not Returns True if both variables are not the same object x is not y •Logical operators
and Returns True if both statements are true x < 5 and x < 10 Logical •Identity operators
or Returns True if one of the statements is true x < 5 or x < 4 •Membership operators
not Reverse the result, returns False if the result is true not(x < 5 and x < 10) •Bitwise operators
Control flow
If statement For loop Known While loop Unknown
The primary keywords used for Iterations:
The for loop is primarily used for iterating over a The while loop isIterations:
used to repeatedly execute a
conditional statements in Python sequence (like a list, tuple, string, or range) or block of code as long as a specified condition
are if, elif (short for "else if"), and else. other iterable objects. It is suitable when the remains true. It is suitable when the number of
Each if, elif, and else statement must number of iterations is known or determined by iterations is unknown beforehand and depends
end with a colon (:). the length of the sequence being traversed. on a condition being met or becoming false.

number of iterations
if statement: is dependent on a
if-else statement: dynamic condition.
if-elif-else statement (Elif Ladder):
Data Built in functions
abs(): Returns the absolute value of a number.
bool(): Converts a value to a Boolean (True or False). Creates a new dictionary.
dict():
chr(): Returns the character represented by a Unicode code point. Converts a value to a floating-point number.
float():
dir(): Returns a list of names in the current scope or the attributes of an object.
Formats a specified value. help():
format(): Returns the identity of an object.
Returns a new frozenset object (an immutable set). id():
frozenset():
Returns the value of a named attribute of an object. input(): Reads a line from input, converts it to a string, and returns it.
getattr():
Returns True if an object has a given named attribute. int(): Converts a value to an integer.
hasattr():
hex(): Converts an integer to a hexadecimal string. len(): Returns the length (the number of items) of an object.
isinstance(): Returns True if an object is an instance of a specified class or of a subclass thereof. list(): Creates a new list.
issubclass(): Returns True if a specified class is a subclass of another specified class. open(): Opens a file and returns a corresponding file object.
max(): Returns the largest item in an iterable or the largest of two or more arguments. print(): Prints objects to the text stream file, separated by sep and followed by end.
min(): Returns the smallest item in an iterable or the smallest of two or more arguments. Returns a sequence of numbers.
range():
object(): Returns a new featureless object. Converts a value to a string.
str():
ord(): Returns the Unicode code point for a one-character string.
tuple(): Creates a new tuple.
pow(): Returns the result of raising a number to a power.
type(): Returns the type of an object.
repr(): Returns a string containing a printable representation of an object.
Returns a reverse iterator. set(): Creates a new set.
reversed():
Rounds a number to a specified number of decimal places. append(): Adds an element to the end of the list.
round():
sum(): Sums the items of an iterable.
copy(): Returns a shallow copy of the list.
Returns the __dict__ attribute for a module, class, instance,
vars(): or any other object with a __dict__ attribute. Removes all elements from the list.
clear():
zip(): Creates an iterator that aggregates elements from multiple iterables. count(): Returns the number of times a specified element appears in the list.
map(): Applies a given function to each item of an iterable and returns an iterator. Returns the index of the first occurrence of a specified element.
index():
filter(): insert(): Inserts an element at a specified position.
reduce(): Removes and returns the element at the specified position (or the last element if n
Returns a new sorted list from the items in an iterable
pop():
sorted(): . Removes the first occurrence of a specified element.
Retrieves the next item from an iterator. remove():
next():
Returns True if all elements of an iterable are true (or if the iterable is empty). reverse(): Reverses the order of the elements in the list.
all():
Returns True if any element of an iterable is true. sort(): Sorts the list in ascending order (by default).
any():
enumerate(): Returns an enumerate object, which yields pairs of (index, item).
map(), filter(): For applying functions to iterables.
Uppercase()
Lowercase()
Data structure - List, Tuple, set and dictionary
[] is a list, and () is a tuple. Tuples are immutable, {} is a set, in that it {} is a dictionary. You can
is mutable, in that its in that their sizes cannot vary. contains unique, immutable ob store key value pairs in it e.g.
size can vary Immutable objects can be hashed, jects. {} is also used to create Person = {'name': one_loop,
List is a collection which is an important property. a dictionary, where the 'age':69}
which is ordered and You can concatenate tuples, but it dictionary has a set of keys Dictionary is a collection
changeable. Allows returns a new tuple, Set is a collection which is which is ordered** and
duplicate members. Tuple is a collection which is unordered, unchangeable*, changeable. No duplicate
ordered and unchangeable. Allows and unindexed. No duplicate members. (e.g., strings,
duplicate members. members.. numbers, tuples),
OOP – Object Oriented Programming
Object-Oriented Programming (OOP) in Python is a programming
paradigm that organizes code around objects rather than
functions and logic. It aims to model real-world entities and their
interactions, leading to more modular, reusable, and
maintainable code.
•Classes and Objects:
•Class: A blueprint or template for creating objects. It defines the
attributes (data) and methods (functions) that objects of that class will
possess.
•Object: An instance of a class. When an object is created from a class,
it inherits the attributes and methods defined in that class.
•Inheritance:
•A mechanism that allows a new class (subclass or child class) to inherit attributes and methods from an existing class (superclass or parent class).
•It promotes code reuse and establishes a hierarchical relationship between classes.
•Polymorphism:
•The ability of objects of different classes to be treated as objects of a common type.
•It allows the same method name to be used for different implementations in different classes, leading to more flexible and extensible code.
•Abstraction:
•The process of hiding complex implementation details and exposing only the necessary functionalities to the user.
•It focuses on what an object does rather than how it does it, simplifying interaction with the object.
•Encapsulation:
•The bundling of data (attributes) and the methods that operate on that data within a single unit (the class).
•It restricts direct access to some of an object's components, promoting data integrity and preventing unintended modifications.
Contd…
1. Defining a Class: 3. Instance Methods:
A class is defined using the class keyword, followed by the Methods are functions defined within a class that operate on the
class name (conventionally capitalized) and a colon. object's data. They also take self as their first parameter.
class MyClass: class Person:
x=5 def __init__(self, name, age):
self.name = name
p1 = MyClass() self.age = age
print(p1.x)
def myfunc(self):
print("Hello my name is " + self.name)
2. The __init__ Method (Constructor):
The __init__ method is a special method, often referred 4. Creating Objects (Instantiating the Class):
to as the constructor, which is automatically called when a To create an object from a class, you call the class name as if it were
new object (instance) of the class is created. It's used to a function, passing any required arguments for the __init__ method
initialize the object's attributes. The first parameter, self,
refers to the instance itself. p1 = Person("John", 36)
Create a class named Person, use the __init__() method to
assign values for name and age: 5. Accessing Attributes and Calling Methods:
class Person: You can access an object's attributes and call its methods using the
def __init__(self, name, dot (.) operator. print(p1.name)
age): . print(p1.age)
self.name = name
Contd…
Class: A Colleton of functions and attributes, attached to a specific
name, which represents an abstract concept.
Attribute: A named piece of data (i.e. variable associated with a class.
Object: A single concrete instance generated from a class
Instances of Classes: Classes can be viewed as factories or templates
for generating new object instances. Each object instance takes on the
properties of the class from which it was created.
class Person:
def __init__(self, name, age):
self.name = name # Initialize the 'name' attribute
self.age = age # Initialize the 'age' attribute

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

# Creating an instance of the Person class


person1 = Person("Alice", 30)

# Accessing and using the object's attributes and methods


person1.display_info() Create a class (blueprint)
Create a instance (Object)
Class vs instance
Instance attributes: defined in __init__(self)
Class attribute
Contd…
Inheritance Polymorphism
Inheritance allows us to define a class that
The word "polymorphism" means "many forms", and in
inherits all the methods and properties from
programming it refers to methods/functions/operators with the
another class.
same name that can be executed on many objects or classes.
Parent class is the class being inherited from,
Two objects of different classes but supporting the same set of
also called base class.
functions or attributes can be treated identically. The
Child class is the class that inherits from another
implementations may differ internally, but the outward
class, also called derived class.
Class inheritance is designed to model relationships of the type "appearance" is the same.
"x is a y" (e.g. "a triangle is a shape")
Cond…
Abstraction Encapsulation
File Handling and Modules
Sl
no Text file Binary file
1 Consist of data in ASCII consists of data in binary form
Suitable to store binary such as images,
Suitable to store Unicode characters
2 videos, audio files, etc
Each line in a text file is terminated with a
3 There is no EOL - End of line) character
special character(EOL)
Operations on text files are slower than binary Operations on binary files are faster as no
4
files as data needs to be translated to binary translation is required
Document Files: .pdf, .doc, .xls, etc.
Image Files: .png, .jpg, .gif, .bmp, etc.
Web Standards: HTML, XML, CSS, JSON, etc. Video Files: .mp4, .3gp, .mkv, .avi, etc.
Source Code: C, APP, JS, PY, Java, etc. Audio Files: .mp3, .wav, .mka, .aac, etc.
5
Documents: TXT, TEX, RTF, etc. Database Files: .mdb, .accde, .frm, .sqlite,
Tabular Data: CSV, TSV, etc. etc.
Configuration Files: INI, CFG, REG, etc Archive Files: .zip, .rar, .iso, .7z, etc.
Executable Files: .exe, .dll, .class, etc
Understanding File Objects
file.name: Name of the file. file.mode: Mode in which the file
was opened ('r', 'w', etc.). file.closed: Boolean indicating
whether the file is closed.
Sequence Of Operations Understanding File Objects
1.Open/Create File file.name: Name of the file.
2.Read from/Write to file file.mode: Mode in which the file was opened ('r', 'w', etc.).
3.Close File file.closed: Boolean indicating whether the file is closed.
Contd…
File modes and operation
Error handling and debugging
Types of Errors in Python
1. Syntax Errors
2. Division by Zero:
3. Accessing Undefined
Variables:
4. Out-of-Bounds
Indexing:
5. File Not Found:
Logical Errors
1. Incorrect Algorithm:
2. Off-by-One Error:
3. Wrong Data Types:
4. Misplaced Conditions:
Exceptions Common Exceptions except ValueError:
Here are some common exceptions in Python:
1. ValueError: ("You must enter a number")
•ZeroDivisionError: Division by zero. except ZeroDivisionError:
2. TypeError:
•IndexError: List index out of range. ("You can't divide by zero")
3. KeyError:• KeyError: Dictionary key not found.
•TypeError: Invalid operation for a data type.
•ValueError: Invalid value for a function or operation.
•Syntax Errors:
Intermediate python - Iterator and Generator
An iterator is an object that represents a stream of data and allows A generator uses the 'yield' keyword in Python. A
you to traverse through its elements one by one. Iterators implement Python iterator, on the other hand, does not. Every
two special methods: __iter__() and __next__(). time 'yield' pauses the loop in Python, the Python
•__iter__() returns the iterator object itself.
•__next__() returns the next item in the sequence. generator stores the states of the local variables. An
• If there are no more items, it raises a StopIteration exception. iterator does not need local variables
Contd…
Lambda
A Python lambda function is a small, anonymous function defined using the lambda keyword. It can take any number of arguments
but can only have one expression. Lambda with filter():
Simple Lambda Function: numbers = [1, 2, 3, 4, 5, 6]
add = lambda a, b: a + b even_numbers = list(filter(lambda x: x % 2
print(add(5, 3)) # Output: 8 == 0, numbers))
Lambda with map(): print(even_numbers) # Output: [2, 4, 6]
numbers = [1, 2, 3, 4] Lambda as a Return Value:
doubled_numbers = list(map(lambda x: x * 2, numbers)) def multiplier(n):
print(doubled_numbers) # Output: [2, 4, 6, 8] return lambda a: a * n
doubler = multiplier(2)
tripler = multiplier(3)
print(doubler(10)) # Output: 20
print(tripler(10)) # Output: 30
Lambda with Conditional Logic:
check_parity = lambda num: "Even" if num %
2 == 0 else "Odd"
print(check_parity(7)) # Output: Odd
print(check_parity(10)) # Output: Even
a = [1, 2, 3]
b = [4, 5, 6]
res = map(lambda x, y: x + y, a, b)
print(list(res))
Map and Filter
Comprehensions Decorators
Comprehensions decorators are a powerful and flexible way to
Comprehensions in Python provide a concise and expressive
modify or extend the behavior of functions or
way to create new sequences (lists, dictionaries, and sets)
methods, without changing their actual code.
from existing iterables. They offer a more readable and
•A decorator is essentially a function that takes
efficient alternative to traditional for loops for many common
data transformation and filtering tasks. another function as an argument and returns a
new function with enhanced functionality.
•List Comprehensions: Used to create new •Decorators are often used in scenarios such as
lists. logging, authentication and memorization,
squares = [x**2 for x in range(10)]
even_numbers = [x for x in range(20) if x % allowing us to add additional functionality to
2 == 0] existing functions or methods in a clean, reusable
way.
•Dictionary Comprehensions: Used to create new
dictionaries. The @ syntax is syntactic
names = ["Alice", "Bob", "Charlie"]
ages = [30, 24, 35] sugar for applying a
name_age_dict = {name: age for name, age in decorator.
zip(names, ages)}
A decorator is a design pattern
•Set Comprehensions: Used to create new that allows you to modify or
sets. Sets are unordered collections of unique enhance the behavior of a
elements. function or class without
unique_letters = {char for char in "hello
world" if char.isalpha()} permanently altering its
source code
Libraries
Python libraries are collections of pre-writtenKey aspects of Python libraries: • Extensive Ecosystem:
code, modules, and packages that provide a • Code Reusability: Data Science and Machine Learning:
wide range of functionalities, allowing • Modularity: Web Development:
developers to perform various tasks without • Simplified Development: Image Processing:
writing code from scratch. They contain • Installation Scientific Computing:
functions, classes, and routines that can be Web Scraping:
NumPy: into your programs.
readily integrated
Fundamental for numerical computing, providing support for large,
multi-dimensional arrays and matrices, along with a collection of
mathematical functions.
Pandas:
Essential for data manipulation and analysis, offering powerful data
structures like DataFrames for working with tabular data.
Matplotlib:
A widely used library for creating static, interactive, and animated
visualizations in Python.
Requests:
Simplifies making HTTP requests, commonly used for interacting
with web APIs and web scraping.
Scikit-learn:
A comprehensive library for machine learning, offering tools for
classification, regression, clustering, and more.
Numpy
NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear
algebra, fourier transform, and matrices.
Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object,
and tools for working with these arrays.
NumPy is a library that helps us handle large and multidimensional arrays and matrices. It provides a
large collection of powerful methods to do multiple operations.
NumPy (Numerical Python) is a fundamental Python library for scientific computing. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of high-level mathematical
functions to operate on these arrays efficiently.

Numpy
Pandas
Pandas is a software library written for the Python programming language specifically designed for data manipulation and
analysis. It provides powerful and flexible data structures, most notably the DataFrame and Series, which are optimized for working
with tabular and labeled data.
Pandas is a Python library used for working with data sets. It has functions for analyzing, cleaning, exploring, and manipulating
data.
Pandas is open-source Python library which is used for data manipulation and analysis. It consist of data structures and functions
to perform efficient
Why Pandas is widely used: What is Pandas?
•Ease of Use: Pandas is a Python library used for working with data sets.
Its intuitive API makes it accessible for both beginners and experienced It has functions for analyzing, cleaning, exploring, and manipulating data.
data scientists. The name "Pandas" has a reference to both "Panel Data", and "Python Data
•Flexibility and Power: Analysis" and was created by Wes McKinney in 2008.
It can handle various data types and structures, from simple tables to
complex time series.
•Performance: Why Use Pandas?
While not inherently multi-threaded, computationally intensive Pandas allows us to analyze big data and make conclusions based on
operations are implemented in C or Cython for efficiency. statistical theories.
•Open Source: Pandas can clean messy data sets, and make them readable and
It is free and open-source, benefiting from a large and active relevant.
community. Relevant data is very important in data science.

Creating a DataFrame from a


Dictionary:
Reading Data from a CSV File: Pandas
Selecting Columns:
Filtering Rows:
Matplotlib:
Matplotlib is a Python library for data visualization, Key Features of Matplotlib
primarily used to create static, animated, and •Versatile Plotting: Create a wide variety of
interactive plots. It provides a wide range of visualizations, including line plots, scatter plots, bar
plotting functions to visualize data effectively. charts, and histograms.
Matplotlib is a powerful and versatile open- •Extensive Customization: Control every aspect
source plotting library for Python, designed of your plots, from colors and markers to labels and
to help users visualize data in a variety of annotations.
formats. Types of •Seamless Integration with NumPy: Effortlessly
Different
plot data arrays directly, enhancing data
Plots
manipulation capabilities.
•1. Line Graph
•High-Quality Graphics: Generate publication-
•2. Bar Chart
ready plots with precise control over aesthetics.
•3. Histogram
•Cross-Platform Compatibility: Use Matplotlib on
•4. Scatter Plot
Windows, macOS, and Linux without issues.
•5. Pie Chart
•Interactive Visualizations: Engage with your
•6. 3D Plot
Steps data dynamically through interactive
import matplotlib.pyplot as plt plotting
•Import Matplotlib: Start by importing features.
x = [0, 1, 2, 3, 4]
matplotlib.pyplot as plt. y = [0, 1, 4, 9, 16]
•Create Data: Prepare your data in the form of lists or
plt.plot(x, y)
arrays. plt.show()
•Plot Data: Use plt.plot() to create the plot.
•Customize Plot: Add titles, labels, and other elements
Requests:
Python Requests Library is a simple and powerful tool to
send HTTP requests and interact with web resources. It
allows you to easily
send GET, POST, PUT, DELETE, PATCH, HEAD requests
to web servers, handle responses, and work with REST
APIs and web scraping tasks.

Sending GET Requests with Parameters


HTTP Request Methods
Response object
Response Methods
Authentication using Python Requests
SSL Certificate Verification
Accessing a site with invalid SSL:
Providing a custom certificate:
Session Objects
Error Handling with Requests
Short cut keys for pycharm

Pycharm shortcut
keys
Installation
Download Python | Python.org
Download PyCharm: The Python IDE for data science and web d
evelopment by JetBrains
pip · PyPI

For libraries – install in pycharm

Pip install pandas

Pip list
Thank you

You might also like