0% found this document useful (0 votes)
47 views

Python Notes

1) The document introduces Python programming language. It discusses that Python is an easy to learn object-oriented language with English-like syntax. 2) It explains basic Python concepts like print function, variables, data types, operators, arrays and condition statements. Functions like print() are used to output text, input() takes user input, and variables are used to store values. 3) Common data types in Python include integers, floats, strings, and booleans. Operators allow performing operations and comparisons. Arrays like lists, dictionaries, tuples and sets are used to store collections of data. 4) Condition statements like if, elif, and else allow running code conditionally based on boolean expressions

Uploaded by

Yashika Sengar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Python Notes

1) The document introduces Python programming language. It discusses that Python is an easy to learn object-oriented language with English-like syntax. 2) It explains basic Python concepts like print function, variables, data types, operators, arrays and condition statements. Functions like print() are used to output text, input() takes user input, and variables are used to store values. 3) Common data types in Python include integers, floats, strings, and booleans. Operators allow performing operations and comparisons. Arrays like lists, dictionaries, tuples and sets are used to store collections of data. 4) Condition statements like if, elif, and else allow running code conditionally based on boolean expressions

Uploaded by

Yashika Sengar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Create by Aditya

1)Introduction to Python

Python is a powerfull object oriented programming language. It is easier than other


programming languages because it have low syntax and similar meaning as English. So it is
easy to learn.In every language there are keywords which are reserved words and are used
to add more functionality to code.python has 33 keywords.

2)Print and Input function and Variables


To learn print function you should learn that what is Console. Console is the area in which
the output comes. Which means if you code anything the output will comes only in the
Console.

Print function is used to write anything in the console . We should write the thing which we
want to show in console in print function as attribute.

Syntax:

print(thing)

Example:

print("Hello World")
Create by Aditya

Output:

Hello World

Variables are names to which the value are assigned. Later this variable is called to perform
various functions. Variables can any of the alphabets and numbers.A Variable cannot be
without alphabets.

Example:

number=3
print(number)

Output:

Input function is used to take input from the user. For example if you search anything on
any search engine you should type the information .That information is the input which is
taken by you to the search engine. Now search engine will evaluate this information or
search this information to match it with any article on any website.In python in input function
we give the message to the user to what to write and store the information in a variable.

example:

name=input("Enter your name :")


print(f"Your name is {name}")

Output:

Enter your name :Aditya


Your name is Aditya

3)Data types in Python


There are 4 data types in python.
Create by Aditya

1)Integer

Integer is the data type in which Integer numbers are present which can either positive or
negative.It is written as int in code. For example 12

2)Float

Float is the data type in which decimal numbers are present.For example 12.5

3)String

String is the data type which contains alphabets,numbers,symbols and everything which is
present on keyboard.It is always written by putting colons in both ends.For example "Year
2023".

4)Boolean

Boolean contains only True and False.Where True is 1 and False is 0.

Example:

integer=23
float=23.5
string="hello"
boolean=True

print(integer)
print(float)
print(string)
print(boolean)

Output:

23
23.5
hello
True
Create by Aditya

4)Conversion of Data types


To convert one data type into another data types some functions are used which are named
as name of data type.

1)int()

It will convert any data type into integer but the data type should contain only numbers or
Boolean values.

Example:

print(int(12.4))
print(int("12"))
print(int(True))
print(int(False))

Output:

12
12
1
0

2)float()

It is used to convert any data type to decimal number but the data types contain only
numbers or Boolean values.

Example:

print(float(12))
print(float("12"))
print(float(True))
print(float(False))

Output:

12.0
12.0
Create by Aditya

1.0
0.0

3)str()

It is used to convert any value to string.It will add colons at both ends to the value which will
make it string.

Example:

print(str(12))
print(str(12.56))
print(str(True))
print(str(False))

Output:

12
12.56
True
False

4)bool()

It is used to convert any value to boolean value.If the value is a number except 0 it will
return True and if the value is 0 it will return False.If the value is string and it doesn't have
anything it will return False else True.

Example:

print(bool(12))
print(bool(0))
print(bool("hello"))
print(bool(""))

Output:

True
False
True
False
Create by Aditya

5)Operators
Operators are used to operate conditions.For example if the time is 12o clock it will sleep
otherwise not.So i will use operators to tell computer the condition.

There are main 6 operators to handle logic.

1)Arithmetic operators

Arithmetic operators are used to perform mathematical operations it have the same symbols
like we have in maths.Some common are + , - ,/ and *. We use * in place of × in
programming.
Others:

1)//

It will divide and convert the answer into integer. Which means it will remove all the
numbers after the decimal point.

2)**

used to raise power.

3)%

it gives the remainder after dividing numbers.

Example:

a=15
b=4
print(a//b)
print(a**b)
print(a%b)

Output:
Create by Aditya

3
50625
3

2)Assignment operators

This operator is used to a sign the value to a variable.

1)=

It assigns value to a variable.

2)+=

It adds a value to a variable

3)-=

It subtracts a value to a variable.

4)/=

It divides a variable by a value.

5)*=

It multiplies a variable by a value.

6)//=

It divides and assign value without decimal point to a variable.

7)**=

It raise the variable by a power.

8)%=
Create by Aditya

It divides and assign value of remainder.

Example:

x=1
print(x)
x+=2
print(x)
x-=1
print(x)
x/=2
print(x)
x*=23
print(x)
x//=2
print(x)
x**=3
print(x)
x%=2
print(x)

Output:

1
3
2
1.0
23.0
11.0
1331.0
1.0

3)comparison operators

It is used to compare values. It always returns boolean values. In conditions the both side of
operators are called operands.

1)==

It gives true if the left operand is equal to right operand.


Create by Aditya

2)!=

It gives true if the left operand is not equal to right operand.

3)>

It gives true if the left operand is greater than right operand.

4)<

It gives true if the left operand is less than right operand.

5)>=

It gives true if the left operand is greater than or equal to right operand.

6)<=

It gives true if the left operand is smaller than or equal to right operand.

Example:

print(5==6)
print(5!=6)
print(6>5)
print(6<5)
print(3>=4)
print(3<=3)

Output:

False
True
True
False
False
True

4)logical operators
Create by Aditya

It is used to combine conditional statements to form a logic.

1)and

It gives true if both conditions are true.

2)or

It gives true if any of the condition is true.

3)not

It gives true if the condition is false and it gives false if the condition is true.

Example:

a=True
b=False
print(a and a)
print(a and b)
print(a or b)
print(not a)
print(not b)

Output:

True
False
True
False
True

5)Identity operators

They are used to check if two values are same or not.

1)is
Create by Aditya

It gives true if both operands are same.

2)is not

It gives true if both operands are not same.

Example:

print(5 is 7)
print(5 is not 7)

Output:

False
True

6)Membership operators

They are used to check if a value is in a sequence.

1)in

It gives true if value is present in the sequence.

2)not in

It gives true if value is not present in the sequence.

Example:

x=[3,4,9,8]
print(4 in x)
print(5 not in x)

Output:

True
True
Create by Aditya

6)Arrays-List,Dictionaries,Tuple and sets


Arrays are collection of values. They are used in case of making several variables. For
example car1,car2,car3 and so on. incident of main king many many words we should make
with several values. To call them we will use their index. Index is the position on which the
value is plotted. The value in a array is called an element. The the index of a starts with 0
from the left side of array. The negative index will call the value from the right.

1)list

List is a type of la in which the values are plotted and have Box brackets [ ] on both sides.

Example:

numbers=["one","two","three"]
print(numbers[0])
print(numbers[-1])

Output:

one
three

1)Append()

Add an element to a list.

Example:

numbers=[1,2,3]
numbers.append(4)
print(numbers)

Output:

[1,2,3,4]

2)insert()
Create by Aditya

Add an element to an particular place.

Example:

numbers=[1,3,4]
numbers.insert(1,2)
print(numbers)

Output:

[1,2,3,4]

There are many more functions try them out.

pop(). removes an element by index

remove(). removes an element by value

clear(). removes all elements of array

copy(). makes a copy of array

sum(). returns sum of array

reverse(). reverse the order of list

sort(). sorts the list.

count(). returns how many times a value is in list.

Note:not all functions are applicable on every array.

2)Dictionary

Dictionary is the array with keys and values in which the keys are called to get the values.
Just like in real life Dictionaries a word is given and in front of it the details or meaning of
that word is given. To call a value in a dictionary by its key we use the get function.

Example:

numbers={1:"one",2:"two",3:"three"}
print(numbers.get(2))

Output:
Create by Aditya

two

3)tuples

Tuples are type of array which are same as list but they are unchangable and they have
round brackets around them.

Example:

numbers=(1,2,3,4)

4)sets

Sets are type of array which are unordered, unchangeable which means once a set is
defined and you print it, it will show random elements on it . You cannot change it after you
define it. You cannot call a value in a set by it's index. The Syntax is same as list and tuples
but it have curly blackets.

Example:

numbers={"h",2,3,"y"}
print(numbers)

Output:

{'y',3,'h',2}

7)Conditions
We use condition statements when we want the computer to make decisions based on the
condition. We use if, elif and else keywords to give conditions. The conditions evaluate into
boolean values which means true and false. If the condition is True the code written in the
condition block executed otherwise not. We use conditional and logical operators here.

example:

x=12
If x%2==0:
print(x," is divisible by 2")
Create by Aditya

elif x%3==0:
print(x," is divisible by 3")

Output:

12 is divisible by 2

In the above example 12 is also divisible by 3 but it is not showing. It is because that we
have written elif condition after the if condition.We can write multiple elif conditions after if
condition but only 1 condition will be executed .if we want to run condition even when 1
condition had runned we can use if conditions after elif conditions. The else condition is
used at last because if no condition executed the else condition will execute.

example:

x=12
If x%2==0:
print(x," is even")

else:
print(x," is odd")

Output:

12 is even

Conditions plays very important role in making programs.

8)loops
Loops are used to repeat a block of code.loops plays a very important role in programming
as it reduces are efforts to write the codes several times. They are two types of loops in
python.

1)for loop

In for loop the loops runs specific times. For loop can be used with list.

Example:
Create by Aditya

for i in range(5):
print("hello")

Output:

hello
hello
hello
hello
hello

To use it with arrays we use following syntax.

Example:

numbers=["a","b","c","d","e"]
for i in numbers:
print(i)

Output:

a
b
c
d
e

Here the i represents the element of list.

When we are for looping with range the variable's value is the time the code had runned
starting from 0.
We can make the variable starts from another integer by adding one more thing in loop.

Example:

for i in range(2,5):
print(i)

Output:

2
3
4
Create by Aditya

It runs only three times because 5 - 2 is 3. We can add one more thing that will make the
variable increase more than 1.

Example:

for i in range(2,10,2):
print(i)

Output:

2
4
6
8

2)while loop

One loops runs only when the condition is True. The condition is just written after while
keyword. Until the while condition become false the loop will run.

Example:

x=1
while x<=5:
print(x)
x+=1

Output:

1
2
3
4
5

There are two more keywords which are added in loops to make it more efficient.

They are break and continue.

As it names break keyword will break the loop so the loop will not be able to run further.
Create by Aditya

The continue means the loop will continue as it was .

Example:

x=0
while True:
print(x)
if x<10:
continue
else:
break

x+=1

Output:

0
1
2
3
4
5
6
7
8
9

These keywords are applicable with both for and while loops.

The loop inside a loop is called nested loop.we cannot the variable of loop and nested loop
same.

Example:

for i in range(2):
for j in range(5):
print(j)

Output:

0
1
2
Create by Aditya

3
4
0
1
2
3
4

9)Functions
Function is the block of code which runs only when it is called. We don't have to write same
code several times. To make the function we use keyword def .

Syntax:

def name():
code

name()

Example:

def hello():
print("hello")

hello()

output:

hello

We can use parameters which will help to give different results based on how we call it.
parameter can be any variable. This variable will be further use in the code of function.

Example:

def message (name):


print("Hello ",name)

message("Dinesh")
message("Geet")
Create by Aditya

Output:

Hello Dinesh
Hello Geet

We can use multiple parameters as much we want.

Example:

def message(from_name, messages,to_name):


print("To ",to_name)
print(messages)
print("From ",from_name)

message("Aditya","What are you doing?","Dinesh")

Output:

To Dinesh
What are you doing?
From Aditya

To store to result of function into variable we use the keyword return

Example:

def add(x,y):
return x+y

sum=add(2,4)
print (sum)

Output:

we can use loops and conditions in a function .

10)Object oriented programming


Sometimes we need to assign many properties to many values or variables. But we cannot
code such for 100 values or variables so oops are designed to make similar properties of
Create by Aditya

distinct objects.To make it we use classes as we know class are collection of information
and here it is collection of code which can run on any value assigned to it.To make a class
we write the keyword class followed by class name and a colon.

Example:

class greet:
pass

Here pass is used to do nothing. Pass can be used with all things in python.

we can write functions in a class to make it possible to assign properties to values.

Example:

class greet:
def morning():
print("Good morning")

greet=greet()
greet.morning()

Output:

Good morning

There are constructors in oops which allow us to use class name to assign values and call
functions . Here we will use parameters.To make a constructor we use __init__ as name of
function in class.we should write self as first parameter because it is default.

Example:

class greet:
def __init__(self,name)
self.name = name
print("Hello ",self.name)

greet("Geet")
greet("Dinesh")

Output:

Hello Geet
Create by Aditya

Hello Dinesh

In classes ,inheritance are used to make one class similar properties as another class.To do
this we write the name of first class as a parameter of another class.

Example:

class Vehicle:
def ride():
print("Riding")

class car(Vehicle):
def brake():
print("Applying brake")

honda=car()
honda.brake()
honda.ride()

Output:

Applying brake
Riding

We can inherit many classes to a class.

Example:

class Vehicle:
def ride():
print("Riding")

class ac:
def show():
print("Vehicle have ac")

class car(Vehicle,ac):
def brake():
print("Applying brake on car")

honda=car()
honda.show()
honda.ride()
honda.brake()
Create by Aditya

Output:

Vehicle have ac
Riding
Applying brake on car

In Oops abstraction is used to hide some details.it is use while writing modules.

11)modules
Modules are pre defined libraries of python in which python code is written which is used by
the user to code better. It helps to write less code with more functionality. One example
there is a math module in python which is used for performing high level mathematical
operations. Such as finding the square root of a number. To use a module in our code we
need to import it .if it is not downloaded then we should download it using terminal. in
terminal we have to write pip install then module name.

Example:

pip install tkinter

After downloading we can import the module in our code.

To import we have to write import keyword followed by module name.

Example:

import random

Now we can perform functions using modules.

Example:

import random

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

Output:

6
Create by Aditya

4
8
3
7

To use the functionality of the module we have to write the module name before the
functions name.

Example:

import random
random.randint(1,5)

We can reduce the module name using as keyword. Which will help to write less letters of
module to use the module.

Example:

import random as r

for i in range(3):
print(r.randint(1,10))

Output:

6
3
6
3
8

if you want to use a part of a module we can write from keyword followed by module name
then import and the function of the module.

Example:

from random import randint

print(randint(3,8))

Output:

7
Create by Aditya

By using this method we cannot write the module name again and again which will help us
to write less code moreover size of the python file will reduce also as it is just importing a
function of a module.

Every module have different functions we can use one module with the another module.

The explanation of module should be so long that it will take your more time than this
tutorials is taking.

but don't worry we will also launch some modules tutorials which will help you to learn the
modules in short.

12)handling errors
Sometimes our code wents wrong that's why the errors comes. When we make user
defined programs the incoming errors are mostly from the input of the user. To handle these
errors python has gives some keywords that are used to handle errors. The first keyword is
try which sees the block of code written after it is giving error or not.just after try block
eccept block is written in which the block of code is written that runs if the above code gives
error.

Example:

Age=input("Enter your age :)

try:
Age=int(Age)

except:
print("Please enter correct value")

Output:

Enter your age :three


Please enter correct value

if we did not write these try and eccept block the error will come which will force the user to
reopen the program.

There is one more keyword finally which runs even if the error comes or not.

Example:
Create by Aditya

age=input("enter your age ")


try:
age=int(age)

except:
print("Input is wrong")

finally:
print("your age is ",age)

Output:

enter your age :13


your age is 13

Trying again with wrong input

Output:

enter your age:thirteen


input is wrong
Your age is thirteen

We can raise error if some value or thing is wrong by writing raise keyword followed by type
of error for example valueerror.

Example:

age=input ("enter your age")


try:
age=int(age)

except:
raise ValueError("There should be integer")

Output:

Enter your age :three


Traceback (most recent call last):
File "<string>", line 3, in <module>
ValueError: invalid literal for int() with base 10: 'threee'
During handling of the above exception, another exception occurred:

Traceback (most recent call last):


File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in
<module>
start(fakepyfile,mainpyfile)
Create by Aditya

File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start


exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 6, in <module>
ValueError: There should be integer

By using this keywords we can reduce the errors.

You might also like