-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_output.py
More file actions
398 lines (306 loc) · 11.3 KB
/
Copy pathinput_output.py
File metadata and controls
398 lines (306 loc) · 11.3 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
"""
Module: input_output.py
Topic: Input and Output Operations
Level: Beginner
This file teaches you how to:
- Take user input with input()
- Format and display output
- Handle different input types
- Work with command-line arguments
"""
# =============================================================================
# SECTION 1: THE input() FUNCTION
# =============================================================================
print("=" * 60)
print("THE input() FUNCTION")
print("=" * 60)
# Basic input
# name = input("What is your name? ")
# print(f"Hello, {name}!")
# Note: input() always returns a STRING!
# age = input("How old are you? ")
# print(f"Next year you'll be {int(age) + 1}")
# =============================================================================
# SECTION 2: TYPE CONVERSION FOR INPUT
# =============================================================================
print("\n" + "=" * 60)
print("TYPE CONVERSION FOR INPUT")
print("=" * 60)
# When getting numeric input, you MUST convert the type
# Integer input
# age = int(input("Enter your age: "))
# print(f"You were born around {2024 - age}")
# Float input
# price = float(input("Enter the price: $"))
# print(f"With tax: ${price * 1.1:.2f}")
# Boolean input (need to handle manually)
# response = input("Continue? (yes/no): ")
# continue_program = response.lower() in ('yes', 'y', 'true', '1')
# =============================================================================
# SECTION 3: MULTIPLE INPUTS
# =============================================================================
print("\n" + "=" * 60)
print("MULTIPLE INPUTS")
print("=" * 60)
# Split input into multiple values
# coordinates = input("Enter x,y coordinates: ")
# x, y = coordinates.split(',')
# print(f"X: {x.strip()}, Y: {y.strip()}")
# Multiple inputs with map
# numbers = list(map(int, input("Enter numbers separated by space: ").split()))
# print(f"You entered: {numbers}")
# print(f"Sum: {sum(numbers)}")
# Using list comprehension
# numbers = [int(x) for x in input("Enter numbers: ").split()]
# print(f"Doubled: {[n * 2 for n in numbers]}")
# =============================================================================
# SECTION 4: FORMATTED OUTPUT
# =============================================================================
print("\n" + "=" * 60)
print("FORMATTED OUTPUT")
print("=" * 60)
# F-strings (Python 3.6+) - RECOMMENDED
name = "Alice"
age = 25
score = 95.5678
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Score: {score:.2f}") # 2 decimal places
# F-string formatting options
print(f"\n{'Formatted Output Examples':=^50}")
number = 42
print(f"Decimal: {number:d}")
print(f"Binary: {number:b}")
print(f"Octal: {number:o}")
print(f"Hexadecimal: {number:x}")
print(f"Hexadecimal (upper): {number:X}")
pi = 3.14159
print(f"\nFloat: {pi:f}")
print(f"Scientific: {pi:e}")
print(f"Percentage: {pi:.2%}")
# Width and alignment
print(f"\n{'Alignment':<15} | {'Value':>10}")
print(f"{'Left':<15} | {42:>10}")
print(f"{'Center':^15} | {42:^10}")
print(f"{'Right':>15} | {42:<10}")
# =============================================================================
# SECTION 5: PRINT OPTIONS
# =============================================================================
print("\n" + "=" * 60)
print("PRINT OPTIONS")
print("=" * 60)
# sep parameter - separator between items
print("2024", "03", "21", sep="-") # 2024-03-21
print("A", "B", "C", sep=" | ") # A | B | C
# end parameter - what to print at the end
print("Loading", end="")
for i in range(3):
print(".", end="", flush=True)
# time.sleep(0.5) # Uncomment for animation effect
print(" Done!")
# Print to file
# with open('output.txt', 'w') as f:
# print("This goes to a file", file=f)
# =============================================================================
# SECTION 6: ESCAPE SEQUENCES
# =============================================================================
print("\n" + "=" * 60)
print("ESCAPE SEQUENCES")
print("=" * 60)
print("New line: Line 1\nLine 2")
print("Tab:\tIndented")
print("Backslash: \\")
print("Quote: \"")
print("Single quote: \'")
print("Carriage return: ABC\rXYZ") # XYZ replaces ABC
print("Backspace: ABC\bX") # ABC with last char replaced by X
# =============================================================================
# SECTION 7: RAW STRINGS
# =============================================================================
print("\n" + "=" * 60)
print("RAW STRINGS")
print("=" * 60)
# Raw strings don't interpret escape sequences
normal_path = "C:\new\test" # Problem! \n and \t are escape sequences
raw_path = r"C:\new\test" # Solution: raw string
print(f"Normal string: {normal_path}") # May produce unexpected output
print(f"Raw string: {raw_path}") # Preserves backslashes
# Raw strings are essential for regular expressions
import re
pattern = r"\d+" # Matches one or more digits
text = "I have 42 apples"
matches = re.findall(pattern, text)
print(f"Regex matches: {matches}")
# =============================================================================
# SECTION 8: FORMATTING METHODS COMPARISON
# =============================================================================
print("\n" + "=" * 60)
print("FORMATTING METHODS COMPARISON")
print("=" * 60)
item = "Apple"
price = 1.50
quantity = 3
total = price * quantity
# Method 1: F-strings (Python 3.6+) - RECOMMENDED
print(f"F-string: {quantity} {item}s at ${price:.2f} each = ${total:.2f}")
# Method 2: .format() method
print(".format(): {} {}s at ${:.2f} each = ${:.2f}".format(quantity, item, price, total))
# Method 3: % formatting (legacy)
print("%% formatting: %d %ss at $%.2f each = $%.2f" % (quantity, item, price, total))
# Method 4: String concatenation (not recommended)
print("Concat: " + str(quantity) + " " + item + "s at $" + str(round(price, 2)) + " each")
# =============================================================================
# SECTION 9: COMMAND-LINE ARGUMENTS
# =============================================================================
print("\n" + "=" * 60)
print("COMMAND-LINE ARGUMENTS")
print("=" * 60)
import sys
# sys.argv contains command-line arguments
# sys.argv[0] is the script name
# sys.argv[1:] are the actual arguments
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
print(f"Number of arguments: {len(sys.argv) - 1}")
# Example usage:
# python input_output.py arg1 arg2 arg3
# Better argument parsing with argparse (for real scripts)
import argparse
# Create a demo parser (in real use, you'd use this for actual arguments)
demo_parser = argparse.ArgumentParser(description='Demo argument parser')
demo_parser.add_argument('-n', '--name', type=str, default='World', help='Name to greet')
demo_parser.add_argument('-c', '--count', type=int, default=1, help='Number of greetings')
demo_parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
# Note: In a real script, you would use:
# args = demo_parser.parse_args()
# print(f"Hello, {args.name}!" * args.count)
# =============================================================================
# SECTION 10: PRACTICAL EXAMPLES
# =============================================================================
print("\n" + "=" * 60)
print("PRACTICAL EXAMPLES")
print("=" * 60)
def simple_calculator():
"""
A simple calculator that takes user input.
"""
print("\n--- Simple Calculator ---")
# In a real program, uncomment the input lines:
# num1 = float(input("Enter first number: "))
# operator = input("Enter operator (+, -, *, /): ")
# num2 = float(input("Enter second number: "))
# For demonstration, use fixed values:
num1, operator, num2 = 10.0, '+', 5.0
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 != 0:
result = num1 / num2
else:
return "Error: Division by zero!"
else:
return "Error: Invalid operator!"
return f"{num1} {operator} {num2} = {result}"
print(simple_calculator())
def create_receipt():
"""
Create a formatted receipt.
"""
print("\n--- Receipt Generator ---")
items = [
("Coffee", 4.50),
("Sandwich", 8.99),
("Cookie", 2.50),
]
subtotal = sum(price for _, price in items)
tax_rate = 0.08
tax = subtotal * tax_rate
total = subtotal + tax
# Print formatted receipt
print("\n" + "=" * 40)
print(f"{'CAFE RECEIPT':^40}")
print("=" * 40)
for item, price in items:
print(f"{item:<25} ${price:>10.2f}")
print("-" * 40)
print(f"{'Subtotal':<25} ${subtotal:>10.2f}")
print(f"{'Tax (8%)':<25} ${tax:>10.2f}")
print("=" * 40)
print(f"{'TOTAL':<25} ${total:>10.2f}")
print("=" * 40)
print(f"{'Thank you for your visit!':^40}")
create_receipt()
def temperature_converter():
"""
Convert temperature between Celsius and Fahrenheit.
Demonstrates input handling and formatted output.
"""
print("\n--- Temperature Converter ---")
# For demonstration:
temp = 25
unit = 'C'
# In real use:
# temp = float(input("Enter temperature: "))
# unit = input("Enter unit (C/F): ").upper()
if unit.upper() == 'C':
converted = (temp * 9/5) + 32
print(f"{temp:.1f}°C = {converted:.1f}°F")
elif unit.upper() == 'F':
converted = (temp - 32) * 5/9
print(f"{temp:.1f}°F = {converted:.1f}°C")
else:
print("Invalid unit! Use C or F.")
temperature_converter()
# =============================================================================
# SECTION 11: INPUT VALIDATION
# =============================================================================
print("\n" + "=" * 60)
print("INPUT VALIDATION")
print("=" * 60)
def get_valid_int(prompt, min_val=None, max_val=None):
"""
Get a valid integer from user input with range validation.
"""
while True:
try:
# value = int(input(prompt)) # Uncomment for real input
value = 5 # Demo value
if min_val is not None and value < min_val:
print(f"Value must be at least {min_val}")
continue
if max_val is not None and value > max_val:
print(f"Value must be at most {max_val}")
continue
return value
except ValueError:
print("Please enter a valid integer!")
def get_valid_email(prompt):
"""
Get a valid email address from user input.
"""
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
while True:
# email = input(prompt) # Uncomment for real input
email = "user@example.com" # Demo value
if re.match(pattern, email):
return email
print("Please enter a valid email address!")
# Demo validation
print("\nValidation Examples:")
age = get_valid_int("Enter age (0-120): ", 0, 120)
print(f"Valid age: {age}")
email = get_valid_email("Enter email: ")
print(f"Valid email: {email}")
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\n" + "=" * 60)
print("✅ You've learned about input and output in Python!")
print("📚 Next: Learn about comments and documentation in comments.py")
print("=" * 60)