Python Impqs
Python Impqs
each serving different purposes. Understanding their differences is crucial for fields like
programming, especially when debugging code, because programming languages are a type of
formal language.
1. Formal Languages
• Structure: They are based on strict syntactic rules, and every statement or command
must follow a well-defined format.
• Examples:
• Characteristics:
2. Natural Languages
• Definition: Natural languages evolve over time and are used for everyday
communication among humans. They are flexible, often ambiguous, and context-
dependent.
• Structure: Natural languages do not have a fixed, rigid structure and often rely on
context, tone, and cultural background for meaning.
• Examples:
• Characteristics:
o Context-sensitive: Meaning can depend on the situation or how the words are
used.
o Tolerates mistakes: Humans can often infer meaning even if the grammar is not
perfect or words are missing.
Key Differences
Aspect Formal Languages Natural Languages
Grammar Strict, fixed, and rigid. Flexible, can evolve over time.
Small mistakes cause errors (e.g., Humans can understand even with
Error Tolerance
missing a semicolon). mistakes in grammar.
2. Error Identification: Debugging requires recognizing that even minor syntax errors (like
missing brackets or incorrect indentation) can cause major issues in formal languages.
Understanding that there’s no room for flexibility or ambiguity in formal languages helps
identify these problems quickly.
4. Ambiguity: In natural languages, the same word can have multiple meanings. In formal
languages, there is no room for multiple interpretations; hence, debugging is often
about finding the exact point where the rules were violated.
2.)
Variables in Python
A variable in Python is a symbolic name that refers to a memory location where a value is
stored. Variables are used to store data that can be manipulated throughout a program. Python
is a dynamically typed language, meaning you don’t need to declare the type of a variable when
you create it—Python infers the type based on the value you assign.
Example:
python
Copy code
x = 10 # x is an integer variable
1. Dynamically Typed: You don’t need to declare the type of a variable in Python.
o Example:
python
Copy code
2. No Explicit Declaration: Unlike other languages like C or Java, you don’t need to
declare variables before using them in Python.
3. Mutable and Immutable Types: Variables in Python can refer to data types that are
mutable (can be changed, e.g., lists, dictionaries) or immutable (cannot be changed,
e.g., integers, strings, tuples).
Variables vs Constants
A constant is a value that does not change throughout the execution of the program. Python
does not have a built-in constant feature like some other programming languages (e.g., const in
C++ or final in Java), but by convention, we write constants in uppercase to indicate that they
shouldn’t be modified.
python
Copy code
radius = 5 # Variable
Python has a set of reserved words or keywords that have predefined meanings and cannot be
used as variable names. These keywords serve as commands or syntactical structures in the
language, and using them for variable names would result in a syntax error.
python
Copy code
False, None, True, and, as, assert, async, await, break, class, continue,
def, del, elif, else, except, finally, for, from, global, if, import,
in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
Example:
python
Copy code
python
Copy code
count = 10
condition = True
python
Copy code
circumference = 2 * PI * radius
length = 15
width = 10
Important Points:
1. Variables are symbolic names for data that can change during program execution.
3. Keywords are reserved words in Python and cannot be used as variable names.
4. Python’s flexibility with variable types allows for fast prototyping, but you need to be
careful with naming and type assignments to avoid confusion, especially when
debugging.
3.)
Python provides several types of operators that allow for performing various operations on
values or variables. These operators can be classified into different categories based on the
type of operation they perform.
1. Arithmetic Operators
+ Addition 5+2→7
- Subtraction 5-2→3
* Multiplication 5 * 2 → 10
/ Division 5 / 2 → 2.5
** Exponentiation 5 ** 2 → 25
Example:
python
Copy code
a = 10
b=3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
These operators are used to compare two values and return a Boolean result (True or False).
== Equal to 5 == 5 → True
Example:
python
Copy code
a = 10
b=3
3. Logical Operators
Logical operators are used to combine conditional statements and return Boolean results (True
or False).
and Returns True if both conditions are True (5 > 2 and 10 > 5) → True
not Reverses the result; returns True if condition is False not (5 > 2) → False
Example:
python
Copy code
a = True
b = False
4. Assignment Operators
5. Bitwise Operators
` ` OR
^ XOR a^b
~ NOT ~a
6. Membership Operators
not in Returns True if a value is not present in the sequence "b" not in "apple" → True
Operator precedence determines the order in which operators are evaluated in expressions.
Operators with higher precedence are evaluated before operators with lower precedence.
Order of Operations:
1. Parentheses: ()
2. Exponentiation: **
8. Logical OR: or
python
Copy code
result = 10 + 2 * 3 ** 2
print(result) # Output: 28
# Breakdown:
# 3 ** 2 = 9 (Exponentiation first)
# 2 * 9 = 18 (Multiplication second)
# 10 + 18 = 28 (Addition last)
4.)
Python provides many powerful operations and methods to manipulate strings. Strings in
Python are immutable, which means that once they are created, they cannot be modified.
However, you can perform various operations like concatenation, repetition, slicing, and use
built-in string methods to work with strings.
Let's go over the most common string operations in Python with examples:
1. String Concatenation
Concatenation is the operation of joining two or more strings together using the + operator.
Example:
python
Copy code
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Adding a space between the words
2. String Repetition
Example:
python
Copy code
3. String Slicing
String slicing allows you to extract a substring from a string by specifying a start and end index.
The syntax is string[start:end].
Example:
python
Copy code
4. String Methods
.upper()
python
Copy code
str1 = "hello"
.lower()
Copy code
str1 = "HELLO"
.replace(old, new)
python
Copy code
.strip()
python
Copy code
.split()
python
Copy code
.join()
python
Copy code
String operations follow the normal precedence of Python operators. For example, in complex
expressions, parentheses control the order of operations, while multiplication (*) and addition
(+) operate as they do for numbers but with strings.
Example:
python
Copy code
5.)
Conditional statements are used to control the flow of a program by executing certain blocks of
code only if specified conditions are met. Python provides several conditional statements,
including if, elif, and else, that allow the program to make decisions based on Boolean
expressions (conditions that evaluate to True or False).
1. The if Statement
The if statement evaluates a condition. If the condition is True, the indented block of code under
it is executed. If the condition is False, Python skips that block.
Syntax:
python
Copy code
if condition:
Example:
python
Copy code
x = 10
if x > 5:
The elif statement allows you to check multiple conditions in sequence. If the first condition is
False, Python checks the next elif condition, and so on.
Syntax:
python
Copy code
if condition1:
elif condition2:
Example:
python
Copy code
x = 10
if x > 15:
elif x > 5:
The else block is executed when none of the if or elif conditions are True. It acts as the "catch-
all" when all other conditions fail.
Syntax:
python
Copy code
if condition1:
elif condition2:
else:
Example:
python
Copy code
x=3
if x > 10:
elif x > 5:
else:
4. Nested Conditionals
Conditional statements can be nested inside other if statements to allow for more complex
decision-making.
python
Copy code
x = 10
y=5
if x > 5:
if y > 5:
else:
print("x is greater than 5, but y is not") # Output: x is greater than 5, but y is not
Logical operators (and, or, not) are used to combine multiple conditions into one.
python
Copy code
x = 10
y=5
print("At least one of x or y is greater than 5") # Output: At least one of x or y is greater than 5
else:
python
Copy code
age = 20
has_ticket = True
if has_ticket:
else:
else:
• If age is greater than or equal to 18, the inner if checks if the person has a ticket.
• If both conditions are satisfied, the person is allowed to enter the event.
• If the person doesn't have a ticket but is old enough, they are not allowed to enter.
Python provides two types of loops for iterating over code blocks: while and for loops. Both are
useful but differ in their structure and typical use cases.
Condition Continues as long as a specified condition Iterates over a sequence (like a list,
Type is True. range, or string).
Potential Can lead to infinite loops if the condition Typically safer because it iterates over
Risks is never met. a defined sequence.
Loop Can have complex conditions to control Typically simpler and more readable
Structure loop flow. for fixed iterations.
May be less efficient if the loop condition More efficient when working with
Efficiency
isn't well-defined. sequences (like lists or ranges).
A while loop repeatedly executes a block of code as long as a specified condition evaluates to
True. It is typically used when the number of iterations is not known beforehand and depends on
a condition being met.
Syntax:
python
Copy code
while condition:
# code block
Example:
python
Copy code
i=1
while i <= 5:
print(f"Iteration {i}")
i += 1
Output:
Copy code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
• Use Case: A while loop is useful when the number of iterations is unknown or when you
want the loop to stop based on dynamic conditions, such as user input or real-time
data.
python
Copy code
user_input = ''
A for loop is used to iterate over sequences such as lists, tuples, strings, or ranges. It is generally
more predictable because the number of iterations is usually known.
Syntax:
python
Copy code
# code block
Example:
python
Copy code
print(f"Iteration {i}")
Output:
Copy code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
• Use Case: A for loop is ideal for iterating over a sequence when you know in advance
how many times the loop should run, or when you need to access elements from a
sequence.
python
Copy code
print(f"Buying {item}")
o For example, processing user input until they provide valid input or a loop that
waits for real-time events.
python
Copy code
n=1
n += 1
print(f"The first number greater than 100 that is divisible by 7 is: {n}")
python
Copy code
print(f"Number: {num}")
In more complex scenarios, you can nest while loops inside for loops (or vice versa) for more
advanced control flow.
python
Copy code