PYTHON

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

PYTHON

History:

➢ Created by Guido van Rossum.


➢ First released in 1991.
➢ Python 2.x and Python 3.x versions.

Data types

Type casting
var1="34.25"
var2="54.42"
#print(var1+var2)
print(float(var1)+float(var2))

print("\n",10*str(float(var1)+float(var2)),"\n")

Operators:

Logical Operator
Bitwise operator

# Assignment

d=7
d+=3
print("+=",d)

d-=4
print("-=",d)

d*=5
print("*=",d)

d/=8
print("/=",d)

d%=12
print("%=",d)

d//=10 # Round up the digit eg 7.6= 8


print("//=",d)

d**=4
print("**=",d) # expotional digit 7 power of 4

# Arithmatic

d=2
print("==",d)

a=3
b=5

print("+",a+b)

print("-",a-b)

print("/",a/b)

print("//",a//b)

print("**",a**b)
print("%",a%b)

print("*",a*b)

# Bitwise

p=1
q=2
print("&",p&q) #

print("~",~q)# shift the digit 1 number

print(~4)

print(3<<2)
print(4>>3)
print(1|2)

print(8&3)

print("^",2^3)

print("<<",q<<p)

print(">>",p>>q)

# Logical

x=2
y=3
z=1
print(x>y and y>z)
print(y>x or x>y)

# Identity

a=[10,20,30]
b=[10,20,30]

print(a is not b)

d=[40,50,60]
print(a is not d)
print (a is d)

# Membership

# in , not in

list1 = ["hii","hello"]
print("hii" in list1)
print("jiii" not in list1)

Built in Function:
Python comes with a wide range of built-in functions that
are readily available for use. Here are some commonly
used built-in functions in Python:
1. **`print()`**: Outputs the specified message to the console.

```python
print("Hello, Python!")
```

2. **`len()`**: Returns the length of an object (number of


items in an object).

```python
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
```

3. **`type()`**: Returns the type of an object.

```python
x = 10
data_type = type(x)
```

4. **`int()`**, **`float()`**, **`str()`**, **`list()`**, **`tuple()`**,


**`dict()`**: Convert values to integers, floats, strings,
lists, tuples, or dictionaries, respectively.

```python
x = int("123")
y = float("3.14")
z = str(42)
```

5. **`input()`**: Reads a line from the console.

```python
name = input("Enter your name: ")
```

6. **`range()`**: Generates a sequence of numbers.

```python
numbers = range(1, 6) # Generates 1, 2, 3, 4, 5
```

7. **`sum()`**: Returns the sum of all elements in an iterable.

```python
my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
```
8. **`max()`**, **`min()`**: Returns the maximum or minimum
value in an iterable.

```python
numbers = [4, 1, 7, 3, 9]
max_value = max(numbers)
min_value = min(numbers)
```

9. **`abs()`**: Returns the absolute value of a number.

```python
x = -10
absolute_value = abs(x)
```
**`sorted
10. ()`**: Returns a sorted list from the specified iterable.

```python
unsorted_list = [3, 1, 4, 1, 5, 9, 2]
sorted_list = sorted(unsorted_list)
```

11. **`enumerate()`**: Returns an enumerate object,


containing pairs of index and element.
```python
my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(index, value)
```

List

Tuple

# touples are enclose in round brackets ,parenthisi


# touple can not be updated

a = (1, 2, 5, "Rise")
b = (5, "CSE")
print(a)
print(a[0])
print(a[0:2])
print(a[1:])
print(b*2)
print(a + b)

d = (10, 20, 30, 40)


print(len(d))

print(max(d))

print(min(d))

print(sum(d))

list = [1, 2, 0, 1, "Nisha"]


print(tuple(list))

index = d.index(20)
print(index)

Dictonary:
- **Unordered Collection:** Dictionaries are an unordered
collection of items.

- **Key-Value Pairs:** Each item in a dictionary is a key-value


pair, where the key and value are separated by a colon.

- **Unique Keys:** Keys must be unique within a dictionary,


providing a reliable way to identify and retrieve
associated values.

- **Flexible Data Structure:** Dictionaries can store a


variety of data types as values, including numbers, strings,
lists, or even other dictionaries.

- **Fast Retrieval:** The key allows for efficient retrieval


of the associated value, making dictionaries a preferred
choice for tasks that involve mapping relationships.

- **Mutable:** Dictionaries are mutable, meaning you can


modify, add, or remove key-value pairs after the dictionary
is created.

Here's a simple example:

dic={'name':"ABC",'code':17,'dept':"CSE"}
print(dic['name'])

print(dic)
print(dic.keys())
print(dic.values())

new=dic.copy()
print(new)

seq=('code','dept','name')
print(dic.fromkeys(seq))

print(len(dic))
print(dic['name'])

dic['name']="DXA"
print(dic)

dic['key']='value'
print(dic)

print(dic.popitem())
print(dic)

del dic['code']
print(dic)

dic2={1:'one',2:'two'}
print(dic2)
Global Keyword:
In Python, the global keyword allows you to change a
variable value outside of its current scope. It is used to
make changes to a global variable from a local location.
The global keyword is only required for altering the
variable value and not for publishing or accessing it.
d=89
def fun1():
d=20
def fun2():
global d
d=88
print("After calling fun2()", d)
print("before calling fun2()",d)
fun2()
fun1()
print(d)

Map() :-
A map() function executes certain instructions- or
functionallity provided to it on every item of an
iterable.
The iterable could be a list, tuple, set, etc. It is worth
nothing that the output in the case of the map is abo an
iterable ie, a list it is a built-in function, so no import
statement required.
a=[1,2,3,4,5]
b=list(map((lambda x:x**3),a))
print(b)

Filter():-
"A filterci in python tests a specific wer- defined condition
for function or returns an iteable for the elements and
values that satisfy the condition or, in other words, return
true.
c=[7,8,9,1,2,3,4,5]
d=list((filter(lambda x:x in a,c)))
print(d)
Reduce():
import functools
q=["2", "4","6","8","10"]
p=functools.reduce((lambda x,y:x+y),q)
print(p)

Adavance Slicing :

The full form of slicing is a[start : end : step]. If the step is


positive (it defaults to 1 if omitted), you go in ascending
index from start up to, but excluding, end. If the step is
negative, you go in descending index from start down to, but
excluding, end

mystr="Welcometopythonprogramming"
print(len(mystr))
print(mystr[0:6])
print(mystr[11:17])
print(mystr[0:29:2])
print(mystr[0:70])

print(mystr[: :-1])
var4="pas1s"
print(var4.isalnum())
print(mystr.isalpha())

Recursion :
def fac_iterative(n):
fact=1
for i in range (n):
fact=fact*(i+1)
return fact
def factorial_recussive(n):
if n==1:
return 1
else:
return n*factorial_recussive(n-1)
number=int(input("Enter no"))
print("factorial iterative method",fac_iterative(number))
print("factorial recussive",factorial_recussive(number))

Short If
a=int(input((" Enter a number")))
b=int(input((" enter a number")))
print("A is greater") if(a>b) else print(" B is greater")

a=int(input((" Enter a number")))


print("A is even no") if (a/2==0) else print("A is odd no")

print(" Enter value")


l=input()
print("Enter value")
k=input()
def fun4(l,k):
print(int(l)-int(k))
print(int(l)-int(k))
fun4(l,k)

String Funcions
var="Good Morning"
print(var.upper())

print(var.lower())
mystr="Welcome to python programming"
print(mystr.replace("python","java"))
print(mystr.count("g"))
print(mystr.find("pro"))
print(mystr.endswith("d"))
print(mystr.split())

a=10
b=20
a,b=b,a
print(a,b)
print("a=",a,"b=",b)
a,b=b,a
print("Ater a=",a,"b=",b)

dhano=" You are very Smart"


print(dhano.upper())
print(dhano.lower())
print(dhano.replace("Smart","Dumbo"))
print(dhano.count("e"))
print(dhano.find("pro"))
print(dhano.endswith("c"))
print(dhano.split())
print(len(dhano))
print(dhano[0:4])
print(dhano[13:19])
print(dhano[0:19:3])
print(dhano[0:70])
print(dhano.isalnum())
print(dhano.isalpha())
print(dhano[: :-1])
print(dhano)
print(dhano.strip())
print(len(dhano))
print(dhano.startswith("q"))
print(dhano.rstrip())
print(dhano.endswith("t"))
print(dhano.center(300))
print(dhano.rjust(60))
print(dhano.ljust(600))
print(dhano.swapcase())
print(dhano.zfill)

Time Date Module

The datetime module supplies classes for manipulating


dates and times. While date and time arithmetic is
supported, the focus of the implementation is on efficient
attribute extraction for output formatting and
manipulation.
import time
initial =time.localtime()
print(time.asctime(initial))
init = time.time()
k=0
for k in range(20) :
print("Hello")
k+=1
time.sleep(2)
init2=time.time()
print("for loop run in",init2-init)
init3=time.time()
i=1
while (i<=20) :
print("Hello")
i+=1
init4 = time.time()
print("while loop run in",init4-init3)

With Block Handling :


In Python, the with statement is used in conjunction with file
handling to ensure that the file is properly closed after
operations are performed. It provides a clean and concise
way to manage resources, and it is particularly useful for
file handling where proper closure is important to free up
system resources.

Here's an example of using the with statement for file


handling in Python:

python
# Writing to a file using 'with' block
with open('example.txt', 'w') as file:
file.write('Hello, this is a sample text.')

# Reading from a file using 'with' block


with open('example.txt', 'r') as file:
content = file.read()
print(content)
In the example above:

1. The open() function is used to open a file. The first


argument is the file name, and the second argument is the
mode ('w' for write, 'r' for read).
2. The with statement is used to create a context in which
the file is opened and operated on.
3. Inside the with block, you can perform operations on the
file, such as reading or writing.
4. Once the operations are done, the with block is exited,
and the file is automatically closed.

This approach is beneficial because it ensures that the file


is closed properly, even if an exception occurs within the
block. It helps in avoiding common issues related to
resource management.
with open("f1.txt","w") as f:
f.write("Hello dumbo sanket but in dreams\n")
f.write("vaishu is damn harami")

with open("f1.txt","r") as f:
print(f.readlines())

You might also like