Basic Syntax
1) Comments
Comments are ignored by the interpreter and used to provide explanations or clarifications in your code.
# This is a single line comment
"""
This is a
multi-line
comment
"""
2) Variables
Variables are used to store data.
name = "Alice" # string
age = 25 # integer
height = 1.65 # float
is_student = True # boolean
3) Data Types
Python supports several data types:
# Strings
text = "Hello, World!"
# Numbers
integer = 42
float_number = 3.14
# Booleans
is_true = True
is_false = False
# Lists
my_list = ["apple", "banana", "cherry"]
# Tuples
my_tuple = ("apple", "banana", "cherry")
# Dictionaries
my_dict = {"name": "Alice", "age": 25}
4) Operators
Python has several operators for performing calculations:
# Arithmetic operators
x = 5 + 3 # addition
y = 5 - 3 # subtraction
z = 5 * 3 # multiplication
q = 5 / 3 # division
r = 5 % 3 # modulus
s = 5 ** 3 # exponentiation
# Comparison operators
a = 5 == 3 # equal
b = 5 != 3 # not equal
c = 5 > 3 # greater than
d = 5 < 3 # less than
e = 5 >= 3 # greater than or equal to
f = 5 <= 3 # less than or equal to
# Logical operators
g = True and False # and
h = True or False # or
i = not True # not
5) Conditional Statements
Conditional statements are used to perform different actions depending on whether a condition is true or false.
if age > 18:
print("You are an adult")
elif age == 18:
print("You just turned 18!")
else:
print("You are a minor")
6) Loops
Loops are used to execute a block of code multiple times.
# For loop
for i in range(5):
print(i)
# While loop
i = 0
while i < 5:
print(i)
i += 1
7) Functions
Functions are used to encapsulate code and reuse it throughout your program.
def greet(name):
print("Hello, " + name)
greet("Alice")
8) Classes
Classes are used to create objects that can have properties and methods.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
alice = Person("Alice", 25)
alice.greet()
9) File I/O
File I/O is used to read and write data to files.
# Reading a file
with open("myfile.txt", "r") as f:
contents = f.read()
print(contents)
# Writing to a file
with open("myfile.txt", "w") as f:
f.write("Hello, World!")
10) Lists
Lists are used to store multiple items in a single variable. Lists are mutable, which means you can change the items inside them.
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: banana
fruits[1] = "kiwi"
print(fruits) # Output: ['apple', 'kiwi', 'cherry']
11) Tuples
Tuples are used to store multiple items in a single variable. Tuples are immutable, which means you cannot change the items inside them.
fruits = ("apple", "banana", "cherry")
print(fruits[1]) # Output: banana
# fruits[1] = "kiwi" # This will raise an error
12) Dictionaries
Dictionaries are used to store key-value pairs. Dictionaries are mutable.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice
person["age"] = 26
print(person) # Output: {'name': 'Alice', 'age': 26}
13) String Formatting
String formatting is used to combine strings and variables into a single string.
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.
14) List Comprehensions
List comprehensions are used to create lists in a concise and readable way.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
15) Lambda Functions
Lambda functions are used to create small, anonymous functions
f = lambda x: x**2
print(f(3)) # Output: 9
16) Modules
Modules are used to organize code into reusable units.
# Importing a module
import math
print(math.pi) # Output: 3.141592653589793
# Importing specific functions from a module
from math import pi
print(pi) # Output: 3.141592653589793
17) Exceptions
Exceptions are used to handle errors that occur during the execution of a program.
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023