Welcome To Python Programming Language




Introduction To Python

Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation.



Installation Process Of Python

If you don't want to use Thonny, here's how you can install and run Python on your computer.

  1. Download the latest version of Python.
  2. Run the installer file and follow the steps to install Python
    During the install process, check Add Python to environment variables. This will add Python to environment variables, and you can run Python from any part of the computer.

    Also, you can choose the path where Python is installed.





Run Python in Immediate mode

Once Python is installed, typing python in the command line will invoke the interpreter in immediate mode. We can directly type in Python code, and press Enter to get the output.

Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a calculator. To exit this mode, type quit() and press enter.






Run Python in the Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.


We just need to save it with the .py extension. But using an IDE can make our life a lot easier. IDE is a piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers, etc. to the programmer for application development.


By the way, when you install Python, an IDE named IDLE is also installed. You can use it to run Python on your computer. It's a decent IDE for beginners.







Your First Python Program With Codolearn

Now that we have Python up and running, we can write our first Python program.

Let's create a very simple program called Hello World. A "Hello, World!" is a simple program that outputs Hello, World! on the screen. Since it's a very simple program, it's often used to introduce a new programming language to beginners.

Type the following code in any text editor or an IDE and save it as hello_world.py



print("Hello, world!")

Congratulations!: You just wrote your first program in Python.

As you can see, this was a pretty easy task. This is the beauty of Python programming language.










Comments in Python

Comments are descriptions that help programmers better understand the intent and functionality of the program.


They are completely ignored by the Python interpreter.




How comments are useful to us in python ?


Using comments in programs makes our code more understandable. It makes the program more readable which helps us remember why certain blocks of code were written.

Other than that, comments can also be used to ignore some code while testing other blocks of code. This offers a simple way to prevent the execution of some lines or write a quick pseudo-code for the program.




There are two types of comment in python

  1. Single Line Comments
  2. Multi-Line Comments



Single line comment : Python single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:
#This is a single line comment
print("Codolearn")



Multi-line : Python multi-line comment is a piece of text enclosed in a delimiter (""") on each end of the comment. Again there should be no white space between delimiter ("""). They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:
""" this
is
a
multi line comment"""



Variables in python

Variables are like containers for storing data values.

How to create a variables ?
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

example:
variable_as_string = "variable"
print(variable_as_string)



example:
variable_as_number = "variable"
print(variable_as_number)



Get the Type
You can get the data type of a variable with the type() function.

example:
name = "kartik"
age = 10
print(type(name))
print(type(age))

We can assign multiple data type in a variables (Data type Next topic)



Data Type in python

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.


Following are the standard or built-in data type of Python:

  1. Numeric
  2. Boolean
  3. Set
  4. Dictionary

Numeric

In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating number or even complex numbers. These values are defined as int, float and complex class in Python.

  • Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be.
  • Float – This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.
  • Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j
# Python program to
# demonstrate numeric value

a = 10
print("Type of a: ", type(a))

b = 8.0
print("\nType of b: ", type(b))

c = 3 + 6
print("\nType of c: ", type(c))

Boolean

Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool.

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))


Sets

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.

# Python program to demonstrate
# Creation of Set in Python

# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)

# Creating a Set with
# the use of a String
set1 = set("CodoLearn")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with
# the use of a List
set1 = set(["codo", "learn", "codo"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'codo', 4, 'learn', 6, 'codo'])
print("\nSet with the use of Mixed Values")
print(set1)


Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.


Creating Dictionary

# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'codolearn', 2: 'For', 3: 'codolearn'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'codolearn', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'codolearn', 2: 'For', 3:'codolearn'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'codolearn'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)



Numbers in python

There are three numeric types in Python:
  • Int
  • Float
  • Complex
example:
x = 5    # int
y = 5.8  # float
z = 3j   # complex



Int
int (Integers) are the whole number, including negative numbers but not fractions. In Python, there is no limit to how long an integer value can be.

example:
num = -5
print(type(num))



Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
x = 30.00
y = 4.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))



Complex
Complex numbers are written with a "j" as the imaginary part:
x = 7+5j
y =  8j
z = -8j

print(type(x))
print(type(y))
print(type(z))



Strings in python

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:
print("Hello World")
print('Hell World')



How to assign string to a variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
variable_name = "codolearn"
print(variable_name)



String Slicing

You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
a = "Hello, World!"
print(b[2:5])



Slice from the start
By leaving out the start index, the range will start at the first character:
b = "Hello, World!"
print(b[:5])



Slice from the start
By leaving out the end index, the range will go to the end:
b = "Hello, World!"
print(b[2:])



Booleans in python

In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)



Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in return,
print(bool("Hello"))
print(bool(15))



What is Operators in python ?

Operators are used to perform operations on variables and values.


There are bassically 7 Types Of Operators In Python

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators


Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y



Assignment Operators

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3



Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y



Logical Operators

Operator Description Example
and  Returns True if both statements are true x < 5 and  x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)



Identity Operators

Operator Description Example
is  Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y



Bitwise Operators

Operator Name Description
AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
 ^ XOR Sets each bit to 1 if only one of two bits is 1
NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off



List in python

Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
listname = ["apple", "banana", "cherry"]
print(listname)



Item in list

List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.




List allows duplicate

Since lists are indexed, lists can have items with the same value:
list_name = ["apple", "banana", "cherry", "apple", "cherry"]
print(list_name)



The list() Constructor

It is also possible to use the list() constructor when creating a new list.
lists = list(("apple", "banana", "cherry"))
print(lists)



Tuples in python

Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
tuple_name = ("apple", "banana", "cherry")
print(tuple_name)



Tuple Items
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.


Ordered Items

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.


Unchangeabel

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.


Allow Duplicates

Since tuples are indexed, they can have items with the same value:
tuple = ("apple", "banana", "cherry", "apple", "cherry")
print(tuple)



String in python

Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function:

print("Hello, Codolearn!")



Assign String to a variable

a = "Codolearn is the best"



Assign String to a array or list

list_name = ["Codolearn", "is", "the", "best"]



Conditional Statements (if...else) in python

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

for using the if statements we have to add if keyword

a = 33
b = 200
if b > a:
    print("b is greater than a")



Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
a = 33
    b = 33
    if b > a:
      print("b is greater than a")
    elif a == b:
      print("a and b are equal")



Else

The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
    b = 33
    if b > a:
      print("b is greater than a")
    elif a == b:
      print("a and b are equal")
    else:
      print("a is greater than b")



While loop in python programming

python has two type of loops:

  • while loop
  • for loop



The While loop

With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i < 6:
  print(i)
  i += 1

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.




Break Statement

With the break statement we can stop the loop even if the while condition is true:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1



Continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)



Else statement

With the else statement we can run a block of code once when the condition no longer is true:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")



For loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)



Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:
for x in "banana":
  print(x)



The Range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(6):
  print(x)



Python Functions

In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.




Syntax:-

def function_name(parameters):
	"""docstring"""
	statement(s)



  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.



def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")



How to call a function in python?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.


def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

greet('Codolearn')



Argruments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

def the_function(fname):
  print(fname + " Refsnes")

the_function("David")
the_function("Alex")
the_function("Steve")



Numbers of Argruments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

def the_function(firstname, lastname):
  print(firstname + " " + lastname)

the_function("Steve", "Trevor")



Python Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.

In the function definition, we use an asterisk (*) before the parameter name to denote this kind of argument. Here is an example.

def greet(*names):
    """This function greets all
    the person in the names tuple."""

    # names is a tuple with arguments
    for name in names:
        print("Hello", name)


greet("Monica", "David", "Steve", "Alex")



Lambda in Python

A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.


Example

Addition

x = lambda a : a + 10
print(x(5))

Example

Addition

x = lambda a, b : a * b
print(x(5, 6))



Why Use Lambda Function ?

The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:


def myfunc(n):
  return lambda a : a * n

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Or, use the same function definition to make a function that always triples the number you send in:
def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))



Python Arrays

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type.




How to Create a Array

Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.
import array as arr

a = arr.array('i', [1, 2, 3])

print ("The new created array is : ", end =" ")
for i in range (0, 3):
	print (a[i], end =" ")
print()

b = arr.array('d', [2.5, 3.2, 3.3])

print ("The new created array is : ", end =" ")
for i in range (0, 3):
	print (b[i], end =" ")




Adding Elements to a array

Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the array.
import array as arr
a = arr.array('i', [1, 2, 3])


print ("Array before insertion : ", end =" ")
for i in range (0, 3):
	print (a[i], end =" ")
print()

a.insert(1, 4)

print ("Array after insertion : ", end =" ")
for i in (a):
	print (i, end =" ")
print()

b = arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")
for i in range (0, 3):
	print (b[i], end =" ")
print()

b.append(4.4)

print ("Array after insertion : ", end =" ")
for i in (b):
	print (i, end =" ")
print()



Lenght of an array

Use the len() method to return the length of an array (the number of elements in an array).
x = len(names)

Looping arrays Elements

You can use the append() method to add an element to an array
names.append("Codolearn")

Removing Array Element

You can use the pop() method to remove an element from the array.
names.pop(1)



All Arrays Method

Method Description
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list



Python Classes / Objects

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state. To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes. Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.


How to Declare a Class in python

class Hiii:
	pass



Python Objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.
An Object Consists of:-
  • State: It is represented by the attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.
class Dog:

	attr1 = "mammal"
	attr2 = "dog"

	def fun(self):
		print("I'm a", self.attr1)
		print("I'm a", self.attr2)

Rodger = Dog()

print(Rodger.attr1)
Rodger.fun()



The __init__() Function

The __init__ method is similar to constructors in C++ and Java. Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
class Person:

	def __init__(self, name):
		self.name = name

	def say_hi(self):
		print('Hello, my name is', self.name)

p = Person('Alex')
p.say_hi()



Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()



Modify Object Properties

p1.age = 40



Delete Object Properties

del p1.age



Delete Objects

del p1



Python Inheritence

Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of inheritance are:

  1. It represents real-world relationships well.
  2. It provides reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
  3. It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.


Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.




class Person(object):

	def __init__(self, name):
		self.name = name

	def getName(self):
		return self.name

	def isEmployee(self):
		return False


class Employee(Person):

	def isEmployee(self):
		return True

emp = Person("Codolearner1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Codolearner2") # An Object of Employee
print(emp.getName(), emp.isEmployee())



How to create a parent class

class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname

  def printname(self):
    print(self.firstname, self.lastname)

x = Person("Alex", "Steve")
x.printname()



How to create a child class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

class Student(Person):
  pass



Use the super() function

Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)



Python Iterator

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have a iter() method which is used to get an iterator:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Even strings are iterable objects, and can return an iterator:
mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))



Looping Through an Iterator

We can also use a for loop to iterate through an iterable object:
mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)



Create an Iterator

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created. The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself. The __next__() method also allows you to do operations, and must return the next item in the sequence.
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))



StopIteration

The example above would continue forever if you had enough next() statements, or if it was used in a for loop. To prevent the iteration to go on forever, we can use the StopIteration statement. In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)



Scopes

A variable is only available from inside the region it is created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
def myfunc():
  x = 300
  print(x)

myfunc()



Function inside Function

As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function:
def myfunc():
  x = 300
  def myinnerfunc():
    print(x)
  myinnerfunc()

myfunc()



Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
x = 300

def myfunc():
  print(x)

myfunc()

print(x)



Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.
def myfunc():
  global x
  x = 300

myfunc()

print(x)


Also, use the global keyword if you want to make a change to a global variable inside a function.
x = 300

def myfunc():
  global x
  x = 200

myfunc()

print(x)



Python Dates

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
import datetime

x = datetime.datetime.now()
print(x)



Date Output

When we execute the code from the example above the result will be:

2021-08-28 18:28:38.631532 The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date object.

Here are a few examples, you will learn more about them later in this chapter:
import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))



Creating date objects

To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
import datetime

x = datetime.datetime(2020, 5, 17)

print(x)


The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).




The strftime() Method

The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))



Python Math

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.




Built-in Math Functions

The min() and max() functions can be used to find the lowest or highest value in an iterable:
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)


The abs() function returns the absolute (positive) value of the specified number:
x = abs(-7.25)
print(x)


The Math Module

Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import math


When you have imported the math module, you can start using methods and constants of the module.
The math.sqrt() method for example, returns the square root of a number:

import math

x = math.sqrt(64)
print(x)


The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x)
print(y)

The math.pi constant, returns the value of PI (3.14...):

import math

x = math.pi
print(x)



Python JSON

JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.
Python has a built-in package called json, which can be used to work with JSON data.
import math


Parse JSON - Convert from JSON to Python

If you have a JSON string, you can parse it by using the json.loads() method.

import json

x =  '{ "name":"Steve", "age":30, "city":"New York"}'
y = json.loads(x)

print(y["age"])


Convert from Python to JSON

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
import json

x = {
  "name": "Steve",
  "age": 30,
  "city": "New York"
}

y = json.dumps(x)
print(y)


You can convert Python objects of the following types, into JSON strings:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None


import json

print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))


Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null


import json

x = {
  "name": "Steve",
  "age": 30,
  "cars": [
    {"model": "Lamborgini terzo", "mpg": 27.5},
    {"model": "Mustang GT", "mpg": 24.1}
  ]
}

print(json.dumps(x))



Python Try Expect

The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement:

try:
  print(x)
except:
  print("An exception occurred")

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")


Else

You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")


Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

try:
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")


Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")



User Input in Python

Python allows for user input. That means we are able to ask the user for input. The method is a bit different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method. The following example asks for the username, and when you entered the username, it gets printed on the screen:
username = input("Enter username:")
print("Username is: " + username)



String Formatting

The format() method allows you to format selected parts of a string. Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input? To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:
price = 49
txt = "The price is {} dollars"
print(txt.format(price))

You can add parameters inside the curly brackets to specify how to convert the value:



txt = "The price is {:.2f} dollars"



Multiple Values

If you want to use more values, just add more values to the format() method:
print(txt.format(price, itemno, count))

And add more placeholders:


quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))



Index Numbers

You can use index numbers (a number inside the curly brackets {0}) to be sure the values are placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))





File Handling


Python File Open

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists



Syntax

f = open("demofile.txt")

The code above is the same as:
f = open("demofile.txt", "rt")



Python File Open


Open a File on the Server

Assume we have the following file, located in the same folder as Python:

To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file:

f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())


Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))


Read Lines

You can return one line by using the readline() method:

f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())



Python File Write


Write to an Existing File

---------------------------

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

f = open("demofile2.txt", "r")
print(f.read())



f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

f = open("demofile3.txt", "r")
print(f.read())


Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", "x")



Python Delete File

To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")






Python References





Python all Built in functions

Function Description
abs()Returns the absolute value of a number
all()Returns True if all items in an iterable object are true
any()Returns True if any item in an iterable object is true
Returns a readable version of an object. Replaces none-ascii characters with escape character
bin()Returns the binary version of a number
bool()Returns the boolean value of the specified object
bytearray()Returns an array of bytes
bytes()Returns a bytes object
callable()Returns True if the specified object is callable, otherwise False
chr()Returns a character from the specified Unicode code.
classmethod()Converts a method into a class method
compile()Returns the specified source as an object, ready to be executed
complex()Returns a complex number
delattr()Deletes the specified attribute (property or method) from the specified object
dict()Returns a dictionary (Array)
dir()Returns a list of the specified object's properties and methods
divmod()Returns the quotient and the remainder when argument1 is divided by argument2
enumerate()Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval()Evaluates and executes an expression
exec()Executes the specified code (or object)
filter()Use a filter function to exclude items in an iterable object
float()Returns a floating point number
format()Formats a specified value
frozenset()Returns a frozenset object
getattr()Returns the value of the specified attribute (property or method)
globals()Returns the current global symbol table as a dictionary
hasattr()Returns True if the specified object has the specified attribute (property/method)
hash()Returns the hash value of a specified object
help()Executes the built-in help system
hex()Converts a number into a hexadecimal value
id()Returns the id of an object
input()Allowing user input
int()Returns an integer number
isinstance()Returns True if a specified object is an instance of a specified object
issubclass()Returns True if a specified class is a subclass of a specified object
iter()Returns an iterator object
len()Returns the length of an object
list()Returns a list
locals()Returns an updated dictionary of the current local symbol table
map()Returns the specified iterator with the specified function applied to each item
max()Returns the largest item in an iterable
memoryview()Returns a memory view object
min()Returns the smallest item in an iterable
next()Returns the next item in an iterable
object()Returns a new object
oct()Converts a number into an octal
open()Opens a file and returns a file object
ord()Convert an integer representing the Unicode of the specified character
pow()Returns the value of x to the power of y
print()Prints to the standard output device
property()Gets, sets, deletes a property
range()Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr()Returns a readable version of an object
reversed()Returns a reversed iterator
round()Rounds a numbers
set()Returns a new set object
setattr()Sets an attribute (property/method) of an object
slice()Returns a slice object
sorted()Returns a sorted list
staticmethod()Converts a method into a static method
str()Returns a string object
sum()Sums the items of an iterator
super()Returns an object that represents the parent class
tuple()Returns a tuple
type()Returns the type of an object
vars()Returns the __dict__ property of an object
zip()Returns an iterator, from two or more iterators




Python Strings Method

Method Description
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isascii()Returns True if all characters in the string are ascii characters
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Converts the elements of an iterable into a string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning



Some of the List Methods

Method Description
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list



Dictionary Methods

Method Description
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary



Tuples Method

Method Description
count()Returns the number of times a specified value occurs in a tuple
index()Searches the tuple for a specified value and returns the position of where it was found





© 2021 Created By "KARTIK A DIGITAL INFLUENCER" || All Rights Reserved