-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMostCommonPythonCodes.py
292 lines (231 loc) · 7.96 KB
/
MostCommonPythonCodes.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
# ----------------------------------------------------------------------
# Reading and Writing Files:
# Reading a file
with open('file.txt', 'r') as file:
content = file.read()
# Writing to a file
with open('file.txt', 'w') as file:
file.write('New content')
# ----------------------------------------------------------------------
iterable =[]
#for Loop:
for item in iterable:
# Code to be executed
pass
# ----------------------------------------------------------------------
condition = True
# if Statement:
if condition:
# Code to be executed if the condition is true
pass
# ----------------------------------------------------------------------
# Defining a Function:
def my_function(parameter1, parameter2):
# Function code
return result
# ----------------------------------------------------------------------
# Using Lists:
my_list = [1, 2, 3, 4, 5]
# ----------------------------------------------------------------------
#Using Dictionaries:
my_dict = {'key1': 'value1', 'key2': 'value2'}
# ----------------------------------------------------------------------
# while Loop:
while condition:
# Code to be executed
pass
# ----------------------------------------------------------------------
#Using Standard Modules:
import math
result = math.sqrt(16)
# ----------------------------------------------------------------------
# List Comprehension:
squares = [x**2 for x in range(10)]
# ----------------------------------------------------------------------
# Exception Handling:
try:
# Code that may raise an exception
pass
except Exception as e:
# Handling the exception
pass
# ----------------------------------------------------------------------
# Working with Strings:
my_string = "Hello, World!"
# ----------------------------------------------------------------------
# Using Sets:
my_set = {1, 2, 3}
# ----------------------------------------------------------------------
# Using Tuples:
my_tuple = (1, 2, 3)
# ----------------------------------------------------------------------
# Getting User Input:
user_input = input("Enter something: ")
# ----------------------------------------------------------------------
# Converting Data Types:
number = int("42")
# ----------------------------------------------------------------------
# Finding the Length of a List:
length = len(my_list)
# ----------------------------------------------------------------------
# Sorting a List:
sorted_list = sorted(my_list)
# ----------------------------------------------------------------------
# Appending to a List:
my_list.append(6)
# ----------------------------------------------------------------------
# Removing an Item from a List:
my_list.remove(3)
# ----------------------------------------------------------------------
# Checking Membership in a List:
if item in my_list:
# Code to handle membership
pass
# ----------------------------------------------------------------------
# Creating a Dictionary:
my_dict = dict(key1='value1', key2='value2')
# ----------------------------------------------------------------------
# Accessing Dictionary Values:
value = my_dict['key1']
# ----------------------------------------------------------------------
# Updating Dictionary Values:
my_dict['key1'] = 'new_value'
# ----------------------------------------------------------------------
# Deleting Dictionary Items:
del my_dict['key1']
# ----------------------------------------------------------------------
# Checking Dictionary Keys:
if 'key1' in my_dict:
# Code to handle key existence
pass
# ----------------------------------------------------------------------
# Using enumerate with Lists:
for index, item in enumerate(my_list):
# Code using index and item
pass
# ----------------------------------------------------------------------
# Using zip to Combine Lists:
list1,list2 = []
combined = list(zip(list1, list2))
# ----------------------------------------------------------------------
# Creating a Function with Default Arguments:
def greet(name="Guest"):
# Function code
pass
# ----------------------------------------------------------------------
# Using the range Function:
for i in range(5):
# Code that runs 5 times
pass
# ----------------------------------------------------------------------
# String Formatting with f-strings:
name = "Alice"
greeting = f"Hello, {name}!"
# ----------------------------------------------------------------------
# Using the in Operator with Strings:
if "substring" in my_string:
# Code to handle substring presence
pass
# ----------------------------------------------------------------------
# Checking for None:
my_variable = None
if my_variable is None:
# Code to handle None
pass
# ----------------------------------------------------------------------
# Creating and Using Classes:
class MyClass:
def __init__(self):
# Constructor code
pass
def my_method(self):
# Method code
pass
# ----------------------------------------------------------------------
# Working with Dates and Times:
from datetime import datetime
now = datetime.now()
# ----------------------------------------------------------------------
# Using map to Apply a Function to a List:
doubled = list(map(lambda x: x * 2, my_list))
# ----------------------------------------------------------------------
# Using filter to Filter a List:
even_numbers = list(filter(lambda x: x % 2 == 0, my_list))
# ----------------------------------------------------------------------
# Creating a List of Unique Values:
unique_values = list(set(my_list))
# ----------------------------------------------------------------------
# Handling Keyboard Interrupt (Ctrl+C):
try:
while True:
# Code that runs indefinitely
pass
except KeyboardInterrupt:
# Code to handle Ctrl+C
pass
# ----------------------------------------------------------------------
# Working with JSON Data:
import json
json_string = '{"key": "value"}'
data = json.loads(json_string)
# ----------------------------------------------------------------------
# Using itertools for Iteration:
from itertools import combinations
combos = combinations(my_list, 2)
# ----------------------------------------------------------------------
# Creating a Virtual Environment:
"""
shell command
python -m venv myenv
"""
# ----------------------------------------------------------------------
# Activating a Virtual Environment:
"""
shell command
source myenv/bin/activate # On Unix/Linux
myenv\Scripts\activate # On Windows
"""
# ----------------------------------------------------------------------
# Installing Packages with pip:
"""
shell command
pip install package_name
"""
# ----------------------------------------------------------------------
# Using a try...except Block with File Operations:
try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
# Handle file not found
pass
# ----------------------------------------------------------------------
# Working with Command-Line Arguments:
import sys
arg1 = sys.argv[1]
# ----------------------------------------------------------------------
# Using defaultdict for Default Values in Dictionaries:
from collections import defaultdict
my_dict = defaultdict(int)
# ----------------------------------------------------------------------
# Reading CSV Files with csv Module:
import csv
with open('data.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
# Process rows
pass
# ----------------------------------------------------------------------
# Using Regular Expressions:
import re
pattern = r'\d+'
result = re.findall(pattern, my_string)
# ----------------------------------------------------------------------
# Creating and Using Generators:
def my_generator():
yield 1
yield 2
# ----------------------------------------------------------------------
# Using os Module for File Operations:
import os
file_exists = os.path.exists('file.txt')