Basics of Python Part -1

Expressions:

In python, 2+2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consists of values such as 2 & the + symbol is called operator.

Below is the list of Math Operators in python.

OperatorDescriptionExampleResult
+Addition5 + 38
Subtraction5 – 32
*Multiplication5 * 315
/Division (float)5 / 22.5
//Floor Division5 // 22
%Modulus (Remainder)5 % 21
**Exponentiation2 ** 38

The order of operations {Also called precedence} of python math operators is similar to that of mathematics. The Exponentiation operator is evaluated first, the Multiplication, division & modulus operators are evaluated next & then addition, subtraction are evaluated in the last starting from left to right. You can use parentheses to override the usual precedence.

In each case the expression you enter will be evaluated t o a single value by python.

Examples of Valid Expressions:
2 ** 8
23/7
(2+1) * (2*3)

You will get an error if you make a mistake or give unclear expression.

Examples of invalid Expressions:
2*+5
5+

Data Types:

Expressions are just values combined with Operators. They always evaluate down to a single value. The data type is a category for values. Every value belongs to a data type. The most common data types in python are listed below in the table.

Data TypeDescriptionExample
intIntegerx = 10
floatFloating-point numberx = 3.14
boolBoolean (True/False)x = True
strString (text)x = “Hello”
listOrdered, mutable listx = [1, 2, 3]
tupleOrdered, immutable listx = (1, 2, 3)
dictKey-value pairsx = {“a”: 1}

We will talk about each of these data types specifically. But Some of them are very common in any programming language like Int, Float & String

The meaning of an operator may change based on the data type of the value next to it. For example, + is addition when the operator is used between two integer or float values. But if used on string values, it joins the strings & concatenates them.

if a + operator is used between 2 values of different data type such as an integer & a string, Python would not know how to interpret this & will give an error.

The * operator multiples two integer or two float values but when used on one string & one integer it becomes string replication.

Variables:

A variable is a placeholder in computers memory. If you want to use the result of an evaluated expression later in your program, you can save it inside a variable.

You can store values in a variable by using an assignment statement. The assignment statement consists of variable name, an equal sign and the value to be stored.

Ex: fruits = 3

A variable is created the first time a value is stored in it. After that you can use it in expressions with other variables & values. When a variable is assigned a new value, the old value is forgotten. This is called overriding the variable.

Variable Names:

A good variable name describes the data it contains, Imagine that you moved to a new city & labelled all your moving boxes as “Important Stuff” you’d never find the item you need when unpacking. Everything becomes Important Stuff.

Variable names in python are case sensitive. Meaning, Name, NAME, NaME & name are four different variables. they are not equal.

You can name your variable almost anything, but there are few rules.

  1. It can only be one word with no spaces
  2. It can only use letters, numbers & underscore charecter.
  3. It can’t begin with a number.
Comments:

Python interpreter ignores comments, you can use them to write notes to remind your self what the code is trying to do. Any text for the rest of the line following the ‘#’ mark is a comment. Python also ignores blank lines after a comment. You can add as many blank lines you need in your program.

The print() Function:

The print() function displays the string value inside its parentheses on the screen.

ex: print (‘hello world’)

Output : hello world

It should be noted that the quotes are not printed. They mark where the string begins & ends.

You can also use this function to put a blank line on the screen. Just call print() with nothing in between the parentheses

The input() Function

The input() function waits for the user to type some the keyboard & press enter.

Ex : Myname = input()

This function call evaluates to a string equal to the users text & the line of code assigns the Myname variable to this string value.

You can think of the input() function call as an expression that evaluates to whatever the user typed in.

The len() Function:

You can pass the len() function a string value or a variable containing a string & the function evaluates to the integer value of the number of charecters in the string.

Ex: len(‘hello’)
output: 5

The str(), int() & float() Functions:

If you want to concatenate an Integer such as number like 15 with a string to pass to print() function, you will need to get the value ’29’ which is the string form. The str() function can be passed to an integer value and it will evaluate to string version.

Ex : print (‘ I am’ + 29 + ‘years old’) will give an error. as adding a integer with string is not possible.

Instead, this should be given as follows using the str() function.

print (‘iam’ + str(29) + ‘years old’)

The str(), int() & float() functions will evaluate to string, integer & float respectively. The value is converted to a different data type using these functions.

it should be noted, that the input() function always returns a string even if the user enters a number. At that time, the number needs to be passed to int() or float() functions.

Flow Control:

Sometimes in a Program, you don’t want it to be executed from start to finish in a sequential order. Depending on how the expressions evaluate, a program may skip certain lines of code or repeat them or choose some of them to be executed.

Flow control statements can decide which lines of code should be executed under which conditions.

The Flow control statements can be though of something similar to a flowchart. Just like how there can be different outputs for a flowchart depending on the conditional statements, so can flow control in programmes.

But, before we talk more about the flow control statements in detail, we need to talk about Boolean Values, comparison operator & Boolean operators.

Boolean Values :

Boolean data type has only two values, True & False. The T & F are capitalized and they don’t contains the quotes.

Like any other values Boolean values are used in expressions and can be stored in variables.

Comparison operator:

Comparison operators are also called relational operators that compare two values & evaluate down a single Boolean value.

These Operators evaluate to True or False depending on the values you give them.

OperatorDescriptionExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 3True
<Less than2 < 8True
>=Greater than or equal to6 >= 6True
<=Less than or equal to4 <= 5True
Boolean Operators :

There are three Boolean operators & they are used to compare Boolean Values. Like comparison operators these as well boil down the expressions down to a Boolean value.

The AND, OR operators take 2 Boolean Values & evaluate the expression to True or False.

The and operator give a output of True only if both expressions are evaluated to True. The or operator gives the output of True if either of the expression evaluates to True. & the not operator does take only one expression or value and the output is negation of the same.

OperatorDescriptionExampleResult
andLogical ANDTrue and FalseFalse
orLogical ORTrue or FalseTrue
notLogical NOT (negation)not TrueFalse

Below is a sample of mixing Boolean & Comparison Operators.

Example 1: (4<5) and (5<6)

Example2: (1=!2) or (3==3)

Just like Math operators, Boolean operators also have an order of operators. The not operator is evaluated first & then the and and or operators

Elements of Flow Control :

Flow control statements often start with a part called the condition & are always followed by a block of code called the clause.

Blocks:

Line of Python code can be grouped together in blocks. You can tell when a block begins and ends from the indentation of the lines of code.

If Statements

The most common type of flow control statement is the if statement. In an if statement clause will get executed if the condition is True. The clause is skipped if the condition is false.

Else statements

An if clause can optionally be followed by an else statement. The else clause is executed only when the if statement condition is False. The else statement does not have a condition.

Example :

if name == 'Alice':
    print ('Hi Alice')
else:
     print ('Hello not Alice')
Elif statements:

You may have a case where you want one of many possible clauses to execute. The elif statement is an ‘else if’ statement that always follows an ‘if’ or another ‘elif’ statement . it provides another condition that is checked only if all previous conditions were also False.

Example :

if name == 'Alice'
    print ('Hello Alice)
elif age < 12:
    print ('You are not a Major')
else:
    print (' Hello Stranger')

This time, in the above the persons age is checked & the program prints a message different if you are younger than 12.

The else clause is skipped in the above if age is less than 12. In the Elif statement once a condition is found to be true, the clause is executed & the rest of the elif clauses are automatically skipped. Hence the order of the elif statements is important.

While Loop:

You can make a block of code execute again & again by using a while loop statement. The code on the while clause will be executed as long as while statement condition is True.

At the end of an if statement, the program execution continues after the if statement. But at the end of the while clause, the program execution jumps back to the start of the while loop.

Example:

Test = 0
while Test <5;
    print ('Hello World')
     Test = Test+1

In the above case the Hello World output is printed 5 times. In While loop the condition is always checked at the start of iteration. as long as the condition holds True, the clause is executed.

Break Statement:

The break statement is a mechanism to break out of while loop clause early. In the below code, the program checks for the name. If the name entered is kapil then the break statement is executed and the while loop will break.

Example:

while True:
    print('please type your name')
    name = input()
    if name == 'kapil'
    break
print ('Thank you')
Continue statement:

Continue statements are used inside loops. When a program execution reaches a continue statement, the program execution immediately jumps to the start of the loop & re-evalulates the loop condition.

Example:

while True:
    print('who are you' )
    name = input()
if name != 'joe'
     continue
print ('Hello Joe, How are you ?)

In the above program, if the user enters any name other than joe, then the execution of program will go back to start of the loop. The execution will always enter the loop as the condition is simply True.

For loops & range() Function:

The While loop keeps looping while the condition is True, but if you want to execute a block of code only a certain number of times you would need to use for loop statement and the range() function.

Ex:

print ('My name is')
for i in range(5):
    print('Jimmy Five Times (' + str(i) + ')')

The output is printed as Jimmy Five Times is repeated 5 times. because, initially the value of i is set to zero & increments by 1 for every iteration.

You can use break & continue statements inside for loops as well. The continue statement will continue the next value of the loop and returned to the start.

Another example of for loop. The program will print the total of 1 + 2 + 3 + … + 101

total = 0
for n in range(101):
    total = total + n
print (total)
Range() Function:

Some functions can be called with multiple arguments separated by the comma, The range() function is one of them. This lets range() to follow any sequence of integers including starting at a number other than Zero.

The range function typically have 3 arguments, ( start value, stop value , step argument). The step is the amount that the variable is increased by after each iteration.

Example :

for i in range (0,10.2):
    print(i)

The output that this prints will be something like 0,2,4,6,8 as the step represents the amount the variable is increased by after each iteration.

Also it should be noted, that the range function is flexible. You can use it with negative numbers as well such as.

Example:

for i in range (5 ,-1,-1):
    print(i)

Output would be something like 5,4,3,2,1,0

Importing Modules:

All python programs can call the basic set of functions called built-in functions. These functions are the ones like print(), input() & len().

But there are some functions that are part of a different modules. Each module of python is a program that contains a related group of code that can be embedded in your programs.

for example, the math module has mathematics related functions, Before you can use the functions defined in these modules in your programs you have to import that module & that can be done by using an import statement.

the import keyword is followed by the name of the module. You can import more than one module using a single import statement with the module names separated by comma.

Example:

import random
for i in range(5):
    print (random.randint(1,10))

The above code prints five random numbers in the range of 1 to 5 for 5 times. but it has to be noted, that the randint() function was proceeded by random before the function name to tell python to look for that function inside the random module.

From import statements:

An alternative form of the import statement is composed of from keyword followed by the module name & then the import keyword and a star.

This form of import will not need the random prefix we talked about earlier. We can just simply call the function by it’s name.

Example:

from random import *
for i in range (5):
    print(randint(1,10))
sys.exit() function:

Programs always terminate if the program execution reaches the bottom of the instructions. However, sometime we will to terminate the program early by using the sys.exit() function. You have to import the sys module before you can use it.

Example:

import sys
while True:
    print('Type exit to exit')
    response = input()
    if response == 'exit':
         sys.exit()
    print('you typed' + response)

The program is an infinite loop. The only time the program exits is if the user types the input of exit.

error: Content is protected !!