Python from Scratch

Python from Scratch

What is Python?


Python is an interpreted and high-level programming language which was originated in the year of late 1980s but it was implemented in December 1989 by Guido Van Rossum. The word Python came from the snake. According to the recent survey by StackOverflow, Python has overtaken java in popularity.

Python is dynamically typed, and garbage-collected language which aims to help a programmer to write clear and logical code for both small and large-scale projects.

Learning Python is good because Python is a famous programming language because it is easy to learn and use. Moreover, there is a large number of libraries available that can be used in your projects today! Some developers even consider it to be a must-known programming language.

Python is opensource which was developed under OSI-approved license, making it freely usable and distributable, even for commercial use. It means any of them can contribute to the python software.


Python Interpreter


An interpreter is a kind of program that executes other programs when you write python, programs, it converts source code written by the developer into an intermediate language. Which again translated into the native language/machine language that is executed.


python interpreter working

The python code written by you is computed into python byte code, which creates a file with the extension .Py. The byte code compilation happens internally and almost completely hidden from the developer. The compilation is simply a translation step, and byte code is a lower-level and platform-independent representation of your source code. Roughly, each of your source statement is translated into a group of byte code instructions, this byte code translation is performed to speed execution of byte code.

The .py file is created during the compilation step in order to execute the data present in the file. Hence interpreter is mostly used for compiling each and every line in python code.


Python Environment


The best environment to learn and execute your code in python is Anaconda. Anaconda is an open-source platform with an inbuilt package of different software required for a developer to execute his skill. Anaconda is popular as it contains many of the tools used in data science and Machine learning with just one install, so it is better to have a short and simple setup.


anaconda ide

To Setup Python Environment, follow the below steps–

Step1: Go to Google and type Anaconda.

Step2: Click on the first link.

Step3: Click “Get Started” button.


Step4: Click on “See all Anaconda products” button.



Step5: Go to “Individual Edition” and click on “Learn More“.



Step6: Now click on “Download” button.



Step7: You will automatically be redirected to down of the page where you can select your system config: Windows- 32/64 bit, Mac, and Linux click download it.



Step8: Install it in your PC/laptop/Mac.


You are ready to become a developer!!



Python Syntax


To print any statement or a sentence you just need to use “print(“YOUR DATA”)“.

Example

print(“Hello world!!”)

Output

Hello world!!

Python Indentation


Indentation in python programming plays a very important role. Indentation refers to space at the beginning of the code. You can indent your code by clicking the space bar 4 times or a tab button once.

Example

if 10>4:
    print(“10 is greater than 4”)

Output

10 is greater than 4

If you don’t follow indentation rules then, you will get Syntax Error.

Example

if 10>4:
print(“10 is greater than 4”)

Output

Syntax Error

 Python Comments


Python also has an ability for commenting on the source code. In python, comments start with a #, and python will render the rest of the lines as a comment.

Example

#This is a comment
print(“Hello world!!”)

Output

Hello World!!

Python Operators


Operators are the constructs, which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands, and + is called the operator.


Python provides Python Operators as most of the languages do. Every programming language has operators. Operators are necessary to work with logics in a program. They tell the compiler or interpreter to perform some mathematical, relational, or logical operations and produce a result. These are special symbols to the language like +, , *, and /. They are like functions which take one or more argument and produces the result.


Python has the following group of operators:


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

Arithmetic Operators


Assume a=10, b=5


OperatorDescriptionExample
+ (Addition)It is used to add two operands.a+b=15
(Subtraction)It is used to subtract the second operand from the first perand.a-b=5
* (Multiplication)Used to multiply two operands.a*b=50
/ (divide)Used to divide first operand by second and results quotient.a/b=2.0
% (reminder)Returns the remainder after dividing first operand by second operand.a%b=0
** (Exponent)Returns the result after calculating the first operand to the power of second operand.a**b=100000
// (Floor division)It returns the floor value of the quotient produced by dividing the two operands.a//b=2

Comparison operators


Comparison operators are simple to understand as they return a boolean value i.e. True or False.


OperatorDescription
==Condition becomes True if two operands are equal
!=Condition becomes True if two operands are not equal
<=Condition becomes True if first operand is less than or equal to second operand
>=Condition becomes True if first operand is greater than or equal to second operand
>Condition becomes True if first operand is greater than second operand
<Condition becomes True if first operand is less than second operand

Assignment Operators


Assignment operators are used to assigning a calculated value from right-hand side expression(after calculation) to the left-hand side operand.


OperatorDescriptionExample
=Simply assigns right side expression to left side operanda=5
+=Adds left operand to right side operand and assigns the value back to left operanda += b is same as a = a+b
-=Decreases left operand value by right operand value and assigns value back to left operanda -= b is same as a = a-b
*=Multiply left operand value with right operand value and assigns the multiplied value back to left operanda *= b is same as a=a*b
%=Divides left operand by right operand and returns remainder which is assigned to left operanda %= b is same as a=a%b
**=Increases left operand to power of right operand and assigns result to left operanda **= b is same as a=a**b
//=It returns floor value as it divides left operand by right operand and assigns result to left operanda //= b is same as a=a//b


Logical Operators


OperatorExplanation
andLet two expressions be a==>True, b==>True then the expression a and b will be True while if anyone from a and b is False then the expression will be False
orLet two expressions be a==>False, b==>False then the expression a and b will be False while if anyone from a and b is True then the expression will be True
notif a is True then not a is False and vice-versa

Bitwise Operators


The bitwise operators are used to perform binary operations on operands.


OperatorDescription
& (binary and)If both the bits at the same place in two operands are 1, then 1 is copied to the result. Otherwise, 0 is copied
| (binary or)The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1
^ (binary xor)The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be 0
~ (negation)It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will be 1 and vice versa
<< (left shift)The left operand value is moved left by the number of bits present in the right operand
>> (right shift)The left operand is moved right by the number of bits present in the right operand

Membership Operators


Using Membership Operators, you can check whether a value is present in a Python data structure or not. It returns True if the value is present in the Python data structure else returns False.


OperatorDescription
inIt returns True if the value is present in the data structure(list, tuple)
not inIt returns False if the value is present in the data structure(list, tuple)

Identity Operators


The identity operators are used to decide whether an element certain class or type.


OperatorDescription
isIt is evaluated to be true if the reference present at both sides point to the same object
is notIt is evaluated to be true if the reference present at both sides do not point to the same object


Python Operator Precedence


We now know all operators and their uses but when they are applied with one another then we should know their precedence otherwise the result may not be the desired one.


OperatorDescription
**The exponent operator is given priority over all the others used in the expression.
~ + –The negation, unary plus, and minus.
* / % //The multiplication, divide, modules, reminder, and floor division.
+ –Binary plus, and minus
>> <<Left shift. and right shift
&Binary and.
^ |Binary xor, and or
<= < > >=Comparison operators (less than, less than equal to, greater than, greater then equal to).
<> == !=Equality operators.
= %= /= //= -= +=
*= **=
Assignment operators
is
is not
Identity operators
in
not in
Membership operators
not
or
and
Logical operators

Python Data types

python datatypes

Introduction to Data types

In computer science and computer programming, a data type or simply type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support various types of data, for example: real, integer or Boolean. A data type provides a set of values from which an expression (i.e. variable, function…) may take its values. This data type defines the operations that can be done on the data, the meaning of the data, and the way values of that type can be stored. A type of value from which an expression may take its value

Variables

Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

For example-

counter = 100

miles = 1000.0

name = “John”

print (counter)

print (miles)

print (name)

Here, 100, 1000.0 and “John” are the values assigned to counter, miles, and name variables, respectively. This produces the following result –

100

1000.0

John

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example-

a=b=c=1

Here, an integer object is created with the value 1, and all the three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example-

a, b, c = 1, 2, “john”

Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one string object with the value “john” is assigned to the variable c.



Standard Data Types

The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types-

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Numbers

Number data types store numeric values. Number objects are created when you assign a value to them. For example-

var1 = 1

var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

del var1[,var2[,var3[….,varN]]]]

You can delete a single object or multiple objects by using the del statement.

For example-

del var

del var_a, var_b

Python supports three different numerical types –

int (signed integers)

float (floating point real values)

complex (complex numbers)

All integers in Python 3 are represented as long integers. Hence, there is no separate number type as long.

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example-

str = ‘Hello World!’

print (str)

print (str[0])

print (str[2:5])

print (str[2:])

print (str * 2)

print (str + “TEST”)

This will produce the following result-

Hello World!

H

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Python Lists

Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One of the differences between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example-

list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]

tinylist = [123, ‘john’]

print (list)

print (list[0])

print (list[1:3])

print (list[2:])

print (tinylist * 2)

print (list + tinylist)

This produces the following result-

[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]

abcd

[786, 2.23]

[2.23, ‘john’, 70.200000000000003]

[123, ‘john’, 123, ‘john’]

[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’]

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.

The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example-

tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )

tinytuple = (123, ‘john’)

print (tuple)

print (tuple[0])

print (tuple[1:3])

print (tuple[2:])

print (tinytuple * 2)

print (tuple + tinytuple)

This produces the following result-

(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003)

abcd

(786, 2.23)

(2.23, ‘john’, 70.200000000000003)

(123, ‘john’, 123, ‘john’)

(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’)

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists –

tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )

list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]

tuple[2] = 1000

list[2] = 1000

Python Dictionary

Python’s dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example-

dict = {}

dict[‘one’] = “This is one”

dict[2] = “This is two”

tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’}

print (dict[‘one’])

print (dict[2])

print (tinydict)

print (tinydict.keys())

print (tinydict.values())

This produces the following result-

This is one

This is two

{‘dept’: ‘sales’, ‘code’: 6734, ‘name’: ‘john’}

[‘dept’, ‘code’, ‘name’]

[‘sales’, 6734, ‘john’]

Dictionaries have no concept of order among the elements. It is incorrect to say that the elements are “out of order”; they are simply unordered.



Data Type Conversion in Python

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type-name as a function.

There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

int(x [,base]): Converts x to an integer. The base specifies the base if x is a string.

float(x): Converts x to a floating-point number.

complex(real [,imag]) : Creates a complex number.

str(x) : Converts object x to a string representation.

repr(x) : Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) : Converts s to a tuple.

list(s) : Converts s to a list.

set(s) : Converts s to a set.

dict(d) : Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s) : Converts s to a frozen set.

chr(x) : Converts an integer to a character.

unichr(x) : Converts an integer to a Unicode character.

ord(x) : Converts a single character to its integer value.

hex(x) : Converts an integer to a hexadecimal string.

oct(x) : Converts an integer to an octal string.

Loops in Python

loops in python

You go through your shopping list until you’ve collected every item from it. The dealer gives a card for each player until everyone has five.
The athlete does push-ups until reaching one-hundred… Loops everywhere! As for for loops in Python: they are perfect for processing repetitive programming tasks.

In Python, and all other modern programming languages, iteration statements (also called loops) allow a set of instructions to be repeatedly executed until a certain condition is reached. This condition may be predetermined (as in the for loop) or open-ended (as in the while and do-while loops). In another way we can say, A loop can be used to tell a program to execute statements repeatedly. Or we can say that a loop repeatedly executes the same set of instructions until a termination condition is met.

loop explanation

For Loop

Python implements an iterator-based ‘for loop’. It is a type of ‘for loop’ that iterates over a list of items through an explicit or implicit iterator.

The loop is introduced by the keyword ‘for’ which is followed by a random variable name

which will contain the values supplied by the object.

This is the syntax of Python’s ‘for loop’:

for variable in list:
statements
else:
statements

Here is an example of a ‘for loop’ in Python:

pizza = [“New York Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed Crust” ,”Pizza”]

for choice in pizza:
if choice == “Pan Pizza”:
print(“Please pay $16. Thank you!”)
print(“Delicious, cheesy ” + choice)
else:
print(“Cheesy pan pizza is my all-time favorite!”)
print(“Finally, I’m full!”)

Run this and you’ll get the following output on Python Shell:

Delicious, cheesy New York Style Pizza
Please pay $16. Thank you!
Delicious, cheesy Pan Pizza
Delicious, cheesy Thin n Crispy Pizza
Delicious, cheesy Stuffed Crust Pizza
Cheesy pan pizza is my all-time favorite!
Finally, I’m full!

Using the range() Function with the for Loop

The range() function can be combined with the ‘for loop’ to supply the numbers required by the loop. In the following example, the range(1, x+1) provided the numbers 1 to 50 needed by the ‘for loop’ to add the sum of 1 until 50:

x = 50
total = 0
for number in range(1, x+1):
total = total + number
print(‘Sum of 1 until %d: %d’ % (x, total))

The Python Shell will display:

l.py
Sum of 1 until 50: 1275

The While Loop

A Python ‘while loop’ repeatedly carries out a target statement while the condition is true. The loop iterates as long as the defined condition is true. When it ceases to be true and becomes false, control passes to the first line after the loop.

The ‘while loop’ has the following syntax:

while condition
statement
statement

Here is a simple ‘while loop’:

counter = 0
while (counter < 10):
print(‘The count is:’ , counter)
counter = counter + 1
print(‘Done!’)

If you run the code, you should see this output:

l.py

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
Done!

If-else in Python

Introduction

We use if statements in our everyday life all the time – even if our everyday life is not written in Python. If the light is green then I’ll cross the road; otherwise, I’ll wait. If the sun is up then I’ll get out of bed; otherwise, I’ll go back to sleep. Okay, maybe it’s not this direct, but when we take actions based on conditions, our brain does what a computer would do: evaluate the conditions and act upon the results. Well, a computer script doesn’t have a subconscious mind, so for practicing data science, we have to understand how an if statement works and how we can apply it in Python!

if-else

Let’s say we have two values: a = 10 and b = 20. We compare these two values: a == b.
This comparison has either a True or a False output. (Test it in your Jupyter Notebook!)

code1

We can go even further and set a condition: if a == b is True then we print ‘yes’.
If it’s False then we print ‘no’. And that’s it, this is the logic of the Python if statements.
Here’s the syntax:

code2

Run this mini script in your Jupyter Notebook! The result will be (obviously): no.

Now, try the same – but set b to 10!

The returned message is yes.

code3

Python if statement syntax

Let’s take a look at the syntax,
because it has pretty strict rules.

The basics are simple:

if statement syntax

You have:

1.an if keyword, then

2.a condition, then

3.a statement, then

4.an else keyword, then

5.another statement.

6.However, there are two things to watch out for:

1. Never miss the colons at the end of the if and else lines!

if-else statement syntax

2. And never miss the indentation at the beginning of the statement-lines!

if-else indentation

If you miss any of the above two, an error message will be returned saying “invalid syntax” and your Python script will fail.

Python if statements – level 2

Now that you understand the basics, it’s time to make your conditions more complex – by using arithmetic, comparison and logical operators. (Note: if the word “operators” does not ring any bells, you might want to check out this article first:

This script will return yes, since both of the conditions, (a + b) / c == 1 and c – b – a == 0 are actually True and the logical operator between them was: and.

Python if statements - level 2

Of course, you can make this even more complex if you want, but the point is: having multiple operators in an if statement is absolutely possible – in fact, it’s pretty common in real life scenarios!

Python if statements – level 3

You can take it to the next level again, by using the elif keyword (which is a short form of the “else if” phrase) to create condition-sequences. “Condition-sequence” sounds fancy but what really happens here is just adding an if statement into an if statement:

Python if statements - level 3

Sure enough the result will be “second condition is true”.

elif

You can do this infinite times, and build up a huge if-elif-elif-…-elif-else sequence if you want!
And… This was more or less everything you have to know about Python if statements.



Functions in Python

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

The first statement of a function can be an optional statement – the documentation string of the function or docstring.

python function parameters

The code block within every function starts with a colon (:) and is indented.

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None

Syntax:

def functionname( parameters ):

“function_docstring”

function_suite

return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

example:

The following function takes a string as input parameter and prints it on the standard screen.

def printme( str ):

“This prints a passed string into this function”

print (str)

return

Calling a Function

Defining a function gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is an example to call the printme() function-

def printme( str ):

“This prints a passed string into this function”

print (str)

return

printme(“This is first call to the user defined function!”)

printme(“Again second call to the same function”)

This is first call to the user defined function!

Again second call to the same function

Pass by Reference vs Value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example-

def changeme( mylist ):

“This changes a passed list into this function”

print (“Values inside the function before change: “, mylist)

mylist[2]=50

print (“Values inside the function after change: “, mylist)

return

mylist = [10,20,30]

changeme( mylist )

print (“Values outside the function: “, mylist)

OUTPUT:

Values inside the function before change: [10, 20, 30]

Values inside the function after change: [10, 20, 50]

Values outside the function: [10, 20, 50]

Function Arguments

You can call a function by using the following types of formal arguments-

Required arguments

Keyword arguments

Default arguments

Variable-length arguments

Required Arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error

Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function

Default Arguments

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Variable-length Arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using thedefkeyword. You can use thelambdakeyword to create small anonymous functions.

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

An anonymous function cannot be a direct call to print because lambda requires an expression.

Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.

Syntax:

lambda [arg1 [,arg2,…..argn]]:expression

example:

sum = lambda arg1, arg2: arg1 + arg2

print (“Value of total : “, sum( 10, 20 ))

print (“Value of total : “, sum( 20, 20 ))

OUTPUT:

Value of total : 30

Value of total : 40

Through the above basics, you can code in python and go for a higher-level of codings like Machine learning and Data science keeping your basics and fundamentals strong is more important so try to grasp the basics using python.

Don’t stop learning because learning makes you more precised one

Happy learning!& Happy coding!!



Thanks for reading


Also Read:




Share:
Avatar of Harry

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you