Basic Concepts of Python

Mannan Ul Haq
0

Python Syntax:

Python commands can be run directly from the Command Line Interface:

print("Hello, World!")

Explanation of the code:

The command 'print()' is a built-in Python function that displays the specified message to the screen. The message can be a string or any other kind of data. 

Note: Python statements do not end in a semicolon. The end of a line is the same as the end of a statement.


Python Indentation:

In Python, indentation is used to define a block of code. Unlike other programming languages that use braces '{}' to define blocks of code, Python uses indentation, making the code easier to read and understand.

Whitespace at the beginning of a line is important. This can be a tab or spaces (typically 4). In Python, one or more spaces or tabs at the beginning of a line is called indentation. All statements with the same distance to the right belong to the same block of code.

Consider the following example:

if 5 > 2:
    print("Five is greater than two!")

Python enforces strict indentation rules. If the indentation is not consistent, it will result in 'IndentationError'.


Output in Python:

In Python, the 'print()' function is used to output data to the standard output device (screen). It's one of the most basic functions in Python, commonly used to output messages and check your code's functionality.

Note: The 'print()' function in Python adds a newline character by default.

Here is an example:

print("Hello, Python learners!")
print("Welcome to CodeTechMentor!")

Output:

Hello, Python learners!
Welcome to CodeTechMentor!


Comments in Python:

Comments in Python are lines that are not executed by the interpreter. They're essential for making your code more readable to others (or even to yourself, when you look back at it later). Python supports two types of comments:

Single-line comments:

Start with '#' and continue until the end of the line. Anything following '#' on the same line is considered a comment.

# This is a single-line comment.
print("Hello, World!") # This is a comment, too!

Multi-line comments:

While Python doesn't formally support multi-line comments, a common practice is to use triple quotes (''' or """), typically used for multi-line strings or docstrings, to create multi-line comments.

'''
This is a multi-line comment.
It can span across multiple lines.
print("This line is commented out.")
'''
print("Hello, World!")


Data Types in Python:

In Python, data types define the type of data that a variable can hold. Some common built-in data types in Python include:

Numeric Types:

Data Type Size (in bytes) Description
int 4 The `int` data type can store whole numbers from -2,147,483,648 to 2,147,483,647.
float 4 The `float` data type can store fractional numbers from 3.4e−038 to 3.4e+038. Sufficient for storing 6 to 7 decimal digits.
complex 8 The `complex` data type is used to represent complex numbers in the form `a + bj`, where `a` and `b` are real numbers, and `j` represents the imaginary unit.

Sequence Types:

Data Type Size (in bytes) Description
str Varies The `str` data type is used to store a sequence of characters (text). String values must be surrounded by single quotes or double quotes.
list Varies The `list` data type is used to store a collection of items in an ordered sequence. Lists can contain elements of different data types and are mutable (can be changed).
tuple Varies The `tuple` data type is similar to a list, but it is immutable (cannot be changed after creation). It is defined using parentheses instead of square brackets.

Mapping Type:

Data Type Size (in bytes) Description
dict Varies The `dict` data type is used to store key-value pairs. Each item in a dictionary has a key and a corresponding value. Dictionaries are mutable.

Set Types:

Data Type Size (in bytes) Description
set Varies The `set` data type is used to store a collection of unique items, where duplicates are not allowed. Sets are mutable and unordered.
frozenset Varies The `frozenset` data type is similar to a set, but it is immutable (cannot be changed after creation).

Boolean Type:

Data Type Size (in bytes) Description
bool 1 bit The `bool` data type is used to store only two possible values: `True` and `False`. This data type is used for simple flags that track true/false conditions.

Binary Types:

Data Type Size (in bytes) Description
bytes Varies The `bytes` data type is used to store sequences of bytes. Bytes are immutable and often used to handle binary data.
bytearray Varies The `bytearray` data type is similar to `bytes`, but it is mutable (can be changed).

None Type:

Data Type Size (in bytes) Description
None 0 The `None` data type represents the absence of a value or a null value. It is often used as a placeholder or to indicate that a variable has no value assigned.



Variables in Python:

In Python, a variable is a named location used to store data in memory. A variable is created the moment you assign a value to it. You don't need to declare its data type because Python is dynamically-typed, meaning the interpreter infers the data type based on the value you assign.

x = 5
y = "Hello, World!"
print(x) # Outputs: 5 
print(y) # Outputs: Hello, World!

In this example, we declare two variables called `x` and `y` of type `int` and `str`.

If you assign a new value to a variable that already has a value, the previous value will be overwritten:

x = 5  # x is assigned the value 5
x = 10  # The value of x is updated to 10
print(x)  # Outputs 10

Python also allows you to assign values to multiple variables in one line:

a, b, c = 5, 3.2, "Hello"

And you can even assign the same value to multiple variables:

x = y = z = "same"

Other Data Types in Pyhton:

myInt = 10
myFloat = 3.14
myStr = "Hello, Python!"
myBool = True
myList = [1, 2, 3]
myTuple = (4, 5, 6)
myDict = {'name': 'John', 'age': 25}

NOTE: Don't worry if you didn't understand any of the above data types. We will discuss them in detail in later tutorials. (alert-success)


Identifiers in Python:

An identifier in Python is a name used to identify a variable, function, class, module, or other object. Here are a few rules you should follow when naming your identifiers:

  • Identifiers can include letters, digits, and underscores (_).
  • The first character must be a letter or an underscore.
  • Identifiers are case-sensitive (`age` and `Age` are different).
  • Names cannot contain special characters like !, #, %, etc.
  • Reserved keywords cannot be used as identifiers.


Displaying Variables in Python:

In Python, the print() function is used to display output to the console. We can use it to print strings, variables, and other data types. For concatenating variables with strings, Python provides comma ',' operator:

The comma ',' operator can be used to print multiple items in a single print() function. The items can be of different types and are automatically converted to strings. Each item is separated by a space.

Example:

name = "Alice"
age = 20

print("My name is", name, "and I am", age, "years old.")

Output:

My name is Alice and I am 20 years old.


Escape-Characters in Python:

In Python, escape characters are special characters that are used to represent non-printable or reserved characters within a string. They begin with a backslash \ followed by another character. Escape characters allow you to include characters in strings that would otherwise be difficult or impossible to represent directly.


Escape-CharacterExplanation  Representation
New Line    To Insert a new Line  \n
Tab    To Insert a Tab  \t
Space    To Insert a Space  Empty Space
Double Quote    To Insert a Double Quote Character  \"
Backslash    To Insert a Backslash Character  \\


The use of escape-characters improves the organization and readability of your code.


Python Casting:

Just like other programming languages, Python also allows you to convert one data type into another. This can be done with built-in functions or implicitly in some cases.

1. Implicit Conversion (Automatic Conversion):

Python automatically converts one data type to another without involving any user intervention. This is called implicit type conversion or type promotion. This process doesn't throw any error if we try to perform operations on similar or compatible data types.

Example of Implicit Conversion:

num_int = 123  # An integer assignment
num_flo = 1.23  # A floating point

num_new = num_int + num_flo

print("Value of num_new:", num_new)
print("datatype of num_new:", type(num_new))

In the above code, 'num_int' is an integer type variable and 'num_flo' is a floating-point type variable. In line 4, an addition operation between 'num_int' and 'num_flo' is performed, which results in a floating-point number. Here, Python implicitly converts integer to float before performing addition operation. Hence, the result 'num_new' is a floating point number.

2. Explicit Conversion (Type Casting):

In Python, you can convert data types with predefined functions such as 'int()', 'float()', 'str()', etc. This process is also known as typecasting because the user casts (change) the data type of the objects.

Example of Explicit Conversion:

num_int = 123     # An integer assignment
num_str = "456"   # A string

# Explicitly convert the string to an integer
num_str = int(num_str) 

print(num_int + num_str)

In the above code, 'num_str' is a string type variable. But we converted this variable into integer by using 'int()' function. Now, Python can add these two variables because they are both of the same type.


User Input in Python:

In Python, you can use the 'input()' function to take input from the user. The 'input()' function reads a line from input (usually user input), converts the input into a string, and returns it.

Example:

print("Enter your name:")
x = input()
print("Hello,", x)

In this example, the program prompts the user to enter their name. The input provided by the user is read using 'input()', and it's stored in the 'x' variable. This value is then printed to the console with a greeting.

If you want to take a number as input and perform mathematical operations, you can use the 'int()' or 'float()' functions to convert the string input to an integer or float, respectively.

Example:

print("Enter a number:")
x = int(input())
print("The square of the number is", x*x)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !