Repository navigation
Expand file tree
/
Copy pathhello_python.py
More file actions
414 lines (314 loc) ยท 9.91 KB
/
Copy pathhello_python.py
File metadata and controls
414 lines (314 loc) ยท 9.91 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
#!/usr/bin/env python3
"""
๐ Session 19: Python Basics & Comparison
CoderDojo - Learning Python alongside C#!
This file contains examples of Python basics.
Run it with: python3 hello_python.py
"""
# ============================================================
# ๐ SECTION 1: PRINT STATEMENTS
# The simplest Python program - just say hello!
# ============================================================
print("=" * 50)
print("๐ Welcome to Python!")
print("=" * 50)
# In C#, you would write: Console.WriteLine("Hello!");
# In Python, it's just:
print("Hello, World!")
print("Python is fun!")
print() # Empty line
# ============================================================
# ๐ SECTION 2: VARIABLES
# No type declarations needed - Python figures it out!
# ============================================================
print("๐ฆ VARIABLES")
print("-" * 30)
# String variable (text)
name = "Alex"
print(f"Name: {name}")
# Integer variable (whole number)
age = 14
print(f"Age: {age}")
# Float variable (decimal number)
height = 5.6
print(f"Height: {height} feet")
# Boolean variable (True/False)
is_student = True
print(f"Is a student: {is_student}")
# Python allows changing variable types!
my_variable = 10
print(f"my_variable is a number: {my_variable}")
my_variable = "now I'm text!"
print(f"my_variable is now text: {my_variable}")
print()
# ============================================================
# ๐ SECTION 3: GETTING USER INPUT
# Use input() to ask the user for information
# ============================================================
print("๐ค USER INPUT")
print("-" * 30)
# Uncomment these lines to try interactive input:
# user_name = input("What's your name? ")
# print(f"Hello, {user_name}! Nice to meet you!")
#
# user_age = int(input("How old are you? "))
# print(f"Next year you'll be {user_age + 1}!")
# For this demo, we'll use preset values:
user_name = "CoderDojo Student"
user_age = 12
print(f"Hello, {user_name}! You are {user_age} years old.")
print()
# ============================================================
# ๐ SECTION 4: IF STATEMENTS (CONDITIONALS)
# Make decisions in your code!
# ============================================================
print("๐ IF STATEMENTS")
print("-" * 30)
score = 85
# Notice: no parentheses around condition, use colon at end!
if score >= 90:
print("Grade: A ๐")
elif score >= 80:
print("Grade: B ๐")
elif score >= 70:
print("Grade: C ๐")
elif score >= 60:
print("Grade: D ๐")
else:
print("Grade: F ๐ข")
# Checking multiple conditions
temperature = 72
is_sunny = True
if temperature > 70 and is_sunny:
print("Perfect day for the park! โ๏ธ")
elif temperature > 70:
print("Warm but cloudy ๐ฅ๏ธ")
else:
print("Maybe stay inside ๐ ")
print()
# ============================================================
# ๐ SECTION 5: LOOPS
# Repeat code multiple times!
# ============================================================
print("๐ LOOPS")
print("-" * 30)
# For loop with range
print("Counting to 5:")
for i in range(1, 6):
print(f" {i}")
# For loop with a list
print("\nFavorite fruits:")
fruits = ["apple", "banana", "cherry", "dragon fruit"]
for fruit in fruits:
print(f" ๐ {fruit}")
# While loop
print("\nCountdown:")
countdown = 5
while countdown > 0:
print(f" {countdown}...")
countdown -= 1
print(" ๐ Blastoff!")
print()
# ============================================================
# ๐ SECTION 6: LISTS
# Store multiple items in one variable!
# ============================================================
print("๐ LISTS")
print("-" * 30)
# Creating a list
colors = ["red", "green", "blue"]
print(f"Colors: {colors}")
# Accessing items (indexing starts at 0!)
print(f"First color: {colors[0]}")
print(f"Last color: {colors[-1]}") # -1 means last item!
# Adding items
colors.append("yellow")
print(f"After adding yellow: {colors}")
# Removing items
colors.remove("green")
print(f"After removing green: {colors}")
# List slicing (getting parts of a list)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"\nNumbers: {numbers}")
print(f"First 3: {numbers[:3]}")
print(f"Last 3: {numbers[-3:]}")
print(f"Middle (3-7): {numbers[3:7]}")
print(f"Every other: {numbers[::2]}")
print()
# ============================================================
# ๐ SECTION 7: FUNCTIONS
# Reusable blocks of code!
# ============================================================
print("๐ง FUNCTIONS")
print("-" * 30)
# Simple function
def say_hello():
"""A function that says hello."""
print("Hello from a function! ๐")
say_hello()
# Function with parameter
def greet(name):
"""Greet someone by name."""
print(f"Hello, {name}! Welcome to Python!")
greet("Ninja Coder")
# Function with return value
def add(a, b):
"""Add two numbers and return the result."""
return a + b
result = add(5, 3)
print(f"5 + 3 = {result}")
# Function with default parameter
def greet_with_emoji(name, emoji="๐"):
"""Greet someone with a custom emoji."""
print(f"Hello, {name}! {emoji}")
greet_with_emoji("Alex")
greet_with_emoji("Sam", "๐")
# Function that works with lists
def calculate_average(numbers):
"""Calculate the average of a list of numbers."""
if len(numbers) == 0:
return 0
return sum(numbers) / len(numbers)
grades = [90, 85, 92, 88, 95]
avg = calculate_average(grades)
print(f"Average grade: {avg}")
print()
# ============================================================
# ๐ SECTION 8: DICTIONARIES
# Key-value pairs - like a real dictionary!
# ============================================================
print("๐ DICTIONARIES")
print("-" * 30)
# Creating a dictionary
student = {
"name": "Alex",
"age": 14,
"grade": 8,
"favorite_subject": "Computer Science"
}
# Accessing values
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
# Adding/updating values
student["email"] = "alex@school.com"
student["age"] = 15 # Happy birthday!
# Looping through a dictionary
print("\nAll student info:")
for key, value in student.items():
print(f" {key}: {value}")
# Check if key exists
if "name" in student:
print(f"\nFound student: {student['name']}")
print()
# ============================================================
# ๐ SECTION 9: CLASSES
# Create your own data types!
# ============================================================
print("๐๏ธ CLASSES")
print("-" * 30)
class Pet:
"""A class representing a pet."""
def __init__(self, name, species, age):
"""Initialize a new pet with name, species, and age."""
self.name = name
self.species = species
self.age = age
self.tricks = []
def speak(self):
"""Make the pet speak based on its species."""
if self.species == "dog":
print(f"{self.name} says: Woof! ๐")
elif self.species == "cat":
print(f"{self.name} says: Meow! ๐ฑ")
elif self.species == "bird":
print(f"{self.name} says: Tweet! ๐ฆ")
else:
print(f"{self.name} says: ...? ๐ค")
def learn_trick(self, trick):
"""Teach the pet a new trick."""
self.tricks.append(trick)
print(f"{self.name} learned '{trick}'! ๐")
def show_tricks(self):
"""Display all tricks the pet knows."""
if not self.tricks:
print(f"{self.name} doesn't know any tricks yet!")
else:
print(f"{self.name}'s tricks: {', '.join(self.tricks)}")
def get_info(self):
"""Return a string with pet information."""
return f"{self.name} is a {self.age}-year-old {self.species}"
# Creating objects from the class
buddy = Pet("Buddy", "dog", 3)
whiskers = Pet("Whiskers", "cat", 5)
# Using object methods
print(buddy.get_info())
buddy.speak()
buddy.learn_trick("sit")
buddy.learn_trick("roll over")
buddy.show_tricks()
print()
print(whiskers.get_info())
whiskers.speak()
print()
# ============================================================
# ๐ SECTION 10: PUTTING IT ALL TOGETHER
# A mini-project combining everything!
# ============================================================
print("๐ฎ MINI PROJECT: Book Collection")
print("-" * 30)
class Book:
"""A class representing a book."""
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.is_read = False
def mark_as_read(self):
"""Mark the book as read."""
self.is_read = True
print(f"โ
Marked '{self.title}' as read!")
def display(self):
"""Display book information."""
status = "๐ Read" if self.is_read else "๐ Unread"
print(f" {self.title} by {self.author} ({self.pages} pages) - {status}")
# Create a list of books
library = [
Book("Harry Potter", "J.K. Rowling", 309),
Book("The Hobbit", "J.R.R. Tolkien", 310),
Book("Percy Jackson", "Rick Riordan", 377),
Book("Diary of a Wimpy Kid", "Jeff Kinney", 217)
]
# Mark some as read
library[0].mark_as_read()
library[2].mark_as_read()
# Display all books
print("\n๐ My Book Collection:")
for book in library:
book.display()
# Calculate total pages
total_pages = sum(book.pages for book in library)
books_read = sum(1 for book in library if book.is_read)
print(f"\n๐ Stats:")
print(f" Total books: {len(library)}")
print(f" Books read: {books_read}")
print(f" Total pages: {total_pages}")
print()
# ============================================================
# ๐ THE END!
# ============================================================
print("=" * 50)
print("๐ Congratulations! You've learned Python basics!")
print("=" * 50)
print()
print("๐ What we covered:")
print(" โ
Print statements")
print(" โ
Variables")
print(" โ
User input")
print(" โ
If statements")
print(" โ
Loops (for and while)")
print(" โ
Lists")
print(" โ
Functions")
print(" โ
Dictionaries")
print(" โ
Classes")
print()
print("๐ Keep practicing and have fun coding!")