Search This Blog

Learn the basic/codersdot1.blogspot.com ! Python Programming Language!...

 


Welcome

Welcome to the LearnPython.org interactive Python tutorial.

Learn the basics of the world's fastest growing and most popular programming language used by software engineers, analysts, data scientists, and machine learning engineers alike.

Python is a general-purpose, versatile and popular programming language. It’s great as a first language because it is concise and easy to read, and it is also a good language to have in any programmer’s stack as it can be used for everything from web development to software development and scientific applications. 

Python is considered one of the easiest programming languages to learn. While anyone can learn Python programming — even if you've never written a line of Python code before — you should expect that it will take time, and you should expect moments of frustration.

Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the Python programming language.

Just click on the chapter you wish to begin from, and follow the instructions. Good luck!

Learn the Basics


1: Hello! World!


Hello! World!(Program)

Python is a very simple language, and has a very straightforward syntax. It encourages programmers to program without boilerplate (prepared) code. The simplest directive in Python is the "print" directive - it simply prints out a line (and also includes a newline, unlike in C).

There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different. This tutorial uses Python 3, because it more semantically correct and supports newer features.

A simple program that displays “Hello, World!”. It's often used to illustrate the syntax of the language.


2: Variables and Types

Variables and Types(Program)

Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name.

For example: >>> >>> n = 300.

This tutorial will go over a few basic types of variables.

  • Numbers

Python supports two types of numbers - integers(whole numbers) and floating point numbers(decimals). (It also supports complex numbers, which will not be explained in this tutorial).

A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
For Example: - (A-z, 0-9, and _ )

  • Strings

Strings are defined either with a single quote or a double quotes.

Python String Concatenation and Variable.

For example, we will concatenate “Guru” with the number “99”. Once the integer is declared as string, it can concatenate both “Guru” + str(“99”)= “Guru99” in the output.

3: - Lists

List(Program)

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 very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner.

For example, you want to create a list to store the first five even natural numbers. Even= [2,4,6,8,10]. Here [2,4,6,8,10] are the list items of the list named Even.

Exercise(DO)

The target of this exercise is to create a string, an integer, and a floating point number. The string should be named mystring and should contain the word "hello". The target of this exercise is to create a string, an integer, and a floating point number.

In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable.

4: - Basic Operators

Basic Operator(Program)

This section explains how to use basic operators in Python.

Arithmetic Operators

There are 7 arithmetic operators in Python

  • Addition.
  • Subtraction.
  • Multiplication.
  • Division.
  • Modulus.
  • Exponentiation.
  • Floor division

Using Operators with Strings

  • Assignment operator: “=.”
  • Concatenate operator: “+.”
  • String repetition operator: “*.”
  • String slicing operator: “[]”
  • String comparison operator: “==” & “!= ”
  • Membership operator: “in” & “not in”
  • Escape sequence operator: “\.”
  • String formatting operator: “%” & “{}”

A couple of the operators that you use on numeric operands can be applied to strings as well—the operator that looks like a plus sign ( + ), which in this case is considered the concatenation operator, and the multiplication sign operator ( * ), which with strings is considered the replication operator.

    Using Operators with Lists

append() The append() method is used to add elements at the end of the list.extend() The extend() method is used to add more than one element at the end of the list.

insert() The insert() method can add an element at a given position in the list.

  • remove() 
  • pop() 
  • slice.
  • reverse()
  • len()
Create a variable to store the input list and give it some random values.
To print list elements separated by spaces without brackets [] first we convert the list to a string by passing the str and list as arguments to the map () function.

The in operator determines whether a given value is a constituent element of a sequence such as a string, array, list, or tuple. When used in a condition, the statement returns a Boolean result of True or False.

Exercise

The target of this exercise is to create two lists called x_list and y_list, which contain 10 instances of the variables x and y, respectively. You are also required to create a list called big_list, which contains the variables x and y, 10 times each, by concatenating the two lists you have created.


5: - String Formatting

String Formatting(Program)

formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions. They then get joined up to build the final string.

string formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

The Format String is the argument of the Format Function and is an ASCII Z string which contains text and format parameters, like: printf (“The magic number is: %d\n”, 1911); • The Format String Parameter, like %x %s defines the type of conversion of the format function.

For Example: - 

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.

6: - Basic String Operations

Basic String Operations(Program)

  • Assignment operator: “=.”
  • Concatenate operator: “+.”
  • String repetition operator: “*.”
  • String slicing operator: “[]”
  • String comparison operator: “==” & “!= ”
  • Membership operator: “in” & “not in”
  • Escape sequence operator: “\.”
String formatting operator: “%” & “{}”

MethodDescription
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

The first thing you learned was printing a simple sentence. This sentence was stored by Python as a string. However, instead of immediately printing strings out, we will explore the various things you can do to them. You can also use single quotes to assign a string. However, you will face problems if the value to be assigned itself contains single quotes

7: - Conditions

Conditions(Program)

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.

              Python Conditions and If statements

              8: - Loops

              Loops(Program)

              There are two types of loops in Python, for and while.

              The "for" loop

              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.

              For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange). Note that the range function is zero based

              Syntax:

              for iterator_var in sequence:
                  statements(s)
              Example of Python for Loop

              # Python program to illustrate
              # Iterating over a list
              print("List Iteration")
              l = ["geeks", "for", "geeks"]
              for i in l:
                  print(i)
               
              # Iterating over a tuple (immutable)
              print("\nTuple Iteration")
              t = ("geeks", "for", "geeks")
              for i in t:
                  print(i)
               
              # Iterating over a String
              print("\nString Iteration")
              s = "Geeks"
              for i in s:
                  print(i)
               
              # Iterating over dictionary
              print("\nDictionary Iteration")
              d = dict()
              d['xyz'] = 123
              d['abc'] = 345
              for i in d:
                  print("%s  %d" % (i, d[i]))
               
              # Iterating over a set
              print("\nSet Iteration")
              set1 = {1, 2, 3, 4, 5, 6}
              for i in set1:
                  print(i),

              Output: 

              List Iteration
              geeks
              for
              geeks
              
              Tuple Iteration
              geeks
              for
              geeks
              
              String Iteration
              G
              e
              e
              k
              s
              
              Dictionary Iteration
              xyz  123
              
              abc 345


              "while" loops

              Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.
              While loops repeat as long as a certain boolean condition is met.


              Syntax: 

              while expression:
                  statement(s)

              Example of Python while Loop


              # Python program to illustrate
              # combining else with while
              count = 0
              while (count < 3):
                  count = count + 1
                  print("Hello Geek")
              else:
                  print("In Else Block")


              Output: 

              Hello Geek
              Hello Geek
              Hello Geek
              In Else Block

              9: - Functions

              Functions(Program)

              A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.


              Example


              def my_function():
                print("Hello from a function")

              where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".


              Exercise

              In this exercise you'll use an existing function, and while adding your own to create a fully functional program.

              Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code.reuse", "Allowing programmers to share and connect code together"

              Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"

              Run and see all the functions work together!


              10: - Classes and Objects

              Classes and Objects(Program)

              Create a Class

              To create a class, use the keyword class:


              Example

              Create a class named MyClass, with a property named x:

              class MyClass:
                x = 5


              Create a Object

              Now we can use the class named MyClass to create objects:


              Example

              Create an object named p1, and print the value of x:

              p1 = MyClass()
              print(p1.x)


              11: - Dictionaries

              Dictionaries(Program)


              A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.

              Both are mutable.

              Both are dynamic. They can grow and shrink as needed.

              Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

              12: - Modules and Packages

              Modules and Packages(Program)

              A Python Module can be a simple python File (. py extension file), i.e., a combination of numerous Functions and Global variables. A Python Package is a collection of different Python modules with an __init__.py File. __init__.py Python File works as a Constructor for the Python Package


              A Python module is any Python files with a .py extension. It can be imported into python without the .py part.

              A Python package is nothing but a collection of modules along with

              __init__.py file. The modules can also be arranged in hierarchy of folders inside a package.

              In programming, a module is a piece of software that has a specific functionality. For example, when building a ping pong game, one module may be responsible for the game logic, and another module draws the game on the screen. Each module consists of a different file, which may be edited separately.