-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic.py
462 lines (327 loc) · 10 KB
/
basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# hello world
print("Hello World!!")
# simple math work
a = 1
b = 2
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a // b)
# function
def func1():
number = 0
number += 1
print('Name' + str(number))
func1()
func1()
func1()
print("Function called 3 times.")
# length of word
message = "hello world"
print(len(message))
print(message[2:5])
# lower case - upper case
print(message.lower()) # to convert the string into lower case
print(message.upper()) # to convert the string into the upper case
print(message.count('l')) # how many times that word or letter being used
print(message.find('world')) # if the word is available then it returns the index of the words
print(message.find('hero')) # otherwise it returns the -1 value
print(message.replace('world', 'Meet'))
name = 'Meet'
greetings = 'Hello'
wel_message = f'{greetings}, {name}. Welcome!'
print(wel_message)
# type of the variable
num = 3
print(type(num))
num1 = 2.34
print(type(num1))
# arithmetic operation
m1 = 5
m2 = 10
print(m1 + m2) # addition
print(m1 - m2) # subtraction
print(m1 * m2) # multiplication
print(m1 / m2) # division
print(m1 // m2) # floor division
print(m1 ** m2) # exponent
print(m1 % m2) # modulo
# absolute value
print(abs(-3))
print(abs(10.4))
# round of the value
print(round(15.5))
print(round(15484.5486616645, 2)) # round of the value at precise decimal
# comparisons
val1 = 10
val2 = 20
print(val1 > val2) # greater then
print(val1 < val2) # less than
print(val1 == val2) # equal
print(val1 != val2) # not equal
print(val1 >= val2) # greater than or equal to
print(val1 <= val2) # less than or equal to
# string addition
num_1 = '1000'
num_2 = '2000'
print(num_1 + num_2)
# type casting
# string to integer
num_1 = int(num_1)
num_2 = int(num_2)
print(num_1 + num_2)
# list :- A list in Python is a comma-separated collection of expressions enclosed in square brackets.
course = ['CSE', 'CE', 'IT', 'ECE', 'ICT']
print(course) # To print the whole list
print(course[2]) # it will return the 2nd element of the list
print(len(course)) # returns the number of element
print(course[-1]) # returns the value from the last
print(course[0:2]) # returns the interval elements
print(course[2:]) # returns the values from starting positions
print(course[:4]) # returns the elements till the end positions
print(course[::-1]) # to return the full list in reverse order
course.append('ME') # to remove the element into the list
print(course)
course.remove('IT') # to remove the element from the list
print(course)
course.insert(2, 'EE') # to insert the element in specific position
print(course)
course.pop() # delete the last element in the list
print(course)
course.reverse() # to reverse the list
print(course)
course_no = [10, 2, 3, 4, 5]
course.insert(0, course_no) # to insert the new list into the existing list from specific positions
print(course)
# to merge the two list without inbuilt functions
print(course + course_no)
# to merge the two list with inbuilt function
course.extend(course_no)
print(course)
# to sort the list elements
course_no.sort()
print(course_no)
print(sum(course_no))
print(max(course_no))
print(course.index('CSE'))
print('Arts' in course) # returns true if available in the list otherwise false
print('CSE' in course)
# Loop in Python
# for loop in python :- print the all element in the list
for item in course_no:
print(item)
for item, course_no in enumerate(course_no):
print(item, course_no)
# for assigning the index starting value to the list to iterate
for item, course in enumerate([546, 7864, 546, 543], start=20):
print(item, course)
# join function in python to join the values
cour = ['a', 'b', 'c', 'd']
course_str = ','.join(cour)
print(course_str)
# Tuple :- it is similar to List but there is one difference that List are Mutable but Tuple is immutable.
# Mutable
list_1 = ['history', 'Math', 'Physics', 'Chemistry']
list_2 = list_1
print(list_1)
print(list_2)
list_1[0] = 'Art'
print(list_1)
print(list_2)
# Immutable
tuple_1 = ('history', 'Math', 'Physics', 'Chemistry')
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# we can't add, delete or remove the values into the tuple , if we do it returns the error message
# tuple_1[0] = 'Art'
#
# print(tuple_1)
# print(tuple_2)
# Sets in Python :- writes in {}
# Sets :- it can't return the same index as we deliver to the system.
cs_course = {'DSA', 'OOPS', 'COA', 'DBMS'}
bca_course = {'WEBD', 'OOPS', 'DBMS', 'SDE'}
print(cs_course)
print('COA' in cs_course) # check the value is either in the set or not
print(cs_course.intersection(bca_course)) # intersection from 2 sets A ∩ B
print(cs_course.difference(bca_course)) # difference from 2 sets A - B
print(cs_course.union(bca_course)) # union of sets A ∪ B
# Empty Lists
empty_list = []
empty_list1 = list()
print(empty_list)
print(empty_list1)
# Empty Tuple
empty_tuple = ()
empty_tuple1 = tuple()
print(empty_tuple)
print(empty_tuple1)
# Empty Sets
empty_sets = {} # this isn't right! It's a dictionary
empty_sets1 = set()
print(empty_sets)
print(empty_sets1)
# Dictionary :- It's like hashmap.
Student = {'name': 'Meet', 'age': '20', 'Courses': ['Math', 'CSE', 'Robotics']}
print(Student) # it will print the whole Dictionary.
print(Student['name']) # in [] if we pass the required parameters then it only returns that parameter
print(Student.get('name')) # get() to get the required data from Dictionary
# it will act like an access key to getting the data from the Dictionary
# if the value is found , it returns the value otherwise it returns our message
print((Student.get('phone', 'Not Found')))
Student['phone'] = '123456789'
print((Student.get('phone', 'Not Found')))
# to update the value in the Dictionary
Student.update({'age': '21'})
print(Student)
# del function to delete the data from Dictionary
del Student['age']
print(Student)
# print the keys of the Dictionary
# and in the Dictionary the key means the parameters like name, age , phone number
print(Student.keys())
print(Student.values())
# the .values functions is responsible to returns the values of the parameter
# item function is used to get the Dictionary data with their id and data
print(Student.items())
for key in Student:
print(key)
for Key, value in Student.items():
print(Key, value)
# Conditionals and Booleans - if , else , elif
if True:
print("True Statement")
if False:
print("False Statement")
a = 1000
b = 2000
c = a % b
if c == 0:
print("number is rational")
else:
print("number is not rational")
# Comparisons:
# Equal : ==
# #Not Equal : !=
# Greater Than : >
# Less Than : <
# Greater or Equal : >=
# Less or Equals : <=
# Object Identity : is
Language = ['Python', 'Java']
if 'Python' in Language:
print('Language is Python')
elif 'Java' in Language:
print('Language is Java')
else:
print('No Match Found')
user = 'Admin'
logged_in = True
# not method
if not logged_in:
print("Please Log in")
else:
print("Welcome")
# or method
if user == 'Admin' or logged_in:
print("Admin Page")
else:
print("Bad Codes")
# and method
if user == 'Admin' and logged_in:
print("Admin Page")
else:
print("Bad Codes")
a = [1, 2, 3]
b = a
print(id(a)) # id means the storage address or any other garbage value
print(id(b))
print(id(a) == id(b))
a = [1, 2, 3, 4, 5]
# break is breaking the loop
for num in a:
if num == 3:
print("number founded!")
break
print(num)
# continue is print the message and continue the loop to iterate
for num in a:
if num == 3:
print("number founded!")
continue
print(num)
# here in this code snippet the value is assigned a character and print number and character until the last number
# last character is not print. like 5 d in this code
for num in a:
for letter in 'abcd':
print(num, letter)
for i in range(10):
print(i)
for i in range(5, 10):
i += 1
print(i)
# while loop
x = 0
while x < 10:
print(x)
x += 2
# recursion
def hello_func(n):
if n > 0:
print("hello world")
hello_func(n - 1)
hello_func(5)
def hello_function(greeting):
return '{} Function.'.format(greeting)
print((hello_function('i\'m a test')))
def sample():
return 'hello Function.'
print(sample().upper())
def student_info(*args, **kwargs):
print(args)
print(kwargs)
student_info('Math', 'Arts', name='Meet', age='20')
# Exception Handling
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("Division successful!")
finally:
print("Execution complete.")
# Handling specific exceptions
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input. Please enter a valid number.")
else:
print(f"Your number is: {num}")
finally:
print("Input handling complete.")
# File Operations
# Writing to a file
with open('sample.txt', 'w') as file:
file.write("Hello, this is a sample file.\n")
file.write("Writing some more lines.")
# Reading from a file
with open('sample.txt', 'r') as file:
contents = file.read()
print(contents)
# Appending to a file
with open('sample.txt', 'a') as file:
file.write("\nAppending a new line to the file.")
# Reading line by line
with open('sample.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # strip() removes any extra newline characters
# Handling file not found error
try:
with open('nonexistent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found!")