Skip to content

Tutorials in Python

LEARN PYTHON

Python is a programming language for computers. This is a full Python tutorial (for Py 3!). It’s appropriate for both new and experienced programmers.

BEGINNER

  • INTRODUCTION

Python is available for download

You’ll need one of these applications to run Python code:

  • PyCharm is available for Windows, Mac OS X, and Linux.
  • Apple iPhone Pythonista
  • Additional programmes…………!!

Execute Python code

A.py extension should be used to save a Python application.
Try the following code:

print(“Hello World!”)
print(“Learn python in easy way!!.”)
Expected output:

Expected output:

Hello World!
Learn python in easy way!!
Interpreter

If you are using the interpreter use:

python program.py
  • STRING

python if string equals

A string or a group of characters

A string is a collection of characters that is typically used to show text.

Simply type words within quotes to define a string. Single, double, and triple quotes are all acceptable in Python.

String Input and Output

SINGLE QUOTES

s = ‘I am beginner’

print(s)

OUTPUT

I am begginer

DOUBLE QUOTES

S = “I am beginner”

print(S)

OUTPUT

I am brginner

  • VARIABLE

Variables can hold numbers that can be used multiple times.

Numbers can be any of the various datatypes:

  • a number (1,2,3,4)
  • to float (numbers behind the dot)

the boolean (True or False)

Numeric variables example

Example of numeric variables:


x = 1
y = 1.234
z = True


You can output them to the screen using the print() function.

x = 1
y = 1.234
z = True

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


Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).

Addition

x = 5

y = 8

print(x+y)

Multiplication

x = 5

y = 8

print(x*y)

Division

x = 5

y = 8

print(x/y)

Subtraction

x = 5

y = 8

print(x-y)

  • LIST

A list is a basic data structure and a sequence. Strings (text) and numbers can both be found in a list. In various programming languages, a list is comparable to an array, although it has more features.

The brackets [] are used to denote lists. The same brackets are used to access the data.
Use of a list as an example:
l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l) # prints all elements
print(l[0]) # print first element
print(l[1]) # prints second element

Add/remove

To manipulate the list, we can use the operations append() and remove().
l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l)                # prints all elements
l.append("Ram")         # add element.
print(l)                # print all elements
l.remove("Dark")        # remove element.
l.remove("Draken")      # remove element.
print(l)                # print all elements.

Sort the list

The sort() function can be used to sort the list.

l = [ "Ram", "Janu", "Mohan", "Priya" ]

print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
print(l)     # prints all elements
  • if STATEMENT

Conditional statements, often known as if-statements, can be defined in Python.

If specific circumstances are met, a block of code is executed.

If statements

Consider this programme: depending on the value of x, it performs both the first and second code.
x = 5
if x > 10:
    print("x smaller than 10")
else:
    print("x is bigger than 10 or equal")

If x is greater than 10, the second code block will be executed. The blocks are defined by indentation (4 spaces).

Conditional operators

Conditional operators: a word of warning

The assignment operator (=) must not be confused with the equals operator (==).

Nesting

Nesting is the most straightforward approach to do several conditions:

Operator Description
!= not equal
== equals

> greater than
< smaller than

a = 12
b = 33

if a > 10:
    if b > 20:
        print("Better")
  • FUNCTION

A function is a piece of code that can be repeated throughout your programme. Functions make your code more intelligible—instead of extensive lists of instructions, functions make code easier to grasp.

Furthermore, functions can be reused or updated, improving testability and extensibility.

Function definition

To define a function, we use the following syntax:

def function(parameters):
instructions
return value
  • PYTHON GLOBAL AND LOCAL VARIABLE

Global variables and local variables are the two sorts of variables.
A global variable can be accessed from anywhere in the code, whereas a local variable can only be read within the scope.

Tutorials in Python
global-local-variable

A global variable (x) can be read and updated anywhere in the code, whereas a local variable (z) can only be entered and altered in block 3.

Local variables

Local variables can only be viewed inside the scope of their scope.

Two local variables, x and y, are used in the example below.

def sum(x,y):
sum = x + y
return sum

print(sum(8,6))

The variables x and y can only be employed within the sum function; they are not available outside of it.

This line will not work because local variables cannot be used outside of their scope:

print(x)
Variables at the global level

Anywhere in the code, a global variable can be used.
We construct a global variable z in the example below.

z = 10

def afunction():
global z
print(z)

afunction()
print(z)

The global variable z can be used everywhere in the programme, both inside and outside of functions.
A global variable can be modified within a function and has an influence across the entire system:

  • SCOPE
In python, what is scope?

Variables can only reach the scope of the area in which they are defined. Consider it to be the section of code where variables can be used. Python has both global and local variables that can be used throughout the programme.

All variables declared in a function are local variables by default. To access a global variable within a function, the term “global variable” must be defined explicitly.

Example
We’ll look at how to use local variables and scope in the sections below. This is not going to work:
def f(x,y):
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))
z = 4 # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2
but this will:
def f(x,y):
z = 3
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))
print(z) # can reach because variable z is defined in the function

f(3,2)
  • LOOPS

A loop can be used to repeat code. Lines of code can be repeated an unlimited number of times, with N being manually adjustable. In effect, this means that the code will be continued until the condition is satisfied. The most frequent cause is (x > = N), although it isn’t the only one.

Loops in Python are categorised into three parts: for loops, while loops, and nested loops.

For loop

A for loop can be used to iterate over a list.
items = [ "Mohan","Greeshma","Mg","GM" ]

for item in items:
    print(item)
While loop

Use a while loop if you’re not sure how many times a code should be repeated.
As an example,

correctNumber = 5
guess = 0

while guess != correctNumber:
guess = int(input("Guess the number: "))

if guess != correctNumber:
print('False guess')

print('You guessed the correct number')
Nested loops

We can use nesting to combine loops. We could use if we wanted to iterate over a (x,y) field.

for x in range(2,20):
    for y in range(2,20):
        print("(" + str(x) + "," + str(y) + ")")

Nesting is beneficial, but the deeper you nest, the more hard it becomes.

  • RANGE

The range() method returns a series of numbers that starts at the lower bound and finishes at the upper bound.

range(lower_bound, upper_bound, step_size)
  • lower_ bound: The list’s initial value.
  • upper_ bound: The list’s maximum value, except this number.
  • step _ bound: The difference between each number in the list, in steps.

The parameters lower bound and step size are optional. The lower bound is set to zero by default, and the cumulative step is set to one. The parameters must be of integer type, however they might be negative.

Tutorials in Python

The interpreter’s python range function

A variation in range implementation


Normally, this distinction will not be a problem. In Python versions, range() is implemented slightly differently:

  • The range() method in Python 2.x returns a list.
  • The range() method in Python 3.x creates a sequence.
  • TUPLE

To hold a bunch of data, the tuple data structure is used. A comma separates the elements in this group. A tuple’s values cannot be altered once it has been formed.

Tuple in Python

In Python, an empty tuple is defined as:

tuple = ()

For a tuple with only one component, a comma is necessary.

tuple = (9,)

The comma for a single item may seem counterintuitive, but without it, you won’t be able to access the element. You don’t need to put a comma at the conclusion of a list of numerous things. This is an example of a set:

personBio = ("Mohan", 18, "India")

A tuple can include data of one or more data kinds, such as text and numbers.

Data accessibility

We can just use an index to get the data. An index, as is customary, is a number enclosed in brackets:

personBio = ("Mohan", 18, "India")
print(personBio[0])
print(personBIO[1])

You can use tuples to assign many variables at the same time:

name,age,country,career = ('Mohan',18,'India','cs')
print(country)

The tuple is written on the right side. The appropriate output variables are to the left of the equality operator.

In Python, you can append to a tuple.

The + operator can be used to append to a tuple that already exists. You can only attach a tuple to a tuple that already exists.

y = (1,2,3)
y = y + (4,5,6)
print(y)
  • DICTIONARY

A dictionary is a collection of key: value pairs that aren’t in any particular sequence.

An empty dictionary is created by a pair of braces:. Each element has the ability to map to a specific value. The index can be either an integer or a string. Dictonaries are not arranged in any particular order.

Using a dictionary as an example

Let’s create a basic dictionary:

Dictionary = {}
Dictionary["Hello"] = "Mohan"
Dictionary["Yes"] = "18"
Dictionary["No"] = "India"
Dictionary["Bye"] = "Tamil Nadu"

print(Dictionary["Hello"])
print(Dictionary["No"])
OUTPUT
Mohan
18
  • python cast

Python, for example, automatically decides the datatype:

x = 8
y = "Hello"

It discovers that x is an integer and that y is a string.

A certain datatype is accepted by functions. Print, for instance, only accepts the string datatype.

Datatypes casting

Casting is frequently required for printing numbers.
We wish to print two numbers in this example, one full number (integer) and one floating point number.

x = 8
y = 7.1531

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

Using the str() function, we converted the variables x (integer) and y (float) to strings.

  • PYTHON CLASS
INTRODUCTION

Technology is continually changing. What exactly are classes, and where did they originate?

  1. Make a statement:
    Programmers used to write merely commands in the early days of computing.
  2. Features:

A reusable set of statements aided in the organisation of the code and increased readability.

  1. Subjects:

Objects with functions and variables are created using classes. Objects include strings, for example: The functions book.replace() and book.lowercase() are available on a string book (). Object-oriented programming is a term used to describe this programming technique.

  • ENCAPSULATION

You can restrict access to methods and variables in an object-oriented Python programme. Encapsulation is a technique that prevents data from being accidentally modified. Let’s have a look at an example.

Encapsulation encapsulation encapsulation encapsulation encapsulation encapsulating encapsulation Access to methods or variables is restricted.


We make a Car class with two methods: drive() and updateSoftware() ().

When a car object is created, the private methods __updateSoftware are called ().

This function can only be invoked from within the class, not directly on the object.

class Car:

    def __init__(self):
        self.__update_Software()

    def drive(self):
        print('driving')

    def __update_Software(self):
        print('updating software')

redcar = Car()
redcar.drive()
OUTPUT
updating software
driving

Encapsulation prevents unintentional access, but not intended access.

The private attributes and methods aren’t truly hidden; they’ve just been renamed with “_Car” at the start.

Redcar. Car updateSoftware can be used to call the method ()

encapsulation-example of private variables

Private variables in a class
Variables can be private, which is handy in a variety of situations. A private variable can only be modified within the scope of a class method, not outside of it.

Objects can store critical data for your application, which you don’t want to update from anywhere in the code.

Encapsulation in Python

To summarise, Python has the following features:

Protected class methods exist in other programming languages as well, but not in Python.

Encapsulation allows you to have more control over the degree of coupling in your code by allowing a class’s implementation to be changed without affecting other portions of the code.

  • INHERITANCE
inheritance in python classes

Other classes’ functionality can be inherited by classes. If you create an object with a class that inherits from a superclass, the object will have both the class’s and the superclass’s methods. The same is true for variables in both the superclass and the superclass’s descendant class.

Unlike other popular programming languages, Python allows inheritance from numerous classes.

  • POLYMORPHISM

An object can come in a variety of shapes and sizes. There are many possible draw outputs for a button (round button, check button, square button, image button), but they all follow the same logic: onClick (). We use the same strategy to get to them. Polymorphism is the term for this concept.

Polymorphism is derived from the Greek words poly (many) and morphism (to change) (forms). We’ll build a building that can hold or employ a variety of objects.

Function-based polymorphism:

We make two classes: Bear and Dog, each of which has its own characteristic sound. Then we create two instances and use the same way to call their actions.

Polymorphism with an abstract class is a type of polymorphism (most commonly used)
The Document class defines the abstract structure.
You may not know in advance what type of documents a user will open if you create an editor (pdf format or word format?).

Isn’t it great to be able to access them in this way, rather than having 20 different types for each document?

  • INNER CLASS

An inner class, also known as a nested class, is one that is wholly contained within the body of another class. If you construct an object with a class, you can utilise the object inside the root class. Although a class can contain multiple inner classes, inner classes are generally avoided.

Python’s ability to nest classes within classes is one of its most useful and powerful features. A nested class is one that is defined within another class and inherits all of the parent class’s variables and methods.

An example of an inner class
Inner classes exist in Python. Classes that are defined inside other classes are known as inner classes. All members of the outer classes have access to the members of the inner classes.

When using inner classes, indentation is crucial. Each inner class should be four spaces indented.

  • PYTHON FACTORY METHOD

It’s possible that we won’t always know what kind of objects we want to make ahead of time.
Some objects can only be created at runtime if a user requests it.

  • When should you use a factory method?
  • A user can build an object by clicking on a specific button.
  • A user can generate several new documents of various types.

When a user opens a web browser, the browser has no idea how many tabs (each of which is an object) will be opened.

  • THREADING

Threads can be created in Python using either the thread module in Python 2.x or the _thread module in Python 3. To interface with it, we’ll use the threading module.
A thread is an operating system procedure that differs from a regular process in the following ways:

  • Threads are a type of process that exists as a subset.
  • Memory and resources are shared by threads.
  • Each process has its own address space (in memory)

When do you think you’d use threading? When you want a function to run at the same time as your programme, this is usually the case. If you’re writing server software, you want it to be able to listen to multiple connections rather than just one. In a nutshell, threads allow programmes to perform numerous tasks at the same time.

Threads that are timed

The Timer class in Python is a subclass of the Thread class. This indicates that it behaves similarly. The timer class can be used to construct timed threads. Timers, like conventional threads, are launched with the.start() function call. The following programme starts a thread after 5 seconds.

  • LAMBDA

Lambda functions are anonymous functions that can be created. Lambda functions are distinct from standard Python functions since they are derived from the Lambda Calculus. It enables the creation of very short functions.

  • SETS IN PYTHON

In Python, a set is a group of objects. Python 2.4 and newer versions have the ability to create sets. They differ from lists and tuples in that they are based on mathematical sets.

  • MODULES

Programming in modules

The software can quickly scale into a big code base as you programme. We can utilise classes, functions, and modules to control complexity.

  • BINARY NUMBERS

We’ve already looked at basic numbers and operations. In this post, you’ll learn how numbers function within the computer, as well as a little magic:-)

More information: While this isn’t immediately useful in online or most desktop programmes, it’s still good to know.

You’ll learn how to use binary numbers in Python, how to convert them to decimals, and how to perform bitwise operations on them in this tutorial.

Binary numbers are a type of number.

At its most basic level, the computer has no concept of numbers other than ‘there is a signal’ or ‘there isn’t a signal.’ You can think of it as a light switch: either it’s on or it’s off.

The lowest quantity of information that can be stored on a computer is known as a bit. A bit is represented as either low (0) or high (1). (1).

The idea of using a sequence of bits to represent integers greater than one was born. A byte is a sequence of eight bits that can store many greater numbers. Binary is a two-digit number sequence made up of ones and zeros. Our ten-digit counting system has been around for a long time.

Binary numbers and logical operations


Binary Left Shift and Binary Right Shift are two different types of shifts.
In binary, multiplying by a factor of two and dividing by a factor of two are both fairly simple operations. Simply move the parts to the left or right. Below, we move to the left:

Bit 4Bit 3Bit 2Bit 1
0101
1010
  • PYTHON DEBUGGING

To minimise and discover errors, we can use debugging tools. This post will teach you the best Python debugging techniques.

Leave a Reply

Your email address will not be published.