Python lesson1 for beginner

we will see the basics of python in the following sections:

In Python, data structures are a fundamental concept that refer to ways of organizing and storing data. Some of the simplest and most commonly used data structures in Python are the built-in data types, such as integers, floats, complex numbers, strings, and booleans. These data types are the building blocks for more complex data structures. Here’s an in-depth look at each of these data types:

  1. Integer (`int`)

– Description: An integer is a whole number without a decimal point. In Python, integers are represented by the `int` type.

– Examples:

“`python

  a = 10      # Positive integer

  b = -5      # Negative integer

  c = 0       # Zero

“`

– Characteristics:

– Python supports arbitrarily large integers; there is no upper bound other than memory.

– Integers are immutable, meaning their value cannot be changed once created.

– Operations:

– Arithmetic operations: `+`, `-`, `*`, `//` (integer division), `%` (modulus), “ (exponentiation).

– Comparison operations: `==`, `!=`, `>`, `<`, `>=`, `<=`.

“`python

  x = 5 + 2   # Addition: 7

  y = 5 - 2   # Subtraction: 3

  z = 5 * 2   # Multiplication: 10

  w = 5 // 2  # Integer division: 2

  r = 5 % 2   # Modulus: 1

  p = 5  2  # Exponentiation: 25

“`

 

  1. Float (`float`)

– Description: A float, or floating-point number, represents a number that has a decimal point. It can be used to represent real numbers.

– Examples:

“`python

  pi = 3.14         # Positive float

  negative_float = -2.7   # Negative float

  zero_float = 0.0        # Zero as float

“`

– Characteristics:

– Floats in Python are based on the IEEE 754 double-precision standard, which provides 15-17 significant digits of precision.

– Like integers, floats are also immutable.

– Python automatically converts integer division results to float if needed.

– Operations:

– Similar to integers but includes floating-point division (`/`).

“`python

  x = 5 / 2   # Floating-point division: 2.5

  y = 2.7 + 3.3  # Addition: 6.0

  z = 3.14 * 2   # Multiplication: 6.28

“`

 

  1. Complex Number (`complex`)

– Description: A complex number is a number with both a real and an imaginary part, represented in the form `a + bj` where `a` is the real part and `b` is the imaginary part.

– Examples:

“`python

  c1 = 2 + 3j    # Complex number with real part 2 and imaginary part 3

  c2 = -1.5 + 2.5j  # Complex number with real part -1.5 and imaginary part 2.5

“`

– Characteristics:

– The imaginary part is denoted with a `j` or `J` (instead of `i` which is used in mathematics).

– Python’s `complex` type can handle complex numbers natively.

– Real and imaginary parts can be accessed using the `.real` and `.imag` attributes.

– Operations:

– Arithmetic operations: `+`, `-`, `*`, `/` work with complex numbers.

“`python

  c_sum = (2 + 3j) + (1 - 2j)  # Addition: 3 + 1j

  c_prod = (2 + 3j) * (1 - 2j) # Multiplication: 8 + j

  c_div = (2 + 3j) / (1 - 2j)  # Division: -0.4 + 1.6j

“`

 

  1. String (`str`)

– Description: A string is a sequence of characters enclosed in single (`’`) or double (`”`) quotes. It is used to represent text.

– Examples:

“`python

  s1 = "Hello, World!"

  s2 = 'Python is fun!'

“`

– Characteristics:

– Strings are immutable; once created, their content cannot be changed.

– Supports indexing (`s[0]`), slicing (`s[1:5]`), and various methods like `upper()`, `lower()`, `split()`, `join()`, `find()`, etc.

– Supports concatenation (`+`) and repetition (`*`).

– Operations:

“`python

  greeting = "Hello" + " " + "World!"  # Concatenation: "Hello World!"

  repeated = "A" * 3                   # Repetition: "AAA"

  first_letter = greeting[0]           # Indexing: "H"

  substring = greeting[0:5]            # Slicing: "Hello"

  length = len(greeting)               # Length of string: 12

“`

 

  1. Boolean (`bool`)

– Description: A boolean represents one of two values: `True` or `False`. Booleans are used in conditional statements and expressions.

– Examples:

“`python

  is_python_fun = True

  is_sky_green = False

“`

– Characteristics:

– The `bool` type is a subclass of `int` where `True` is represented as `1` and `False` as `0`.

– Often used in logical expressions, conditional statements, and loops.

– Operations:

– Logical operations: `and`, `or`, `not`.

“`python

  result = True and False  # Logical AND: False

  result = True or False   # Logical OR: True

  result = not True        # Logical NOT: False

“`

 

Summary

– Integers: Whole numbers without a decimal point, immutable.

– Floats: Real numbers with decimal points, support precise arithmetic.

– Complex Numbers: Numbers with real and imaginary parts, useful for scientific computations.

– Strings: Textual data, immutable, supports various methods and operations.

– Booleans: Represents truth values, useful in control flow and logical expressions.

These basic data types are fundamental in Python and are the foundation for more complex data structures and algorithms.

  • Variable, dynamic typing and strong variable

Python is a high-level, dynamically-typed, and strongly-typed programming language. These concepts are fundamental to understanding how Python handles data and variables. Let’s explore each topic in detail:

  1. Variables in Python

– Definition: A variable is a named location in memory used to store data. In Python, variables are created when you assign a value to them.

– Syntax: The syntax for creating a variable in Python is straightforward:

  variable_name = value

– Examples:

  age = 25                 # An integer variable

  name = "Alice"           # A string variable

  temperature = 36.6       # A float variable

  is_sunny = True          # A boolean variable

  complex_number = 3 + 4j  # A complex number variable

 

– Characteristics:

– No need for explicit declaration: Unlike some other programming languages (like C or Java), you do not need to explicitly declare the type of a variable in Python.

– Dynamic Typing: The type of a variable is determined at runtime based on the value assigned to it.

– Case-sensitive: Variable names are case-sensitive. For example, `age` and `Age` are different variables.

– Naming Conventions:

– Variable names should start with a letter (a-z, A-Z) or an underscore (`_`), followed by letters, digits (0-9), or underscores.

– Variable names cannot contain special characters like `@`, `$`, `%`, etc.

– Variable names should be meaningful, descriptive, and follow the `snake_case` convention (e.g., `student_name`, `total_amount`).

 

  1. Dynamic Typing in Python

 

– Definition: Dynamic typing means that the type of a variable is determined at runtime, not in advance. You do not have to specify the data type of a variable; it is inferred from the value assigned to it.

– Examples:

  x = 10          # 'x' is an integer

  x = "Hello"     # Now, 'x' is a string

  x = [1, 2, 3]   # Now, 'x' is a list

– Characteristics:

– Flexibility: Variables can change types as the program executes. This provides great flexibility in programming because you can use the same variable for different types of data at different times.

– Ease of use: You don’t have to worry about defining the type of the variable ahead of time, making Python code easier to write and read.

– Advantages:

– Fewer type declarations: Since types are inferred, there is less boilerplate code.

– Flexibility: Enables writing generic code that can work with any data type.

– Disadvantages:

– Runtime errors: Type errors will only be caught at runtime, not at compile-time, which may lead to bugs that are harder to detect.

– Performance: Dynamic typing can be slower than static typing because type checks occur at runtime.

  1. Strong Typing in Python

– Definition: Strong typing means that even though Python is dynamically typed, it does not implicitly convert between incompatible types. When an operation involves incompatible types, Python raises a `TypeError`.

– Examples:

  a = 5          # An integer

  b = "10"       # A string

  result = a + b # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'

– Characteristics:

– Type Safety: Python enforces type constraints during operations. If you attempt to perform an operation with incompatible types (such as adding an integer to a string), Python will raise an error.

– Explicit Conversion: To combine or operate on different types, you must explicitly convert them using built-in functions like `int()`, `str()`, `float()`, etc.

– Example of Explicit Type Conversion:

  a = 5

  b = "10"

  result = a + int(b)  # Converts 'b' to an integer before addition

  print(result)        # Output: 15
  1. Combining Dynamic and Strong Typing in Python

 

Python combines dynamic and strong typing by allowing variables to change types dynamically but enforcing strict type rules during operations. This combination provides flexibility while maintaining type safety.

– Example:

  x = "Hello"

  print(type(x))  # Output: <class 'str'>

  x = 42

  print(type(x))  # Output: <class 'int'>

  y = "World"

  result = x + y  # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'

Key Points

– Variables: Named references that store data values. Python variables are dynamically typed and do not require type declaration.

– Dynamic Typing: The type of a variable is determined at runtime based on its assigned value, allowing the variable to hold values of different types during execution.

– Strong Typing: Python enforces type constraints and does not implicitly convert incompatible types, helping to prevent unintended errors.

Summary

Python’s use of dynamic typing makes it a flexible and easy-to-use language, especially for rapid development and prototyping. At the same time, its strong typing ensures that operations on variables maintain logical consistency and correctness. Understanding these concepts is essential for writing robust and error-free Python code.

  • Branching: if, elif & else

  • Block and spacing

  • Advance types: lists

  • Loops: For loop, While loop

  • Range function

  • Break and continue statement.

Introducing to basic python codes.

The Following session shows the basic pythons codes which has been run by Jupyter IDE. Jupyter is a python notebook where we can execute the codes. Jupyter notebook is installed by default if you install anaconda package. please see how to install python section.  Google colab provides this feature in the web browser similar to the Jupyter notebook. You can connect these codes in Google colab and run the codes live and see the results.  see the section how to connect to Google colab.
Google colab may not work in phones, preferred to use computer or laptop. The python code block is embedded here in the below section. please scroll through the embedded page to see the complete content.

refer to the link below:

After completing these codes, go through the next topic :  python-lesson2

 

Was this article helpful?
YesNo

1 thought on “Python lesson1 for beginner”

Leave a Comment