1.
base
message= “hello world”
print(message)
print(len(message))
print(message[0])
print(message[0:5])
print (message[6:])
print([Link]())
print([Link]())
print([Link](‘l’))
print([Link](‘w’)
message=[Link](‘world’ , ‘universe’)
print([Link]())
print(S[-1])
>
<
>=
<=
==
!=
and
or
Not
\n to break line. In vertical sequence , add it in bw
.capatalize
print([Link](“Python”, “Javascript”)
print([Link](“xxx”))
print([Link](“$”))
2.
greeting= “hello”
name= “michael”
message= greeting + ‘ ’ + name
message2= ‘{ }, { }. Welcome!’ .format(greeting,name)
print(message)
message= f’{greeting}, {[Link]()} . welcome!’
print(dir(name))]
print(help(str))
print(help([Link]))
Use isalpha(), isdigit(), and isspace(
3.
num=3
print(type(num))
num=3.14
print(type(num)
print(abs(-3))
print(round(3.75))
4.
Equal ==
Not equal !=
num1=1
num2=2
print(num1==num2)
Print (num1!=num2)
w
5.
num1=”1”
num2=”2”
num1= int(num1)
num2=int(num2)
print(num1+ num2)
6. list Prefer ‘ over ”
courses= [‘maths’, ‘physics’, ‘chem’ ,’ Bio’]
print(courses)
print(len(courses))
print(courses[0]))
print(courses[2])
print(courses[-1])
print(courses[0:2])
[Link]('art')
[Link](0 ,'art')
[Link](0,courses2)
[Link](courses2)
[Link](‘math’)
[Link](1)
popped=[Link]()
print("the popped course is" ,popped)
[Link]()
[Link]()
[Link](reverse=True) *(T capital)
print([Link](‘chem’))
print(‘math’ in courses)
print(courses)
courses= ['maths', 'physics', 'chem' ,'Bio']
for index, course in enumerate(courses):
print(index, course)
courses= ['maths', 'physics', 'chem' ,'Bio']
courses_str = ', '.join(courses)
print(courses_str)
courses= ['maths', 'physics', 'chem' ,'Bio']
courses_str = '- '.join(courses)
print(courses_str)
[Link]()
[Link](reverse=True)
[Link]()
[Link](index,el)
print(" ".join(result))
7.
nums = [1, 5, 2, 4, 3]
print(min(nums))
print(max(nums))
print(sum(nums))
8. Sets
c = {'kkj', 'pnc', 'csk,' }
print(c)
c = {'kkj', 'pnc', 'csk',}
d = {'mi' , 'pnc', 'kkj'}
print('kkj' in c )
print('rcb' in c)
print(c)
print([Link](c))
print([Link](d))
9. Dictionaries
student={'name': 'KKJ', 'age':'25', 'course': ['CSE', 'Maths']}
print(student['course'])
print(student)
student['phone'] = '999-888-7714'
print([Link]('phone', 'not found'))
[Link]({'age': '18', 'phone':'9220923433'})
print( student)
[Link]['age']
print(student)
print([Link]())
print([Link]())
print(len(student))
print([Link]())
[Link]({'age':'134'})
for key, value in [Link]():
print(key,value)
[Link](key)
[Link](values)
[Link]()
9. CONDITIONALS AND BOOLEENS
A)
a=input('Enter Your Language(in Block Letters):')
if a== 'PYTHON':
print('Go to section 78')
if a== 'JAVA':
print('Language is "JAVA"')
else:
print(' go to sector 62')
B)
user= "admin"
logged_in = False
if not logged_in:
print('Please Log In')
else:
print('welcome')
C)
a=[1,2,3]
b=[1,2,3]
print(id(a))
print(id(b))
10.
A)
num = [1,2,3,4,5]
for num in nums:
print(num)
B) nums = [1,2,3,4,5]
for num in nums:
if num== 4:
print('FOUND!')
break
print(num)
C)
nums = [1,2,3,4,5]
for num in nums:
if num== 4:
print('FOUND!')
continue
print(num)
D) nums=[1,2,3,4,5]
for num in nums:
for letter in 'abc':
print(num, letter)
E)
for i in range(1,11):
print(i)
F)
x=0
while x<10:
print(x)
x +=1
G)
x=0
while True:
if x == 5:
break
print(x)
x+=1
H)for i in range(5):
mark = int(input(f"Enter marks in subject-{i+1}: "))
[Link](mark)
H)
items = [] while True: item = input("Enter item: ") if [Link]() == "done": break
[Link](item)
11) functions
A)
def hello_func():
print('Hello Function!')
hello_func()
hello_func()
B)
def hello_func():
return 'hello Function'
print(hello_func())
print(hello_func().upper)
C) def hello_func(greeting):
return '{} '.format(greeting)
print(hello_func('Hi'))
D)
def hello_func(greeting, name):
return '{},{}'.format(greeting, name)
print(hello_func('Hi', name = 'corey'))
E)
def student_info(*args, **kwargs):
print(args)
print(kwargs)
courses = ['Math', 'Art']
info = {'name':'John', 'age': '22'}
student_info(*courses, **info)
F)n = []
for i in range(1,6):
num = int(input(f"ENTER A NUMBER-{i}:"))
[Link](num)
odd = 0
even = 0
for num in n:
if num % 2 == 0:
even += 1
else:
odd += 1
x=0
for num in n :
if num >50:
x += 1
average = sum(n)/len(n)
print(n)
print(sum(n))
print(even)
print(odd)
print(x)
print(average)
F)
#contact book
store = [ {'name':'RCB', 'phone':'049'},
{'name':'GT', 'phone':'003'},
{'name':'RR', 'phone':'014'},
{'name': 'SRH', 'phone':'016'}
]
print("-------MENU-----")
print("1. Add")
print("2. Search")
print("3. View All")
print("4. Exit")
while True:
choice = int(input("Enter your choice number:"))
if choice == 1:
name = (input("Enter the name:"))
phone = int(input("Enter the phone no.:"))
dic = {'name':name, 'phone':phone}
[Link](dic)
print(store)
print("Contact Added")
if choice == 2:
search_name = input("Enter the name: ")
for contact in store:
if contact["name"] == search_name:
print("Phone no. is:", contact["phone"])
if choice == 3:
print(store)
if choice == 4:
print("Exit")
break
Extra-
1)n = int(input("Enter the number:"))
for i in range(1,11):
table = n * i
print(table)
for i in range(n, 0, -1):
print("If You type 'STOP' then addition of numbers in list would stop. ")
nums = []
while True:
num = (input("Enter the number in list:"))
if num == "STOP":
break
try:
num = int(num)
[Link]((num))
except ValueError:
print("Please enter a valid number.")
positive = 0
for num in nums:
if int(num) > 0:
positive += 1
print(int(positive))
print("No. of numbers in list are",len((nums)))
2)
student = {}
print("add student; write 'yes' to continue; write 'no' to exit. ")
while True:
i = input("Enter yes or no:")
if i == "yes":
n = input("Enter the name:")
marks = []
s1 = int(input("Enter score in phy:"))
[Link](s1)
s2 = int(input("Enter score in maths:"))
[Link](s2)
s3 = int(input("Enter score in chem:"))
[Link](s3)
average = sum(marks)/3
[Link](average)
[Link]({n:marks})
print("average:",average)
print(student)
if i == "no":
print("exiting")
Break
3)
word1 = input("Enter the first word: ").lower()
word2 = input("Enter the second word: ").lower()
if sorted(word1) == sorted(word2):
print("Anagrams")
else:
print("Not anagrams")
4)
dict = {"a":1, "b":2, "c":3}
inverted = {value: key for key, value in [Link]()}
print(inverted)
Lengend
sen = input("Enter the sentance:")
a = [Link]()
freq = {}
for b in a:
if b in freq:
freq[b] += 1
else:
freq[b] = 1
shortest = a[0]
for word in a:
if len(word) < len(shortest):
shortest = word
longest = a[0]
for word in a:
if len(word) > len(longest):
longest = word
print(freq[longest])
print(freq)
print(len(freq))
print(len(sen))
print(longest)
print(shortest)
6)word[::-1]
means:
● Start from the end.
● Move backwards one character at a time.
● Return the reversed string.
for word in words:
rev = ""
for ch in word:
rev = ch + rev
print(rev, end=" ")
12)Math
1)import math
print("------this system Calculates value of logx where y is the base.-------")
Y = float(input("enter Y:"))
X = float(input("enter X:"))
print([Link](X,Y))
2)import math
rads = [Link](90)
print(rads)
3)import math
rads = [Link](90)
print([Link](rads))
4)
import datetime
import calendar
today = [Link]()
print([Link](2017))
5)import os
print([Link]())
print(os.__file__)
6)import antigravity
import inspect
7)[Link]()
# Method A: Print the exact file path on your computer
print([Link](antigravity))
# Method B: Print the actual code on your screen
print([Link](antigravity))
5) transpose = list(zip(*matrix))
13) OS
1) import os
print(dir(os))
print([Link]())
[Link](r'\Users\DELL\OneDrive\Desktop\code')
print([Link]())
2)
import os
[Link](r'\Users\DELL\OneDrive\Desktop\code')
[Link]('OS-Demo-3/Sub-dir-1')
[Link]('OS-Demo-3/sub-dir-1')
print([Link]())
3)
import os
[Link](r'\Users\DELL\OneDrive\Desktop\code')
[Link]('OS-Demo-2/Sub-dir-1')
[Link]('OS-Demo-2/sub-dir-1')
print([Link]())
4)
import os
[Link](r'\Users\DELL\OneDrive\Desktop\code')
os. rename(‘[Link]’, ‘[Link])
print([Link]())’
5)
import os
from datetime import datetime
[Link](r'C:\Users\DELL\OneDrive\Desktop\code')
mod_time = [Link]('[Link]').st_mtime
print([Link](mod_time))
14) Reading Files
1)
f = open('[Link]', 'r')
print([Link])
print([Link])
[Link]()
2)with open('[Link]', 'r') as f:{or f = open('[Link]', 'r')}
f_contents = [Link]()
print(f_contents)
3)f = open('[Link]', 'r')
f_contents = [Link]()
print(f_contents)
4)f = open('[Link]', 'r')
f_contents = [Link]()
print(f_contents)
5)for line in f:
print(line, end ='')
6)f = open('[Link]', 'r')
size_to_read = 8
f_contents = [Link](size_to_read)
print(f_contents)
7)
f = open('[Link]', 'r')
size_to_read = 7
f_contents = [Link](size_to_read)
print(f_contents,end='')
while len(f_contents) > 0:
print(f_contents,end='*')
f_contents = [Link](size_to_read)
8) print([Link]())
9)f = open('[Link]', 'r')
size_to_read = 7
f_contents = [Link](size_to_read)
print(f_contents, end='')
[Link](0)
f_contents = [Link](size_to_read)
print(f_contents)
10)
f = open("[Link]", "w")
[Link]("djehu ed ejk cer cruch r")
[Link]("\nasdffgrg")
[Link]()
11)
f = open("[Link]", "r+")
[Link]("djehu ed ejk cer cruch r")
[Link]("\nasdffgrg")
print([Link]())
[Link]()
12)
f = open("[Link]", "a+")
[Link]("djehu ed ejk cer cruch r")
[Link]("\nasdffgrg")
print([Link]())
[Link]()
13) if([Link]())
14)def check_word():
print("write '0X0' to stop this function")
while True:
a = input("Enter the word:")
word = a
if a == "0X0":
break
f = open("[Link]", "r")
data = [Link]()
if([Link](word) !=-1):
print("Found")
else:
print("not found")
check_word()
write() → writes one string.
writelines() → writes a list of strings.
read() → returns one string.
readlines() → returns a list of strings.
MEANINGS
x - create new file and open it to write
a- open for writing
b- binary mode
t-text mode
+ Open a disk file to update
10)
Data = f. read()
OOPS
class Student:
def __init__(self):
[Link] = input("Enter name of student: ")
marks = []
for i in range(1, 4):
m = int(input(f"Enter marks in subject-{i}: "))
[Link](m)
[Link] = sum(marks) / len(marks)
print("Name:", [Link])
print("Average:", [Link])
For private self.__acc_pass = acc_pass
Inhertance- @staticmethod
s1 = Student()
2)
class car:
def __init__(self, type):
[Link] = type
@staticmethod
def car_start():
print("car started")
@staticmethod
def car_stop():
print("car stopped")
class toyotacar(car):
def __init__(self, name, type):
super(). __init__(type)
[Link] = name
car1 = toyotacar("SAM","NUK")
print([Link])
3)
class complex:
def __init__(self, real, img):
[Link] = real
[Link] = img
def shownumber(self):
print([Link], "i", [Link], "j")
def add(self, num2):
newreal = [Link] + [Link]
newimg = [Link] + [Link]
return complex(newreal, newimg)
num1 = complex(1,3)
[Link]()
num2 = complex(2,6)
[Link]()
num3 = [Link](num2)
[Link]()