PYTHON
Opening:
Open the folder.
Tap on the address of the file and write cmd.
In command box write “code .”(Space in between)
This opens the file in VS code.
Saving:
Save the file with extension .py
Running and debugging in VS CODE:
In the command bar below write folder_name.program_name.py
1 INTRODUCTION
Program 1:
print("Hello World")
print("Welcome to Python")
print("I am Nithika")
Semicolon is optional.
Program 2:
#integer
age=20
#float
height=5.6
#string
name="Nithika"
#boolean
is_student=True
print("Name:",name)
print("Age:",age)
print("Height",height)
print("Is a student",is_student)
The line starting with # is comment.
Program 3:
name= input("Enter your name:")
age=input("Enter your age:")
print(name,"is ",age,"years old.")
We can take input during declaring the variable .
2 DATA TYPES, CONTROL VRIABLES
2.1 DATATYPE:
Program 4:
#integer(int)
age=25;
print(age,type(age))
#string(str)
name="nithika";
print(name,type(name))
#float
height=155.56;
print(height,type(height))
#complex
z=3+5j;
print(z,type(z))
#boolean(bool)
is_true=True;
print(is_true,type(is_true))
#list
fruit=["apple","banana","mango","mango"];
print(fruit,type(fruit))
#tuple
weekdays=("mon","tue","wed","thr","fri");
print(weekdays,type(weekdays));
#set
unique={1,2,3,3,2}
print(unique,type(unique))
#range
numbers=range(1,6)
print(list(numbers),type(numbers))
#dictionary
student={"name":"ravi","age":21,"grade":"a"}
print(student,type(student))
1)Integer
2)String: Every word in program other than variables and keywords
need to be in double quote(including the input).
3)Float
4)Boolean:
Gives true or false
Output must and should be True or False.
5)List:
List of items- Organized , Can contain duplicate , Changeable
Should and must have [] bracket.
6)Tuple:
List of items that-cannot be changed , organized
Should and must have () bracket.
7)Set:
Contains a set of unique values(no duplicates allowed)
If any value is present more than once it gets cancelled.
Should have {} bracket.
8)Range:
Gives range of values within the specified range
If Input is number=range(1,6) with print( number),then output is
range(1,6)
If Input is number=range(1,6) with print( list(number)),then
output is 1,2,3,4,5.
9)Dictionary:
Key:Value
TYPE:Is a function that returns the datatype of the variable. Output
will be like: <class,’int’>
2.2 BASIC FUNCTIONS
Program 5:
print("Hello world");
print(10+20);
name=input("Enter a name");
print("Hello ",name);
Program 6:
2.3 BINARY OPERATORS
2.3.1 Arithmetic operators
a=10;b=5
print("Addition",a+b);
print("Subtraction",a-b);
print("Multiply",a*b)
print("Division",a/b);
print("Modulus",a%b);
print("Floor division",a//b);
print("Power",a**b)
2.3.2 Comparison Operator
print(a>b);
print(a<b);
print(a==b);
print(a!=b);
Gives output as true or false.
In ths case(a=10,b=5) =>True,False,False,True
2.3.3 Logical operator
age=18
has_id=True;
print(age>=18 and has_id);
print(age>=18 or has_id);
print(age<18 and has_id);
print(age<18 or has_id);
print(not has_id);
2.3.4 Assignment Operator
c=5
c+=5;
print(c);
2.3.5 Bitwise operator
print(x&y);
print(x|y);
print(x^y);
print(x>>y);
print(x<<y);
Program 6:
x=int(input("Enter First number"))
y=int(input("Enter Second Number"));
print("Addition",x+y);
3 LOOPS
Program 7:
i=int(input("Enter the numver"));
if i>=10:
print("The Number is greater than 10");
while i<=10:
print(i);
i+=1
Indentation matters in python. The content in loop is decided by the
indentation. Standard is 4 space (in VS code, pressing tab will
automatically give that).
The format of condition needs to be noted. There are no brackets just
“:”.
FILE HANDLING
File Handling means opening, reading, writing and closing a file.
To create a text file in VS Code.
New File ->save it as [Link]
3.1
3.2 1)OPENING A FILE
Use open().
File=open(“[Link]”,”r”)
1.1 TYPES OF FILE MODE:
i) Read mode “r”
ii) Write mode “w”
iii) Append mode “a”
iv) Read and write mode “r+”
Program 1:
s=open('[Link]', 'r');
print([Link]());
[Link]();
s=open('[Link]', 'w');
[Link]("Bye Bye")
[Link];
s=open('[Link]', 'a');
[Link](" Don't Come back");
[Link];
#In append mode, [Link]() is used to append.
EXCEPTION HANDLING
Exceptions are the errors that are generated in the code. Exception
Handling involves detecting, raising and handling.
Exception Typical Trigger Example Situation
Accessing a list element outside its my_list[5] when list has only 3
IndexError
range. items.
Looking up a missing key in a my_dict['missing'] when key isn’t
KeyError
dictionary. present.
Performing an operation on
TypeError Adding a string to an integer.
incompatible types.
Passing an argument of correct type int('abc') – string cannot be
ValueError
but inappropriate value. converted to int.
ZeroDivisionError Dividing any number by zero. 10 / 0.
FileNotFoundError Trying to open a non-existent file. open('[Link]').
The following are used in Exception Handling:
1)try(): Write the code that you think will have an error in this block.
2)Except(): If there is an error in the Try block, then content from the
except() block is printed.
3)Else(): Else if there is no Error, then the content from the else() block
is printed.
4)Finally():This will be executed anyways, even if the try() block is
executed or not. This is like closing the file.
file = open("[Link]")
try:
data = [Link]()
x = 10 / 0
except:
print("Error happened")
else:
print("Successful")
finally:
[Link]() # ALWAYS runs
NUMPY
1 INTRODUCTION
NumPy (Numerical Python) is a fundamental library used to perform
Mathematical operations in Python, such as array, matrix, or scientific
calculations.
.np is extension used.
2 INSTALLATION
Install using pip install numpy in terminal.
Importing: import numpy as np