0% found this document useful (0 votes)
45 views91 pages

Python

The document discusses various programming concepts in Python like data types, variables, operators, control structures, functions and collection types. It provides examples of arithmetic, logical and comparison operators. It explains different types of control structures like sequential, conditional and iterative structures. It also discusses functions, recursion, strings, lists, tuples and dictionaries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
45 views91 pages

Python

The document discusses various programming concepts in Python like data types, variables, operators, control structures, functions and collection types. It provides examples of arithmetic, logical and comparison operators. It explains different types of control structures like sequential, conditional and iterative structures. It also discusses functions, recursion, strings, lists, tuples and dictionaries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 91

For Assembly language need assembler to convert into machine language

High level languages need compiler or interpreter to convert to machine language

C, C++ are platform dependent and Java, Python, VB are platform independent

When java program is compiled will get byte code

JVM – Java Virtual Machine executes Java byte codes

Compiled – Compile the whole program and execute next (C, Java)

Interpreter – Read each line by line and if no error that will be executed (Python)

C & Java first run the whole syntax (that means compiled) and if no errors then it will execute but
Python runs and execute line at the same time and moves to next line – Interpreted

The interpreter executes the program directly, translating each statement into a sequence of


one or more subroutines, and then into another language (often machine code)

C, VB used for desktop (stand-alone) applications

Java used for internet applications

PHP used for web applications

Python can be used for any type of applications


Syntax error – If any mistake in the syntax used for program, found during compilation

Logical error – If logic of the program is incorrect, result will be wrong

Runtime error – If program needs to use a file but file is not available
https://www.python.org

Download - Python 3.8.3

Copy the .exe file and save it for later use.

Double click .exe file and install – Check both the check boxes for installing

Open command prompt and type python –version


https://atom.io - Editor

Extension of python programs is .py

In command prompt can try the python commands


Variable – naming the empty memory to use

An identifier is a string to name a variable to store any value

In python no need to define any data type while declaring a variable.

Variables occupy primary memory

Assignment takes right to left

a=b+3

first addition is done and then assigned to variable a.

No character data type in Python, only string

Strings can be used by both single and double quotes


Strings can be used with single, double or triple quotes

Can have negative numbers assigned to variables

Data types – int, float, String, Boolean, complex


Type(variable) gives the data type of the variable

A variable can start with alphabet or underscore but not numbers.


Order of operations:

PEMDAS – Paranthesis, Exponention, Multiplication, Division, Addition, Subtraction

If a small number is divisible by big number we get remainder as same small number

7/8 = 7
Value taken by “input” function is string so need to convert the value if needed to integers using int
function like below

Int function takes only integers but not float but float can take integers as well. Please see below

print("welcome to python")

a=5

b=8

c = a+b
print("Sum=",c)

a=int(input("Enter the first number: "))

b=int(input("Enter the second number: "))

c=a+b

print("Sum=",c)

a=float(input("Enter the first number: "))

b=float(input("Enter the second number: "))

c=a+b

print("Sum=",c)

\n – New line

\t = Tab

\ = coding not ended and continued in next line

# - For comment

Functions learned:

Type

Print

Input

Int

Float

Str

For assigning values to multiple variables can follow the below

a,b = 6,7

At the same time single value can be assigned to multiple variables


If need to add multiple strings in the same print follow as above and if any arithmetic calculations
those to be converted as strings by using str()

There is another option of not converting numbers into string in print function, can use the format
function as below

item = input("Enter the item to purchase: ")

quantity = int(input("Enter the quantity: "))

rate = float(input("Enter the amount: "))

input("{0} {1}(s) of Rs.{2} each costs Rs.{3}/-".format(quantity,item,rate,quantity*rate))


Keyword should not use as identifier but can use keywords with capital letters as identifiers
Arithmetic operations +, -, /, *, %, //, **

Floor division - //

5/4 = 1.25

5//4 = 1 (Gives only integer value and remove decimals not round off the value)

% (Mod) - Reminder

5%2 = 1

5%5 = 0

4%5 = 4

** Exponentiation

5**2 – 5 square (5*5)

5***3 – 5 cube (5*5*5)

Assignment operation is “=”

Comparison operators:

<, >, <=, >=, ==, !=

Returns Boolean values (True / False)


Shorthand operators

a=4

a=a+4

a+=4

b=70

b=b-10 = (Answer is 60)

b-=10 = Answer is 50

b/=5 (Answer is 10)

b*=3 (30)

b%=2 (0)

b+=70 (70)

b//=3 (23)
b**=2 (23 square = 529)

Logical operators

And, or, not

Delimers:

()[]{},

Complex data type comes with imaginary literal


A=4+7j (Here j is the representation of complex number in Python)

B=3

A+b=7+7j (Integers are added together)

Type (a) = Complex data type

Control structure determines flow of execution of statements in a program

3 different types of control structures in any program language

1. Sequential
2. Conditional / selection
3. Iterative / loop

Sequential: It means execution of statements specified in the program one after the other

Conditional: based on condition or decision, a set of instructions to execute

Simple if, if ….. else, nested if else s, if …. Elif …. else

If <condition> :

Above getting both statements since else is working when if condition is not satisfied. So need to use
else if.
Program to print 0 and 1 alternatively up to a limit. Eg: if the limit is 5 then 0 1 0 1 0

Write a program to find the sum of n numbers entered by the user

If any variable is used to do some arithmetic operation then it should be initialised first

Sum=0

Sum=sum+i

n = int(input("Enter number: "))


length = 0 #additive identity
if n==0:
length = 1
else:
if n<0:
n*=-1
while n>0:
length +=1
n //= 10
print("length of the number =", length)

 Break statement skips the rest of the statements within the loop and exit (loop will not
continue)
 Continue statement skips the rest of the statements within the loop and continue with next
iteration

Range(x) – [0,1,2,…..x-1]

Range(x,y) – [x,x+1,x+2,…..y-1]

Rnage(x,y,z) – [x,x+z,x+z+z,x+3z,……]

range(5) - [0,1,2,3,4]
range(2,9) - [2,3,4,5,6,7,8]
range(2,9,3)-[2,5,8] // In this case from 2 to 9-1 increments with jump of 3
range(9,2,-2)-[9,7,5,3] // In this case from 9 to 2-1 decrements with jump of -2

if programmer knows in advance or prior to the execution, the total number of iterations required
for the loop then need to use “FOR LOOP”

if programmer doesn’t know the number of iterations before execution then use “WHILE LOOP”

Assignment:

Write a program to draw the patterns like the following

First scenario

Enter 3 , get below pattern

**

***
Second scenario

Enter 3 , get below pattern

* *

* * *

* * *

* *

Third scenario

Enter 3 , get below pattern

0 1

0 1 0

Fourth scenario

Enter 3 , get below pattern

1 1

0 0 0

1 1 1 1 (if enter 4)

Tutorialspoint.com

W3schools

Khan academy
Function: A small block of code that can be executed any no. of times at any position in a program

Two different type of programing

POP – Procedure oriented programming. Eg: C

OOP – Object oriented programming. Eg: C++, Java

If two functions having the same name it won’t throw any error but the first function will be
over written by the last one
Def sum(x,y)

Def – Keyword

Sum – function name

X, y – parameters / formal arguments

Sum(a,b)

A,b – arguments / actual arguments

Arguments and parameters should be the same number otherwise will get error

We can’t method over loading (polymorphism) in Python. That means same function name with
different arguments since the last function is considered as the final one.

Below is not possible in python which is possible in Java

def sum(a):

print("Sum =",a+5)

def sum(a,b):

print("Sum =",a+b)

def sum(a,b,c):

print("Sum =",a+b+c)

So alternative method in python is to use *with parameter

Sum(*a)
Recursive function – Function statements called the same function.

Eg: factorial

Fact(n)

N*fact(n-1)

This can be used an alternative of loop control structures. There should be a terminating condition
inside the recursive function to terminate in order to avoid indefinite loop.

We shouldn’t use loops in recursive function

‘return keyword in function – exists from function

Stack – Stack follows Last in first out. Reverse of Queue (First in first out)

Intermediate values are stored in stack format (Bottom to top)

5!

5 * fact(4) - Bottom

Fact(4)=4 * fact(3) – Bottom+1

Fact(3) = 3 * fact(2) – Bottom + 2

Fact(2) = 2 * fact(1) – Bottom +1

Fact(1) – return 1 – Top

In stack order it replaces from fact(1) to fact(4) and returns the final value
String can be defined in three types

A=’one’

B=”$%^”

C=’’’ It is a

Mutilined

String’’’

D=””” It is again a

Multilined

String “””
Slicing can be done with string

A=”WELCOME”

A[0]=W

A[1]=E
1. Program to check whether a string is palindrome or not
2. Program to find the number of occurrences of a character in a string.
3. Program to replace a string with another string
Collection types – are data types that can store multiple elements in a single variable

Can store different data types in collection types

List

Set

Tuple

Dictionary

Web applications – List & dictionary are used


For I in mylist[::-1]:

Print(i) – In this line need to enter tab then enter two times to exit from the loop
Values can be changed, here “Safwan” changed to “Mohammed Safwan”

Adding new values using append function. Duplicates can be added. (List element can be changed,
duplicated)
Inserting in a particular position by using insert function

Can Insert any type of data type


Here remove(3), 3 is not an index but exact number. Number 3 will be removed from the list

Write a program to remove all the occurrences of a list item in the list

Can have spaces and comma at the end – no error will return

Del is used to delete all the elements in the list

Can specify specific position numbers to be deleted


Write a program to collect n names from the use and remove last element when arranged in
alphabetical order
Here both l1 and l2 are referring to same memory location. So change in l1 will reflect in l2 and
viceversa.

Here l3 is new variable getting the values of l1 copied not the actual memory location
Nested list example below
Declaration

Mt=(2,3,4)

Type(mt)

Mt=() – creating empty tuple

If we need to create a tuple with single value need mention comma ‘,’ otherwise it consider as int,
float, string

Mt=(9) – consider as int


Mt=(9,) – consider as tuple

We can’t change the value in tuple as shown above. So to change the value create a list assigning
the values from tuple, convert the values in list and again change list to tuple as below

Converting tuple to list – list(mt)

Converting list to tuple – tuple(mt)


Delete tuple as below
Dictionary can have any data type as above
Pop and del used to delete, difference is pop returns value and delete. Delete function won’t return
any value but just delete
Remove will get error if we try to delete number which is not in set but discard will not get error
OOPS concepts:

Abstraction / Encapsulation - Hiding

Inheritance – Getting features / properties from parents

Polymorphism – same command with different actions with different contexts


#static variables – available for all objects of a class

If self is not used as constructor in a method then it is static method


__init__ => special function inside the class that is defined using __ . It takes at least one argument
(self).

Constructor is a function which invokes automatically when object is created of a class


No method overloading in python. Considers last method and executes it. Instead of it can use
multiple variable arguments.

And can be done this with operator overloading as well.


Write a program to overload the minus operator so that it can be used to subtract one substring
from a main string

Eg: ms = “India is my country”

Ss = “is”

Ms-ss should produce “India my country”

Inheritance:
Data base – Used to store information in structured manner.

File – To store information permanently

Folder – Logical arrangement of files

File = open(‘swap.py’)

If the file “swap.py” is in the same path in which the program is saved

Print(file.read())

Print function will print all the coding in the file swap.py in command prompt
Below are used for exception handling

Try

Except

Else

Finally
Search for python 3 math module to see the list of all maths functions
All topics

Variable is a named memory location get from RAM

Name given to the variable is called identifier


Print is like over loading method. Will take any no. of arguments we give
While – Not having any no. of iterations

For – if we know no. of iterations prior to the execution of program


There shouldn’t be any loop control structures in recursive functions
Lambda used mostly in cloud programming
A, w both will create a new file if doesn’t exist

W – if exists then entire data is cleared and the new data is added

A – if exists then the new data will be appended at the end

You might also like