[go: up one dir, main page]

0% found this document useful (0 votes)
5 views22 pages

Basics of Python Syntax

Uploaded by

vernyuybresneuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Basics of Python Syntax

Uploaded by

vernyuybresneuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

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

x = 10 # Integer (whole number)


y = 3.14 # Float (decimal number)
name = "Alice" # String (text)
is_active = True # Boolean (True or False)

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")

o For loops: Used to repeat a block of code a certain number of times.

python

for i in range(5):
print(i)

o While loops: Used to repeat a block of code as long as a condition is true.

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

def add(a, b):


return a + b

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

fruits = ["apple", "banana", "cherry"]


print(fruits[0]) # Output: apple

2. Dictionaries: Dictionaries are unordered collections of key-value pairs. They are


created using curly braces {}.

python

student = {"name": "Alice", "age": 25}


print(student["name"]) # Output: Alice

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.

Here's how you can create and use variables:

python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean

In this example:

 x is a variable holding an integer value 10.


 y is a variable holding a float value 3.14.
 name is a variable holding a string value "Alice".
 is_active is a variable holding a boolean value True.

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

2. Float (float): Floats are numbers with a decimal point.

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

fruits = ["apple", "banana", "cherry"]


numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", True, 3.14]

6. Tuple: Tuples are similar to lists, but they are immutable (you cannot change their
content once they are created).

python

coordinates = (10, 20)

7. Dictionary (dict): Dictionaries are unordered collections of key-value pairs. Each key
must be unique, and values can be of any type.

python

student = {"name": "Alice", "age": 25, "is_active": True}

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}

Assigning Values to Variables

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

Variable Naming Rules

 Variable names must start with a letter or an underscore (_).


 The rest of the name can contain letters, numbers, and underscores.
 Variable names are case-sensitive (myVariable and myvariable are different
variables).

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)

Input and Output in Python

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.

Here's an example of how to use the input() function:

python

name = input("Enter your name: ")


print(f"Hello, {name}!")

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.

Here's an example of how to use the print() function:

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.

Using str.format() method:

python

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Using f-strings (formatted string literals):

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))

Example Code for Input and Output

Here's a complete example that demonstrates both input and output in Python:

python

# Taking input from the user


name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert the input to an integer
hobby = input("Enter your favorite hobby: ")

# Displaying output using print function


print(f"\nHello, {name}!")
print(f"You are {age} years old.")
print(f"Your favorite hobby is {hobby}.")

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.

Operator Description Example

+ 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

> Greater than x > y

< Less than x < y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators

Logical operators are used to combine conditional statements.

Operator Description Example

and Logical AND x and y

or Logical OR x or y

not Logical NOT not x

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Description Example

= Assign x = 5

+= Add and assign x += 3

-= Subtract and assign x -= 3

*= Multiply and assign x *= 3

/= Divide and assign x /= 3

%= Modulus and assign x %= 3

//= Floor divide and assign x //= 3

**= Exponent and assign x **= 3


Bitwise Operators

Bitwise operators are used to perform bit-level operations on integers.

Operator Description Example

& Bitwise AND x & y

` ` Bitwise OR `x y`

^ Bitwise XOR x ^ y

~ Bitwise NOT ~x

<< Left shift x << 2

>> Right shift x >> 2

Membership Operators

Membership operators are used to test if a sequence contains a certain value.

Operator Description Example

in Value is in sequence x in y

not in Value is not in sequence x not in y

Identity Operators

Identity operators are used to compare the memory locations of two objects.

Operator Description Example

is Objects are the same x is y

is not Objects are not the same x is not y

Example Code

Here’s an example that demonstrates the use of various operators:

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.

Logical Operators in Conditional Statements

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

Here’s an example that demonstrates various conditional statements:

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.

Here's the basic syntax of a for loop:

python

for item in sequence:


# Code to be executed for each item

Example 1: Iterating over a list


python

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

In this example, the for loop iterates over each item in the fruits list and prints it.

Example 2: Using the range() function

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.

Here's the basic syntax of a while loop:

python

while condition:
# Code to be executed while the condition is True

Example 3: Using a while loop


python

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.

Example 4: Nested loops


python

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.

Break and Continue Statements

You can control the flow of loops using the break and continue statements.

Example 5: Using break

The break statement is used to exit the loop prematurely.

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.

Example 6: Using continue

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

Here’s a complete example that demonstrates various types of loops:

python

# For loop with a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# For loop with range


for i in range(5):
print(i)

# 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!

list, tupples sets dictionaries

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

 Definition: Ordered, mutable (changeable) collection of items.


 Syntax: Defined using square brackets [].

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

 Definition: Ordered, immutable (unchangeable) collection of items.


 Syntax: Defined using parentheses ().

Example:
python

colors = ("red", "green", "blue")


print(colors) # Output: ('red', 'green', 'blue')

# Accessing items
print(colors[0]) # Output: red

# Tuples are immutable, so you cannot add or remove items


# colors.append("yellow") # This will raise an AttributeError

# 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

 Definition: Unordered, mutable collection of unique items.


 Syntax: Defined using curly braces {}.

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

 Definition: Unordered, mutable collection of key-value pairs.


 Syntax: Defined using curly braces {} with a colon : separating keys and values.

Example:
python

student = {"name": "Alice", "age": 25, "is_student": True}


print(student) # Output: {'name': 'Alice', 'age': 25, 'is_student': True}

# Accessing values
print(student["name"]) # Output: Alice

# Adding or updating items


student["major"] = "Computer Science"
print(student) # Output: {'name': 'Alice', 'age': 25, 'is_student': True,
'major': 'Computer Science'}

# 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

single_quoted = 'Hello, World!'


double_quoted = "Hello, World!"
multi_line = """This is a
multi-line string."""

Accessing Characters

You can access individual characters in a string using indexing.

python

text = "Hello"
print(text[0]) # Output: H
print(text[1]) # Output: e

Slicing Strings

You can extract a substring by specifying a start and end index.

python

text = "Hello, World!"


print(text[0:5]) # Output: Hello
print(text[7:]) # Output: World!
print(text[:5]) # Output: Hello
print(text[-6:]) # Output: World!

String Length

Use the len() function to get the length of a string.

python

text = "Hello"
print(len(text)) # Output: 5

String Concatenation

You can concatenate (join) strings using the + operator.

python

text1 = "Hello"
text2 = "World"
result = text1 + ", " + text2 + "!"
print(result) # Output: Hello, World!

String Methods

Python provides many built-in string methods for manipulation.

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

text = " Hello, World! "


print(text.strip()) # Output: Hello, World!
print(text.lstrip()) # Output: Hello, World!
print(text.rstrip()) # Output: Hello, World!

Finding and Replacing


python

text = "Hello, World!"


print(text.find("World")) # Output: 7
print(text.replace("World", "Python")) # Output: Hello, Python!

Splitting and Joining


python

text = "apple, banana, cherry"


fruits = text.split(", ")
print(fruits) # Output: ['apple', 'banana', 'cherry']

separator = " - "


result = separator.join(fruits)
print(result) # Output: apple - banana - cherry

Checking Prefixes and Suffixes

python

text = "Hello, World!"


print(text.startswith("Hello")) # Output: True
print(text.endswith("World!")) # Output: True

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

Here's a complete example demonstrating various string manipulation techniques:

python

text = " Hello, World! "


print(text.strip()) # Output: Hello, World!
print(text.lower()) # Output: hello, world!
print(text.upper()) # Output: HELLO, WORLD!
print(text.replace("World", "Python")) # Output: Hello, Python!
print(text.split(", ")) # Output: ['Hello', 'World!']

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:

Function Definition and Call:

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

2. Enclosing Scope: Variables in the local scope of enclosing functions. A function


inside another function can access variables from its enclosing function.

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

4. Built-in Scope: Names preassigned in Python, such as functions like len() or


print().
python

print(len([1, 2, 3])) # Output: 3

LEGB Rule

Python follows the LEGB rule to resolve the scope of variables:

 Local: Variables defined inside the function.


 Enclosing: Variables in the local scope of enclosing functions.
 Global: Variables defined at the top level of a module.
 Built-in: Predefined names in Python.

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.

Example of LEGB Rule:

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()

You might also like