Conditionals
Conditionals are used to control the flow of execution of a program. They allow you to make decisions based on the value of a variable or expression.
There are two types of conditionals in Python: if statements and elif statements.
If statements are used to make decisions based on a single condition. For example:
if x == 1:
print("x is equal to 1")
This code will print "x is equal to 1" if the value of x is equal to 1.
Elif statements are used to make decisions based on multiple conditions. For example:
if x == 1:
print("x is equal to 1")
elif x == 2:
print("x is equal to 2")
else:
print("x is not equal to 1 or 2")
This code will print "x is equal to 1" if the value of x is equal to 1. It will print "x is equal to 2" if the value of x is equal to 2. And it will print "x is not equal to 1 or 2" if the value of x is not equal to 1 or 2.
Loops
Loops are used to repeat code a certain number of times. There are two types of loops in Python: for loops and while loops.
For loops are used to iterate over a collection of data. For example
for i in range(10):
print(i)
This code will print the numbers from 0 to 9.
While loops are used to repeat code as long as a condition is true. For example:
i = 0
while i < 10:
print(i)
i += 1
This code will print the numbers from 0 to 9, one per line.
Functions
Functions are used to group together code that performs a specific task. They can be called multiple times without having to rewrite the code.
To define a function, use the def keyword. For example:
def my_function():
print("This is my function")
To call a function, use the function name followed by parentheses. For example:
my_function()
This will print the message "This is my function" to the console.
Classes
Classes are used to create objects. Objects are like variables, but they can store more than just data. They can also store methods, which are functions that are specific to that object.
To define a class, use the class keyword. For example:
class MyClass:
def init(self):
self.name = "John Doe"
self.age = 30
def say_hello(self):
print("Hello, my name is {} and I am {} years old".format(self.name, self.age))
To create an object, use the class name followed by parentheses. For example:
my_object = MyClass()
To call a method on an object, use the dot notation. For example:
my_object.say_hello()
This will print the message "Hello, my name is John Doe and I am 30 years old" to the console.
These are just a few of the things that you can do with Python. There is much more to learn, but this should give you a good starting point.