Computer Science

Python study note: Basic Expressions

Study note 2:

Python, with its clean syntax and versatility, has become one of the most popular programming languages in the world. Whether you’re just starting out or looking to refresh your skills, understanding the fundamentals is key. In this study note, we’ll dive into the basics of Python, covering everything from variables and expressions to conditional statements and logical operators.

1. Getting Started: Variables, Expressions, and Statements

Values and Types: Python deals with different types of data, including strings (text), integers (whole numbers), floats (decimal numbers), and Booleans (true or false values).

Variables: In Python, variables are used to store values. They are assigned using the syntax variable = value.

Python Keywords: Python comes with a set of reserved words known as keywords, which have special meanings and cannot be used as variable names. These include and, if, else, for, while, and many more.

Operators: Python supports various operators for performing mathematical operations, such as addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**).

PEMDAS: The order of operations in Python follows the acronym PEMDAS, which stands for Parentheses, Exponents, Multiplication and Division (from left to right), and Addition and Subtraction (from left to right).

2. Input and Output

Input Function: The input() function allows you to prompt the user for input. It returns the input as a string, which can be stored in a variable for further processing.

Type Conversion: Python provides functions like int(), float(), and str() to convert values from one type to another. This is useful when performing operations or concatenating strings of different types.

F-Strings: F-strings (formatted strings) provide a convenient way to embed variables and expressions within strings. They are denoted by the prefix f and allow for easy interpolation of values.

3. Conditional Statements and Logical Operators

Boolean Expressions: Boolean expressions evaluate to either True or False. They are often used in conditional statements to control the flow of a program.

Conditional Statements: Python supports if, else, and elif (else if) statements for executing different blocks of code based on certain conditions.

Nested Conditions: Conditional statements can be nested within one another to handle more complex logic.

Chained Conditions: Chained conditions allow you to check multiple conditions in sequence using if, elif, and else blocks.

Logical Operators: Python provides logical operators such as and, or, and not for combining multiple conditions.

Try and Except: The try and except blocks are used for handling exceptions (errors) in Python code. They allow you to gracefully handle errors and continue execution.

Leave a Reply