Basics of Python Syntax
Basics of Python Syntax
1. Comments: Comments are lines in your code that Python ignores. They are used to
explain the code and make it more readable.
python
# This is a comment
2. Variables and Data Types: Variables are used to store data. Python has several built-
in data types, including integers, floats, strings, and booleans.
python
3. Indentation: Python uses indentation to define the structure of the code. It's
important to use consistent indentation (usually 4 spaces) because incorrect
indentation can cause errors.
python
def greet():
print("Hello, World!")
4. Control Flow: Control flow statements are used to control the execution of code
based on certain conditions.
o If statements: Used to make decisions in your code.
python
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
python
for i in range(5):
print(i)
python
while x > 0:
print(x)
x -= 1
5. Functions: Functions are blocks of reusable code that perform a specific task. They
are defined using the def keyword.
python
result = add(3, 4)
print(result) # Output: 7
Advanced Topics
1. Lists: Lists are ordered collections of items. They are created using square brackets
[].
python
python
3. Classes and Objects: Classes are blueprints for creating objects. Objects are
instances of classes. They allow you to create reusable code and model real-world
entities.
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age}
years old.")
p = Person("Alice", 25)
p.greet() # Output: Hello, my name is Alice and I am 25 years old.
4. Modules and Importing: Modules are files containing Python code that can be
imported and used in other Python files. The import statement is used to include a
module in your code.
python
import math
print(math.sqrt(16))
Variables
A variable is a name that refers to a value. You can think of it as a labeled storage container
for data that you want to use later in your code. Variables can hold different types of data,
and their types can change throughout the program.
python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
In this example:
Data Types
Python has several built-in data types. Here are some of the most commonly used ones:
1. Integer (int): Integers are whole numbers, without any decimal point.
python
x = 10
python
y = 3.14
3. String (str): Strings are sequences of characters, enclosed in either single quotes ' or
double quotes ".
python
name = "Alice"
greeting = 'Hello, World!'
4. Boolean (bool): Booleans represent one of two values: True or False.
python
is_active = True
is_logged_in = False
5. List: Lists are ordered collections of items. Items can be of different types, and lists
are mutable (you can change their content).
python
6. Tuple: Tuples are similar to lists, but they are immutable (you cannot change their
content once they are created).
python
7. Dictionary (dict): Dictionaries are unordered collections of key-value pairs. Each key
must be unique, and values can be of any type.
python
8. Set: Sets are unordered collections of unique items. Sets are mutable, but the items
inside them must be immutable (e.g., strings, numbers).
python
unique_numbers = {1, 2, 3, 4, 5}
Variables in Python are assigned using the = operator. The value on the right side of the = is
assigned to the variable on the left side.
python
x = 5
y = 10
sum = x + y
Example Code
Here's a sample code that demonstrates the use of different data types and variables:
python
# Variables
name = "Alice"
age = 25
height = 5.6
is_student = True
# List
hobbies = ["reading", "coding", "hiking"]
# Dictionary
student = {
"name": name,
"age": age,
"height": height,
"is_student": is_student,
"hobbies": hobbies
}
# Printing values
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
print("Hobbies:", hobbies)
print("Student Info:", student)
Python provides various ways to take input from the user and display output. Let's explore
these concepts:
Input
To get input from the user, you can use the input() function. This function reads a line from
the input (usually from the keyboard) and returns it as a string.
python
In this example:
The input() function displays the prompt "Enter your name: " and waits for the
user to enter their name.
The user input is then stored in the variable name.
The print() function is used to display the greeting message along with the entered
name.
Output
To display output to the console, you can use the print() function. The print() function
can take multiple arguments and will convert them to strings and print them separated by
spaces.
python
x = 5
y = 10
print("The value of x is", x)
print("The value of y is", y)
print("The sum of x and y is", x + y)
In this example:
The print() function displays the values of x and y and their sum.
Formatted Output
You can also use formatted strings to create more readable output. There are several ways to
format strings in Python, including using the str.format() method, f-strings (formatted
string literals), and the % operator.
python
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Using % operator:
python
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Here's a complete example that demonstrates both input and output in Python:
python
In this example:
The input() function is used to get the user's name, age, and favorite hobby.
The int() function is used to convert the age input (which is a string) to an integer.
The print() function is used to display the user's information.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor Division x // y
Comparison Operators
Comparison operators are used to compare two values and return a boolean result (True or
False).
Operator Description Example
== Equal to x == y
!= Not equal to x != y
Logical Operators
or Logical OR x or y
Assignment Operators
= Assign x = 5
` ` Bitwise OR `x y`
^ Bitwise XOR x ^ y
~ Bitwise NOT ~x
Membership Operators
in Value is in sequence x in y
Identity Operators
Identity operators are used to compare the memory locations of two objects.
Example Code
python
# Arithmetic Operators
x = 10
y = 5
print("x + y =", x + y) # Output: 15
print("x - y =", x - y) # Output: 5
print("x * y =", x * y) # Output: 50
print("x / y =", x / y) # Output: 2.0
print("x % y =", x % y) # Output: 0
print("x ** y =", x ** y) # Output: 100000
print("x // y =", x // y) # Output: 2
# Comparison Operators
print("x == y:", x == y) # Output: False
print("x != y:", x != y) # Output: True
print("x > y:", x > y) # Output: True
print("x < y:", x < y) # Output: False
print("x >= y:", x >= y) # Output: True
print("x <= y:", x <= y) # Output: False
# Logical Operators
a = True
b = False
print("a and b:", a and b) # Output: False
print("a or b:", a or b) # Output: True
print("not a:", not a) # Output: False
# Assignment Operators
z = 5
z += 3
print("z after z += 3:", z) # Output: 8
# Bitwise Operators
m = 5 # 0101 in binary
n = 3 # 0011 in binary
print("m & n:", m & n) # Output: 1 (0001 in binary)
print("m | n:", m | n) # Output: 7 (0111 in binary)
print("m ^ n:", m ^ n) # Output: 6 (0110 in binary)
print("~m:", ~m) # Output: -6
print("m << 2:", m << 2) # Output: 20 (10100 in binary)
print("m >> 2:", m >> 2) # Output: 1 (0001 in binary)
# Membership Operators
numbers = [1, 2, 3, 4, 5]
print("3 in numbers:", 3 in numbers) # Output: True
print("6 in numbers:", 6 in numbers) # Output: False
# Identity Operators
x1 = [1, 2, 3]
x2 = [1, 2, 3]
x3 = x1
print("x1 is x2:", x1 is x2) # Output: False
print("x1 is x3:", x1 is x3) # Output: True
print("x1 is not x2:", x1 is not x2) # Output: True
conditional statements
Sure! Conditional statements in Python allow you to execute certain pieces of code based on
whether a condition is true or false. The most common conditional statements are if, elif,
and else.
If Statement
The if statement evaluates a condition and executes the block of code inside it if the
condition is true.
python
x = 10
if x > 5:
print("x is greater than 5")
In this example, since x is greater than 5, the message "x is greater than 5" will be printed.
Elif Statement
The elif (short for "else if") statement allows you to check multiple conditions. If the first
if condition is false, the program will check the elif condition.
python
x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
In this example, since x is equal to 5, the message "x is equal to 5" will be printed.
Else Statement
The else statement is executed when all the previous conditions are false.
python
x = 3
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
In this example, since x is less than 5, the message "x is less than 5" will be printed.
Nested If Statements
You can also nest if statements inside each other to check multiple conditions.
python
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
else:
print("x is greater than or equal to 15")
else:
print("x is less than or equal to 5")
In this example, since x is between 5 and 15, the message "x is between 5 and 15" will be
printed.
You can use logical operators (and, or, not) to combine multiple conditions.
python
x = 10
y = 20
if x > 5 and y > 15:
print("Both conditions are true")
In this example, since both x is greater than 5 and y is greater than 15, the message "Both
conditions are true" will be printed.
Example Code
python
# Getting user input
age = int(input("Enter your age: "))
# Conditional statements
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")
# Nested if statements
number = int(input("Enter a number: "))
if number >= 0:
if number == 0:
print("The number is zero.")
else:
print("The number is positive.")
else:
print("The number is negative.")
In this example:
The first conditional block checks the user's age and prints a message based on their
age group.
The second block checks whether the entered number is zero, positive, or negative
using nested if statements.
Conditional statements are a fundamental part of programming, allowing you to control the
flow of your code based on different conditions. Let me know if you have any questions or
need further explanation!
loops
Loops in Python are used to repeatedly execute a block of code as long as a certain condition
is met. There are two main types of loops in Python: for loops and while loops.
For Loops
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and
execute a block of code for each item in the sequence.
python
In this example, the for loop iterates over each item in the fruits list and prints it.
The range() function generates a sequence of numbers, which can be used to iterate over a
specific range.
python
for i in range(5):
print(i)
In this example, the for loop iterates over the numbers from 0 to 4 and prints each number.
While Loops
A while loop repeatedly executes a block of code as long as a specified condition is True.
python
while condition:
# Code to be executed while the condition is True
x = 5
while x > 0:
print(x)
x -= 1
In this example, the while loop continues to execute the block of code as long as x is greater
than 0. The value of x is decremented by 1 in each iteration.
Nested Loops
You can also nest loops inside other loops to perform more complex iterations.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
In this example, the outer for loop iterates over the numbers 0 to 2, and for each iteration, the
inner for loop iterates over the numbers 0 to 1. The nested loops print the values of i and j
for each combination.
You can control the flow of loops using the break and continue statements.
python
for i in range(10):
if i == 5:
break
print(i)
In this example, the for loop iterates over the numbers from 0 to 9, but the break statement
causes the loop to exit when i equals 5.
The continue statement is used to skip the current iteration and proceed to the next iteration.
python
for i in range(10):
if i % 2 == 0:
continue
print(i)
In this example, the for loop iterates over the numbers from 0 to 9, but the continue
statement causes the loop to skip the even numbers and print only the odd numbers.
Example Code
python
# While loop
x = 5
while x > 0:
print(x)
x -= 1
# Nested loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
# Break statement
for i in range(10):
if i == 5:
break
print(i)
# Continue statement
for i in range(10):
if i % 2 == 0:
continue
print(i)
Loops are a powerful tool in Python that allow you to repeat actions and automate repetitive
tasks. If you have any specific questions or need further clarification, feel free to ask!
Sure! Let's dive into lists, tuples, sets, and dictionaries in Python. These are all types of
collections that allow you to store and manipulate groups of items. Each of them has its own
unique characteristics and use cases.
Lists
Example:
python
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
# Accessing items
print(fruits[0]) # Output: apple
# Adding items
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
# Removing items
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
# Slicing
print(fruits[1:3]) # Output: ['cherry', 'orange']
Tuples
Example:
python
# Accessing items
print(colors[0]) # Output: red
# But you can create a new tuple that includes the desired changes
new_colors = colors + ("yellow",)
print(new_colors) # Output: ('red', 'green', 'blue', 'yellow')
Sets
Example:
python
numbers = {1, 2, 3, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
# Adding items
numbers.add(6)
print(numbers) # Output: {1, 2, 3, 4, 5, 6}
# Removing items
numbers.remove(3)
print(numbers) # Output: {1, 2, 4, 5, 6}
# Sets do not support indexing or slicing
# print(numbers[0]) # This will raise a TypeError
Dictionaries
Example:
python
# Accessing values
print(student["name"]) # Output: Alice
# Removing items
del(student["age"])
print(student) # Output: {'name': 'Alice', 'is_student': True, 'major':
'Computer Science'}
Summary
Lists are ordered and mutable collections, suitable for storing sequences of items that
can be modified.
Tuples are ordered and immutable collections, suitable for storing sequences of items
that should not be changed.
Sets are unordered and mutable collections of unique items, suitable for storing non-
duplicate elements.
Dictionaries are unordered and mutable collections of key-value pairs, suitable for
storing data that can be quickly accessed via unique keys.
Each of these collections has its own strengths and use cases
string manipulation
String manipulation refers to the process of changing, parsing, or analyzing strings. Here are
some common string manipulation techniques in Python:
Creating Strings
Strings can be created by enclosing characters in single quotes ('), double quotes ("), or triple
quotes (''' or """ for multi-line strings).
python
Accessing Characters
python
text = "Hello"
print(text[0]) # Output: H
print(text[1]) # Output: e
Slicing Strings
python
String Length
python
text = "Hello"
print(len(text)) # Output: 5
String Concatenation
python
text1 = "Hello"
text2 = "World"
result = text1 + ", " + text2 + "!"
print(result) # Output: Hello, World!
String Methods
Changing Case
python
text = "Hello, World!"
print(text.upper()) # Output: HELLO, WORLD!
print(text.lower()) # Output: hello, world!
print(text.title()) # Output: Hello, World!
print(text.capitalize()) # Output: Hello, world!
Stripping Whitespace
python
python
Formatting Strings
You can use f-strings (formatted string literals) or the str.format() method to format
strings.
Using f-strings
python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Using str.format()
python
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Example Code
python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # Using f-strings
print("My name is {} and I am {} years old.".format(name, age)) # Using
str.format()
String manipulation is a powerful tool in Python that allows you to work with and transform
text data effectively
Functions in Python
A function is a block of reusable code that performs a specific task. Functions help to make
your code more organized and modular. Here's how you define and use a function in Python:
Functions are defined using the def keyword, followed by the function name and parentheses
(). Inside the parentheses, you can define parameters. The function body contains the code to
be executed. Here's a breakdown:
python
def function_name(parameters):
# Function body
return value # Optional return statement
Example:
python
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(3, 5)
print(result) # Output: 8
In this example:
def add_numbers(a, b): defines a function named add_numbers with parameters a
and b.
sum = a + b calculates the sum of a and b.
return sum sends the result back to the caller.
add_numbers(3, 5) calls the function with arguments 3 and 5.
Scope in Python
Scope refers to the visibility of variables within different parts of your code. There are four
types of scopes in Python:
1. Local Scope: Variables declared inside a function. They can only be accessed within
that function.
python
def my_function():
local_var = 10
print(local_var)
my_function() # Output: 10
python
def outer_function():
enclosing_var = 20
def inner_function():
print(enclosing_var)
inner_function()
outer_function() # Output: 20
3. Global Scope: Variables declared at the top level of a script or module. They can be
accessed anywhere in the module.
python
global_var = 30
def my_function():
print(global_var)
my_function() # Output: 30
print(global_var) # Output: 30
LEGB Rule
If Python doesn't find a variable in the local scope, it looks in the enclosing scope, then the
global scope, and finally the built-in scope.
python
global_var = 40
def outer_function():
enclosing_var = 50
def inner_function():
local_var = 60
print(local_var) # Output: 60 (Local)
print(enclosing_var) # Output: 50 (Enclosing)
print(global_var) # Output: 40 (Global)
inner_function()
outer_function()