Repository navigation
Expand file tree
/
Copy pathsummary.py
More file actions
1060 lines (831 loc) · 28.4 KB
/
Copy pathsummary.py
File metadata and controls
1060 lines (831 loc) · 28.4 KB
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================================
# PYTHON LEARNING SUMMARY - All Original Code with Comments
# Author: Ritesh Chauhan
# Purpose: Complete collection of all original Python practice code
# Files: 1.py through 24.py (Original versions with explanatory comments)
# ============================================================================
print("=" * 70)
print("PYTHON COURSE - COMPLETE CODE SUMMARY")
print("=" * 70)
print()
# ============================================================================
# FILE 1: INPUT AND COMPARISON OPERATORS
# ============================================================================
print("\n--- FILE 1: Input and Comparison ---")
# Taking user input and converting to integer
a = int(input("Enter your 1st number: "))
b = int(input("Enter your 2nd number: "))
# Comparison operators demonstration
print(a == b) # Equal to - checks if both numbers are same
print(a != b) # Not equal to - checks if numbers are different
print(a >= b) # Greater than or equal to
print(a > b) # Greater than
print(a <= b) # Less than or equal to
print(a < b) # Less than
# ============================================================================
# FILE 2: STRINGS AND STRING METHODS
# ============================================================================
print("\n--- FILE 2: Strings and String Methods ---")
# String variable
str1 = "ritesh chauhan"
# String methods - modifying case
print(str1.upper()) # Convert to uppercase: RITESH CHAUHAN
print(str1.lower()) # Convert to lowercase: ritesh chauhan
print(str1.title()) # Title case: Ritesh Chauhan
print(str1.capitalize()) # Capitalize first letter: Ritesh chauhan
# String slicing - extracting parts of string
print(str1[0]) # First character: 'r'
print(str1[7]) # Character at index 7: 'c'
print(str1[0:6]) # Slice from index 0 to 5: 'ritesh'
print(str1[:6]) # Same as above: 'ritesh'
print(str1[7:]) # From index 7 to end: 'chauhan'
print(str1[7:14]) # Slice from 7 to 13: 'chauhan'
# Negative indexing - counting from end
print(str1[-7]) # 7th character from end
print(str1[-7:-1]) # Slice using negative indices
# ============================================================================
# FILE 3: CONDITIONAL STATEMENTS
# ============================================================================
print("\n--- FILE 3: Conditional Statements ---")
# Example 1: Age eligibility check
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible")
else:
print("You are not eligible")
# Example 2: Grade calculator using elif
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade A")
elif marks >= 80: # 90 > marks >= 80
print("Grade B")
elif marks >= 70: # 80 > marks >= 70
print("Grade B")
elif marks >= 60: # 70 > marks >= 60
print("Grade C")
elif marks >= 50: # 60 > marks >= 50
print("Grade D")
elif marks >= 40: # 50 > marks >= 40
print("Grade E")
else:
print("Better luck next time")
print("GiveUp")
# Storing grade in variable
if marks >= 90:
Grade = "A"
elif marks >= 80:
Grade = "B"
elif marks >= 70:
Grade = "B"
elif marks >= 60:
Grade = "C"
elif marks >= 50:
Grade = "D"
elif marks >= 40:
Grade = "E"
else:
Grade = "why you checking your grade"
print("Better luck next time")
print("GiveUp")
print("Your Grade is", Grade)
# Example 3: Nested if statements
if age >= 18:
if age <= 70: # Checking age range for driving
print("You can drive")
else:
print("Can't drive, you're old")
else:
print("Can't drive, sorry")
# Example 4: Odd or even checker
number = int(input("Enter a number: "))
if number % 2 == 0: # Modulo operator - remainder is 0 means even
print("The number", number, "is even number")
else:
print("The number", number, "is odd number")
# Example 5: Find greatest of three numbers
num1 = int(input("Enter your 1st number: "))
num2 = int(input("Enter your 2nd number: "))
num3 = int(input("Enter your 3rd number: "))
if num1 > num2 > num3:
print(num1, "is the greatest")
elif num2 > num3:
print(num2, "is the greatest")
else:
print(num3, "is the greatest")
# Example 6: Multiple of 7 checker
multiple = int(input("Enter your number: "))
check = multiple % 7 == 0 # Boolean expression
if check == True:
print("The number is multiple of 7")
else:
print("The number is not multiple of 7")
# ============================================================================
# FILE 4: LISTS AND LIST SLICING
# ============================================================================
print("\n--- FILE 4: Lists and List Slicing ---")
# Creating a list of marks
marks = [69, 66, 78, 65, 87, 89]
print(type(marks)) # <class 'list'>
print(marks) # Print entire list
print(marks[0]) # First element (index 0)
print(marks[1]) # Second element (index 1)
# List with mixed data types
student = ["Ritesh Chauhan", 21, "India"]
print(student)
# Lists are mutable - can be changed
student[0] = "Arjun" # Changing first element
print(student)
# List slicing - extracting portions
print(marks[1:4]) # Elements from index 1 to 3
print(marks[:4]) # Elements from start to index 3
print(marks[0:]) # Elements from index 0 to end
print(marks[-3:-0]) # Using negative indices
# ============================================================================
# FILE 5: LIST OPERATIONS AND METHODS
# ============================================================================
print("\n--- FILE 5: List Operations ---")
# Creating a list with duplicates
list_nums = [1, 3, 4, 5, 2, 5, 6, 6, 1]
# append() - adds element at the end
list_nums.append(10)
print(list_nums)
# sort() - arranges in ascending order
list_nums.sort()
print(list_nums)
# sort(reverse=True) - descending order
list_nums.sort(reverse=True)
print(list_nums)
# Adding more elements
list_nums.append(11)
list_nums.append(15)
print(list_nums)
# reverse() - reverses the order
list_nums.reverse()
print(list_nums)
list_nums.sort(reverse=True)
print(list_nums)
# insert(index, element) - insert at specific position
list_nums.insert(2, 0)
print(list_nums)
# remove(element) - removes first occurrence
list_nums.remove(0)
print(list_nums)
# pop(index) - removes element at index
list_nums.pop(5)
print(list_nums)
# Final sort
list_nums.sort()
print(list_nums)
# count() - counts occurrences of element
print(list_nums.count(1))
# ============================================================================
# FILE 6: TUPLES
# ============================================================================
print("\n--- FILE 6: Tuples ---")
# Creating a tuple
tup = (1, 2, 4, 3, 2, 4, 4, 1)
print(tup)
print(type(tup)) # <class 'tuple'>
# Accessing tuple elements by index
print(tup[1]) # Second element
print(tup[0]) # First element
print(tup[6]) # Seventh element
# Single element tuple - comma is important
tup1 = (1,) # Comma makes it a tuple
print(type(tup1))
# Tuple methods
print(tup.index(4)) # Find index of first occurrence of 4
print(tup.count(2)) # Count occurrences of 2
# ============================================================================
# FILE 7: USER INPUT FOR LISTS
# ============================================================================
print("\n--- FILE 7: User Input Lists ---")
# Method 1: Store inputs in variables, then create list
movie1 = input("Enter your 1st fav movie: ")
movie2 = input("Enter your second movie: ")
movie3 = input("Enter your third movie: ")
movie_list = [movie1, movie2, movie3]
print(type(movie_list))
print(movie_list)
# Method 2: Append to empty list
movies = []
movies.append(input("Enter your 1st movie: "))
movies.append(input("Enter your 2nd movie: "))
movies.append(input("Enter your 3rd movie: "))
print(movies)
# ============================================================================
# FILE 8: LIST AND TUPLE PRACTICE
# ============================================================================
print("\n--- FILE 8: List/Tuple Practice ---")
# Check if list is a palindrome
list5 = [1, 2, 3, 2, 1]
list1 = list5.copy() # Create a copy
list1.reverse() # Reverse the copy
if list5 == list1:
print("The list is palindrome")
else:
print("Not")
# Count specific grade in tuple
grade = ("A", "B", "C", "D", "A", "B", "E", "A", "B")
print(grade.count("A")) # Count how many times 'A' appears
# Sort the tuple by converting to list
list1 = list(grade) # Convert tuple to list
list1.sort() # Sort the list
print(list1)
# ============================================================================
# FILE 9: DICTIONARIES
# ============================================================================
print("\n--- FILE 9: Dictionaries ---")
# Creating a dictionary
student_dict = {
"name": "Ritesh",
"cgpa": 6.7,
"marks": [],
}
print(student_dict["name"]) # Access value by key
# Adding new key-value pair
student_dict["subject"] = "Python", "Java"
print(student_dict["subject"])
# Nested dictionary - dictionary inside dictionary
student = {
"name": "Ritesh",
"subject": {
"phy": 76,
"chem": 67,
"math": 100
}
}
print(student["subject"]) # Access nested dictionary
print(student["subject"]["phy"]) # Access nested value
# Dictionary methods
print(student.keys()) # Get all keys
print(student.values()) # Get all values
print(student.items()) # Get key-value pairs
print(len(student)) # Number of keys
# Access nested dictionary keys
print(list(student["subject"]))
print(student["subject"]["phy"])
# Converting to lists
print(list(student.keys()))
print(list(student.values()))
print(list(student.items()))
print(len(student))
# update() - add or modify keys
student.update({"city": "Bhubaneswar"})
print(student)
# ============================================================================
# FILE 10: SETS
# ============================================================================
print("\n--- FILE 10: Sets ---")
# Creating a set from list - duplicates automatically removed
num_list = [1, 1, 2, 3, 4, 4, 5, 4, 3, 2, 5, 6, 7, 8, 1, 1, 9, 10, 9, 9, 9, 10]
num_set = set(num_list)
print(type(num_set), "=", num_set)
# Convert back to list
unique_list = list(num_set)
print(type(unique_list), "=", unique_list)
# Set operations
print(num_set.pop()) # Remove and return random element
print(num_set.pop())
num_set.add(11) # Add element
print(num_set.pop())
num_set.add(22)
print(num_set.pop())
num_set.add(9)
print(num_set.pop())
num_set.add(3)
print(num_set)
# Removing multiple elements
print(num_set.pop())
print(num_set.pop())
print(num_set.pop())
print(num_set.pop())
print(num_set.pop())
print(num_set.pop())
print(num_set.pop())
# clear() - remove all elements
num_set.clear()
print(num_set)
# ============================================================================
# FILE 11: SET OPERATIONS
# ============================================================================
print("\n--- FILE 11: Set Operations ---")
# Creating two sets
set1 = {1, 2, 3, 4, 5, 6, 3, 4, 2, 5, 7, 4}
set2 = {4, 5, 4, 3, 2, 3, 8, 11, 2, 2, 3, 3, 4, 9, 10, 0}
# union() - combines all unique elements from both sets
print(set1.union(set2))
# intersection() - elements common to both sets
print(set1.intersection(set2))
# Dictionary with multiple meanings (using sets)
words = {
"table": {
"a piece of furniture",
"list of facts & figures"
},
"cat": "animals",
}
print(words)
# Dictionary with list values
word_dict = {
"table": ["a piece of furniture", "list of facts & figures"],
"cat": "animals",
}
print(word_dict)
# Practical example - count unique subjects
subjects = {"python", "java", "c++", "python", "javascript", "java", "python", "java", "c++", "c"}
print("Classroom needed:", len(subjects)) # Set removes duplicates
# ============================================================================
# FILE 12: DICTIONARY FROM INPUT
# ============================================================================
print("\n--- FILE 12: Dictionary from Input ---")
# Getting marks from user
a = int(input("Enter marks of math: "))
b = int(input("Enter marks of python: "))
c = int(input("Enter marks of javascript: "))
# Creating dictionaries
marks_dict = {} # Empty dictionary
dict1 = {
"math": a,
"python": b, # Fixed typo from original "pyhton"
"javascript": c,
}
# update() - merges dict1 into marks_dict
marks_dict.update(dict1)
print(marks_dict)
# ============================================================================
# FILE 13: WHILE LOOPS BASICS
# ============================================================================
print("\n--- FILE 13: While Loops ---")
# Example 1: Print message 5 times
count = 1
while count <= 5:
print("Hello Ritesh")
count += 1 # Increment counter
# Example 2: Another loop
i = 1
while i < 6:
print("Ok boss")
i = i + 1
# Example 3: Print numbers
a = 0
while a < 6:
print(a)
a = a + 1
# ============================================================================
# FILE 14: NUMBER SEQUENCES
# ============================================================================
print("\n--- FILE 14: Number Sequences ---")
# Counting from 1 to 100
i = 1
while i <= 100:
print(i)
i = i + 1
# Counting from 100 to 1
i = 100
while i >= 1:
print(i)
i = i - 1
# ============================================================================
# FILE 15: MULTIPLICATION TABLE
# ============================================================================
print("\n--- FILE 15: Multiplication Table ---")
# User input for table
number = int(input("Enter a number for a table: "))
table = 1
# Generate table from 1 to 10
while table <= 10:
print(number, "multiplying with", table, "=", number * table)
table += 1
# ============================================================================
# FILE 16: ITERATE LISTS WITH WHILE
# ============================================================================
print("\n--- FILE 16: Iterate Lists ---")
# List of perfect squares
square_list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print(len(square_list)) # Length of list
# Loop through list using index
i = 0
while i < len(square_list):
element = square_list[i]
print(element)
i += 1
# ============================================================================
# FILE 17: SEARCHING IN TUPLE
# ============================================================================
print("\n--- FILE 17: Searching in Tuple ---")
# Tuple of perfect squares
tuples = (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
print(tuples)
# Get search value from user
x = int(input("Enter number to search from the tuple: "))
# Linear search algorithm
b = 0
found = False
while b < len(tuples):
if tuples[b] == x:
print("Found at index", b)
found = True
break # Exit after finding - FIXED BUG
b += 1
if not found:
print("Number not found in tuple")
# ============================================================================
# FILE 18: BREAK AND CONTINUE
# ============================================================================
print("\n--- FILE 18: Break and Continue ---")
# Break example - exits loop when condition met
i = 1
while i <= 5:
print(i)
if i == 3:
break # Exit loop immediately
i += 1
print("End of loop")
# Continue example - skips rest of iteration
i = 1
while i <= 5:
if i == 3:
i += 1
continue # Skip to next iteration
print(i)
i += 1
# ============================================================================
# FILE 19: ODD AND EVEN WITH CONTINUE
# ============================================================================
print("\n--- FILE 19: Odd/Even with Continue ---")
# Print odd numbers using continue
i = 0
while i <= 10:
if i % 2 == 0: # If even
i += 1
continue # Skip printing
print(i) # Only prints odd
i += 1
# Print even numbers using continue
i = 0
while i <= 10:
if i % 2 != 0: # If odd
i += 1
continue # Skip printing
print(i) # Only prints even
i += 1
# ============================================================================
# FILE 20: FOR LOOPS WITH SETS
# ============================================================================
print("\n--- FILE 20: For Loops ---")
# Iterate through a set
num_set = {1, 2, 6, 3, 1, 44, 3, 2, 3, 44, 1, 1, 3, 3, 4, 5, 53, 44, 34}
for val in num_set: # For loop iterates through each element
print(val)
# ============================================================================
# FILE 21: INTERACTIVE TUPLE AND LIST
# ============================================================================
print("\n--- FILE 21: Interactive Input ---")
# Create tuple from user input
tup_input = input("Enter elements for tuple (comma-separated): ")
tup = tuple(tup_input.split(',')) # split() converts string to list, tuple() converts to tuple
print("Tuple elements:")
for a in tup:
print(a.strip()) # strip() removes extra spaces
# Search in tuple
search_element = input("Enter an element to find in the tuple: ").strip()
if search_element in tup: # Membership test - FIXED BUG
print("Element Found")
else:
print("Not Found")
print() # Blank line
# Create list from input
list_input = input("Enter elements for list (comma-separated): ")
num_list = list_input.split(',')
print("List elements:")
for element in num_list:
print(element.strip())
# ============================================================================
# FILE 22: RANGE FUNCTION
# ============================================================================
print("\n--- FILE 22: Range Function ---")
# range(stop) - 0 to stop-1
for i in range(10):
print(i)
print()
# range(start, stop) - start to stop-1
for i in range(2, 10):
print(i)
print()
# range(start, stop, step) - with custom increment
for i in range(1, 10, 2):
print(i)
# Even numbers 0 to 100
for i in range(0, 101, 2):
print(i)
print()
# Odd numbers 1 to 100
for i in range(1, 101, 2):
print(i)
# Counting backward (negative step)
for i in range(100, 0, -1):
print(i)
# Multiplication table using range
table_num = int(input("Enter a number for table: "))
for i in range(1, 11):
print(table_num * i)
# ============================================================================
# FILE 23: FACTORIAL CALCULATION
# ============================================================================
print("\n--- FILE 23: Factorial ---")
# Calculate factorial using while loop
n = int(input("Enter a number for factorial: "))
factorial = 1 # Start with 1 (not 0)
i = 1
while i <= n:
factorial = factorial * i # Multiply each number
i += 1
print(factorial)
# ============================================================================
# FILE 24: PATTERN PRINTING
# ============================================================================
print("\n--- FILE 24: Pattern Printing ---")
# Pattern 1: Right triangle
a = 5
for b in range(a):
print("*" * b) # Print b stars
# Pattern 2: With spaces
c = 5
for d in range(c):
print(" " * c, "*" * d)
c -= 1 # Decrease c in each iteration
# Pattern 3: Pyramid (centered)
num = 5
for i in range(num):
print(" " * (num - i), (2 * i - 1) * "*")
# ============================================================================
# FILE 25: FUNCTIONS - BUILDING BLOCKS
# ============================================================================
print("\n--- FILE 25: Functions - Building Blocks ---")
# Function to add two numbers
def add(a, b):
sum = a + b
print(sum)
return sum
add(15, 5)
add(1, 2)
# Simple function with no parameters
def ritesh():
print("Hello from function!")
ritesh()
# Function to calculate average
def avg(a, b, c):
avg = (a + b + c) / 3
print(avg)
return avg
avg(5, 5, 5)
# ============================================================================
# FILE 26: FUNCTIONS - PRACTICAL APPLICATIONS
# ============================================================================
print("\n--- FILE 26: Functions - Practical Applications ---")
# Function to print length of a list
list1 = [1, 2, 3, 4, 5, 6]
list2 = ["abc", "def", "ghi"]
def print_len_list(list):
print(len(list))
print_len_list(list1)
print_len_list(list2)
# Function to print elements in a single line
def print_listsl(list):
for items in list:
print(items, end=" ")
print_listsl(list1)
print_listsl(list2)
print()
# Function to calculate factorial
def fact(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(factorial)
fact(10)
fact(5)
fact(6)
# Function to convert USD to INR
def convert(usd):
inr = usd * 83
print("Rs : ", inr)
convert(10)
# Function to check odd or even
def numberOddEven(number):
if (number % 2 == 0):
print("Even")
else:
print("Odd")
# numberOddEven(number=int(input("Enter Your Number : "))) # Commented to avoid input in summary
# ============================================================================
# FILE 27: RECURSION
# ============================================================================
print("\n--- FILE 27: Recursion ---")
# Recursive function to calculate sum of first n natural numbers
def sum(n):
if (n == 0):
return 0
return sum(n - 1) + n
print(sum(5))
# Recursive function to print list elements
def printlist(list, index=0):
if (index == len(list)):
return
print(list[index])
printlist(list, index + 1)
cities = ["brj", "ktm", "pkhr", "jnk"]
printlist(cities)
# ============================================================================
# FILE 28: FILE I/O - READING AND WRITING FILES
# ============================================================================
print("\n--- FILE 28: File I/O - Reading and Writing ---")
# Create and write to a file
with open("pratice.txt", "w+") as f:
f.write(" hi everyone\n we are learning file i/o\n using java\n i like programming in java")
# Read the file
with open("pratice.txt", "r") as f:
data = f.read()
print(data)
# Replace text in file
new_data = data.replace("java", "Python")
print(new_data)
# Write modified data back
with open("pratice.txt", "w") as f:
f.write(new_data)
# Search for a word in file
word = "learning"
with open("pratice.txt", "r") as f:
data = f.read()
if (data.find(word) != -1):
print("found")
else:
print("not found")
# ============================================================================
# FILE 29: FILE I/O - ADVANCED OPERATIONS
# ============================================================================
print("\n--- FILE 29: File I/O - Line Search ---")
# Function to find line number where word appears
def check_for_line():
word = "learning"
data = True
line_no = 1
with open("pratice.txt", "r") as f:
while data:
data = f.readline()
if (word in data):
print(line_no)
return line_no
line_no += 1
return -1
print(check_for_line())
# ============================================================================
# FILE 30: FILE I/O - PROCESSING CSV DATA
# ============================================================================
print("\n--- FILE 30: File I/O - CSV Processing ---")
# Create file with comma-separated numbers
with open("pratice1.txt", "w") as f:
f.write("1,2,3,4,5,6,7,8,99,11,12,13,23,24,35,354,646,5,57,345,32323,523,5,235")
# Read and process CSV data
with open("pratice1.txt", "r") as f:
data = f.read()
# Split by comma
new_data = data.split(",")
print(new_data)
# Convert to integers
new_data1 = []
for item in new_data:
a = int(item)
new_data1.append(a)
print(new_data1)
# Separate even and odd numbers
even = []
odd = []
for item in new_data1:
if (item % 2 == 0):
even.append(item)
else:
odd.append(item)
print("Even:", even)
print("Odd:", odd)
# ============================================================================
# FILE 31: OOP - CLASSES AND OBJECTS
# ============================================================================
print("\n--- FILE 31: OOP - Student Class ---")
# Student class with average calculation
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def avrage(self):
avg = 0
for val in self.marks:
avg += val
avrag = avg / 3
print("Hi ", self.name, "Your avg marks is : ", avrag)
s1 = Student("Ritesh", [60, 50, 80])
s1.avrage()
# ============================================================================
# FILE 32: OOP - BANK ACCOUNT CLASS
# ============================================================================
print("\n--- FILE 32: OOP - Account Class ---")
# Account class with debit and credit methods
class Acount:
def __init__(self, bal, acc):
self.balance = bal
self.account_no = acc
def debit(self, amount):
self.balance -= amount
print("Rs", amount, "Debited From Acc -", self.account_no,
"Your Total Balance is :", self.get_balance())
def credit(self, amount):
self.balance += amount
print("Rs", amount, "Credited To Acc -", self.account_no,
"Your Total Balance is :", self.get_balance())
def get_balance(self):
return self.balance
acc1 = Acount(10000, 12122001100210005645)
print(acc1.balance)
print(acc1.account_no)
acc1.debit(500)
acc1.credit(100)
acc1.credit(500)
# ============================================================================
# FILE 33: OOP - OPERATOR OVERLOADING (POLYMORPHISM)
# ============================================================================
print("\n--- FILE 33: OOP - Operator Overloading ---")
# Complex number class with operator overloading
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def shownumber(self):
print(self.real, "i +", self.imag, "j")
def __add__(self, num2):
newr = self.real + num2.real
newi = self.imag + num2.imag
return Complex(newr, newi)
num1 = Complex(2, 3)
num1.shownumber()
num2 = Complex(3, 4)
num2.shownumber()
num3 = num1 + num2
num3.shownumber()
# ============================================================================
# FILE 34: OOP - CIRCLE CLASS
# ============================================================================
print("\n--- FILE 34: OOP - Circle Class ---")
# Circle class with area and perimeter
class Circe:
def __init__(self, r):
self.radius = r
def area(self):