Creating and using Python files, also known as Python scripts, is the foundation of writing and running Python programs. Here’s a beginner-friendly explanation of how to get started:
Ctrl
+N
(Windows) or Cmd
+N
(macOS)..py
extension, which indicates it’s a Python script. For example, you can save it as my_script.py
.print("Hello, World!")
print()
function to display “Hello, World!” on the screen.cd
command (e.g., cd Documents
if your file is in the “Documents” folder).python
followed by the name of your Python file and press Enter:python my_script.py
Ctrl
+S
or Cmd
+S
).That’s the basic process of creating and using Python files. Start with simple scripts like “Hello, World!” and gradually build your skills by tackling more advanced projects. Python is known for its readability and simplicity, making it an excellent choice for beginners to start their coding journey.
Python is a versatile programming language that can work with various types of data. Here’s a basic overview of three fundamental data types: int
, float
, and str
. These 3 data types help to make up most of the basic operations you will do.
int
)Integers are whole numbers, which means they don’t have any decimal points.
5
, -10
, 1000
my_integer = 42
print(my_integer) # Output: 42
float
)3.14
, -0.5
, 2.0
my_float = 3.14159
print(my_float) # Output: 3.14159
str
)'Hello, World!'
, "Python is fun"
, '''Triple-quoted strings'''
my_string = "Hello, World!"
print(my_string) # Output: Hello, World!
These three basic data types are the building blocks for most Python programs. You can perform operations on them, combine them, and use them to represent different kinds of data in your code. As you continue to learn Python, you’ll discover more data types and ways to work with them, but these are the essential ones to get started.
If you are not familiar you can find details about what collections are here.
Python provides two common collection types, lists, and tuples. These collection types allow you to store multiple values in a single variable.
Creating a List:
To create a list, use square brackets []
and separate the items with commas.
my_list = [1, 2, 3, "apple", "banana"]
Accessing Elements: You can access individual elements in a list by their position, called an index. Python uses zero-based indexing, so the first element is at index 0.
first_item = my_list[0] # Gets the first item (1)
second_item = my_list[1] # Gets the second item (2)
Modifying a List: You can change, add, or remove items from a list.
my_list[3] = "cherry" # Modifies an item (changes "apple" to "cherry")
my_list.append(4) # Adds an item to the end (appends 4)
my_list.remove("banana") # Removes an item (removes "banana")
Creating a Tuple:
To create a tuple, use parentheses ()
and separate the items with commas.
my_tuple = (1, 2, 3, "apple", "banana")
Accessing Elements: You access tuple elements in the same way as with lists, using zero-based indexing.
first_item = my_tuple[0] # Gets the first item (1)
second_item = my_tuple[1] # Gets the second item (2)
Immutable Nature: You cannot change the elements of a tuple after creation. Attempting to do so will result in an error.
my_tuple[3] = "cherry" # This will raise an error (Tuples are immutable)
When to Use Lists vs. Tuples:
Here’s a simple summary: Lists are like dynamic containers where you can put different things and change them, while tuples are like sealed containers where you put things that won’t change. Both are valuable tools in Python, and your choice depends on your specific needs in a program.
If you are not familiar you can find details about what functions are here.
Python functions are like mini-programs or reusable blocks of code that perform specific tasks. Think of them as functions in math, where you input something, and it gives you a result. In Python, you can create your own functions to perform tasks you need. Here’s a beginner-friendly explanation:
def
keyword, followed by the function name and parentheses ()
. You can also include parameters (input values) inside the parentheses.def greet(name):
print("Hello, " + name + "!")
greet
that takes one parameter, name
.greet("Alice")
greet
function and passes "Alice"
as the name
parameter.return
keyword. This is like the answer you get from a math function.def add(a, b):
result = a + b
return result
add
function takes two parameters, a
and b
, adds them together, and returns the result.sum_result = add(5, 3)
print(sum_result) # Output: 8
add
function with 5
and 3
as arguments and store the result in the sum_result
variable.print()
, len()
, and input()
, which you can use without having to define them yourself.Here’s a simple summary: Functions in Python allow you to define a set of instructions that can be used over and over again. They take input, perform actions, and can return results. Functions are like handy tools you create to make your coding tasks easier and more organized.
Python control flows, especially the if
statement, help you make decisions in your code. Think of them as instructions to your program to perform certain actions based on conditions. Let’s break it down in a beginner-friendly way:
if
Statementif
statement is used to make decisions in Python.if
Syntaxif
statement looks like this:if condition:
# Code to execute if the condition is True
condition
is an expression that evaluates to either True
or False
.True
or False
in a boolean context.0
, an empty string ""
, and empty containers.You can compare values using boolean logical operators to create conditions in your if
statements.
Common boolean operators are:
==
(equal): Checks if two values are equal.!=
(not equal): Checks if two values are not equal.<
(less than): Checks if one value is less than another.>
(greater than): Checks if one value is greater than another.<=
(less than or equal to): Checks if one value is less than or equal to another.>=
(greater than or equal to): Checks if one value is greater than or equal to another.Example:
x = 5
y = 10
if x < y:
print("x is less than y")
if
statement checks if x
is less than y
. If it’s true, it prints “x is less than y.”else
and elif
(Else-If) Statementsif
statements with else
and elif
(else-if) statements to handle multiple conditions.Example:
age = 20
if age < 18:
print("You are underage.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
if
Statementsif
statements inside other if
statements to handle more complex conditions.Example:
x = 5
if x > 0:
if x % 2 == 0:
print("x is a positive even number.")
else:
print("x is a positive odd number.")
else:
print("x is not a positive number.")
if
statements to determine whether x
is positive and even or positive and odd.In summary, if
statements allow your Python program to make decisions based on conditions. You can use boolean operators to create conditions, and you can include else
and elif
statements for more complex decision-making. This is a fundamental building block for creating dynamic and responsive code in Python.
Python loops are used to repeatedly execute a block of code. They allow you to automate repetitive tasks by running the same code multiple times. Let’s explore Python loops in a beginner-friendly way:
for
Loopfor
loop is used when you know how many times you want to repeat a certain action. It’s often used to iterate over a sequence, such as a list or a range of numbers.Basic for
Loop Syntax:
for variable in sequence:
# Code to execute in each iteration
variable
represents an item from the sequence in each iteration, and sequence
is the collection of items to loop through.Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for
loop iterates through the fruits
list and prints each fruit one by one.while
Loopwhile
loop is used when you want to repeat a block of code as long as a certain condition is true. It’s often used when you don’t know in advance how many times the loop will run.Basic while
Loop Syntax:
while condition:
# Code to execute as long as the condition is True
condition
remains True
.Example:
count = 0
while count < 5:
print("Count: ", count)
count += 1
while
loop prints the value of count
as long as it’s less than 5
, incrementing count
in each iteration.break
: Terminates the loop prematurely.continue
: Skips the current iteration and moves to the next.Example (using break
):
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num == 4:
break # Exit the loop when num is 4
print(num)
num
becomes 4
, and the code after the loop continues executing.Example (using continue
):
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 == 0:
continue # Skip even numbers
print(num)
Python loops are powerful tools for automating repetitive tasks and processing data. By understanding for
and while
loops and how to control their flow, you can make your programs more dynamic and efficient.
In Python, classes are like blueprints for creating objects. Think of a class as a template that defines the properties (attributes) and behaviors (methods) that objects of that class will have. Let’s break down Python classes in a beginner-friendly way:
class
keyword, followed by the name of the class (usually starting with a capital letter).class Dog:
# Class definition goes here
Dog
.class Dog:
breed = "Unknown" # Attribute to store the dog's breed
age = 0 # Attribute to store the dog's age
breed
and age
are attributes that every dog object will have.class Dog:
breed = "Unknown"
age = 0
def bark(self):
print("Woof! Woof!")
def fetch(self):
print("Fetching the ball...")
bark()
and fetch()
are methods that represent the actions a dog can do.my_dog = Dog() # Creating an instance of the Dog class
my_dog
is now an object of the Dog
class.object_name.attribute
or object_name.method()
).my_dog.breed = "Golden Retriever" # Setting the breed attribute
my_dog.age = 3 # Setting the age attribute
print("My dog is a", my_dog.breed) # Accessing the breed attribute
my_dog.bark() # Calling the bark method
breed
and age
attributes and called the bark()
method on my_dog
.__init__
)__init__
method is a special method in Python classes. It’s called when you create an object from the class and is used to initialize attributes.class Dog:
def __init__(self, breed, age):
self.breed = breed
self.age = age
def bark(self):
print("Woof! Woof!")
Dog
object, you need to provide values for breed
and age
.my_dog = Dog("Golden Retriever", 3)
That’s the basic idea of Python classes! Classes allow you to define a blueprint for creating objects with specific attributes and behaviors. They help you organize your code in a structured and reusable way, which is especially useful for building complex applications.