Pyrhon For Beginners
Pyrhon 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}")
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.
Pycharm shortcut
keys
Installation
Download Python | Python.org
Download PyCharm: The Python IDE for data science and web d
evelopment by JetBrains
pip · PyPI
Pip list
Thank you