Python Basics: Operators and Control Flow
Python Basics: Operators and Control Flow
Arithmetic operators perform basic mathematical operations such as addition and exponentiation. An example is 'a + b', which would be 13 for a = 10 and b = 3. Assignment operators, on the other hand, modify the value of a variable using another value, such as 'a += 5' which updates 'a' to 15 .
A year is a leap year in Python if it is divisible by 4 but not by 100, unless it is divisible by 400. For instance, 2024 satisfies 'year % 4 == 0 and year % 100 != 0', making it a leap year .
The 'in' operator checks if a sequence contains an element. For instance, 'a in [5, 15]' evaluates to True if 'a' is either 5 or 15 .
Control flow statements like 'if-elif-else' guide the execution path based on conditions, such as turning a number check into printing 'Positive', 'Zero', or 'Negative'. Loops, like a 'for' loop with 'for i in range(3):', iterate over a sequence three times .
Logical operators in Python are used to evaluate expressions and return a Boolean result. The 'and' operator requires both conditions to be true, while the example 'True and False' evaluates to False as one condition is false .
Attempting 's[0] = 'P'' to change a string directly causes an error due to string immutability. To change a string, concatenate: 's = "P" + s[1:]', which correctly modifies 'python' to 'Python' .
A 'for' loop iterates over a fixed sequence, like 'for i in range(3):', which runs three times. Conversely, a 'while' loop continues until a condition changes, as 'while count < 3:' increments 'count' until it ceases to be less than 3 .
In Python, strings are immutable, meaning their characters cannot be changed in place. For example, trying 's[0] = 'P'' will cause an error. To modify a string, a new one must be created, like 's = "P" + s[1:]', which changes 'python' to 'Python' .
Identity operators like 'is' test if two references point to the same object. In the example, 'x is y' evaluates to True because 'x' and 'y' point to the same list object .
Python functions encapsulate code and handle specific tasks, defined using 'def'. Calling 'add_numbers(5, 10)' returns the sum of 5 and 10, which is 15, demonstrating encapsulation and functionality .