-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbasics.py
More file actions
115 lines (87 loc) · 2.57 KB
/
basics.py
File metadata and controls
115 lines (87 loc) · 2.57 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
# Variables
#
name = "Alice" # String variable
anotherName = 'Alice' # String variable
age = 30 # Integer variable
height = 5.5 # Float variable
is_student = True # Boolean variable
print("Name:", name)
print("Another Name:", anotherName)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
# Lists
#
# A list is an ordered collection of items.
fruits = ["apple", "banana", "cherry"]
# Accessing elements in a list
print("First fruit:", fruits[0])
# Adding elements to a list
fruits.append("mango")
print("Fruits after adding date:", fruits)
# For loop
for fruit in fruits:
print("Fruit:", fruit)
# While loop
count = 0
while count < 3:
print("Count:", count)
count += 1
# Conditionals
# Conditionals allow you to execute different code based on conditions.
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
# Functions
# A function is a reusable block of code that performs a specific task.
def greet(name):
"""Greet a person by their name."""
return f"Hello, {name}!"
print(greet("Bob"))
# Function with multiple parameters and default parameter value
def add(a, b=5):
"""Add two numbers."""
return a + b
print("Add 3 + 4:", add(3, 4))
print("Add 3 + default 5:", add(3))
# Dictionaries
# A dictionary is a collection of key-value pairs.
person = {
"name": "Charlie",
"age": 28,
"city": "New York"
}
# Accessing elements in a dictionary
print("Person's name:", person["name"])
# Adding elements to a dictionary
person["email"] = "charlie@example.com"
print("Person dictionary after adding email:", person)
# Tuples
# A tuple is an ordered, immutable collection of items.
coordinates = (10.0, 20.0)
# Accessing elements in a tuple
print("X coordinate:", coordinates[0])
print("Y coordinate:", coordinates[1])
# Classes
# A class defines a blueprint for creating objects.
class Dog:
"""A simple class representing a dog."""
def __init__(self, name, age):
"""Initialize the dog with a name and age."""
self.name = name
self.age = age
def bark(self):
"""Make the dog bark."""
return f"{self.name} says woof!"
# Creating an instance of the Dog class
my_dog = Dog("Rex", 5)
# Accessing attributes and methods
print("Dog's name:", my_dog.name)
print("Dog's age:", my_dog.age)
print(my_dog.bark())
dogs = [Dog("Buddy", 3), Dog("Bella", 2), Dog("Max", 1)]
for dog in dogs:
print(dog.name, "is", dog.age, "years old.")