We'll like to hear from you Contact Us Message Us!

Python Basics

Learn more about Python. Create projects. Keep up with new Python stuff.
Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated
Welcome to Python Basics! This is where you start your journey to mastering the fundamentals of Python programming. Whether you're new to programming or just want to refresh your skills, this guide will give you the essential knowledge to write Python code with confidence. Let's get started!

What is Python

Python is a great choice for both beginners and experienced programmers because of its simplicity, readability, and versatility. In this article, we've covered the basics of Python, including setting up your environment, writing your first program, and understanding syntax, control flow, and functions. As you continue learning with Python Basics, remember to explore its wide range of libraries, frameworks, and tools. They can help you unlock Python's full potential in different areas of programming.

Writing your first Python Program


print("Hello World! I Don't Give a Bug")

Output

Hello World! I Don't Give a Bug

Python Basics

Comments in Python

Comments in Python are lines in the code that the interpreter ignores during execution. They enhance code readability and help programmers understand the code better.

# This is a sample comment
# This is a Python Comment
name = "Learn Tricking"
print(name)

Output:

Learn Tricking

Keywords in Python

Keywords in Python are reserved words that have special meanings and cannot be used as identifiers (e.g., variable names, function names). These keywords are used to define the syntax and structure of the Python language. Examples of keywords in Python include:

and False nonlocal
as finally not
assert for or
break from pass
class global raise
continue if return
def import True
del is try
elif in while
else lambda with
except None yield

Python Variable

In Python, variables are containers that store values. Unlike statically typed languages, Python variables can hold different types of values at different times. When you assign an object to a variable, the variable acts as a pointer to that object.

Rules for naming variables in Python:

1. Must start with a letter or underscore (_).
2. Cannot start with a number.
3. Can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
4. Variable names are case-sensitive (e.g., `name`, `Name`, and `NAME` are different).
5. Cannot use reserved words (keywords) as variable names.

Example

In the provided Python example, three variables are assigned values of different types: an integer, a floating-point number, and a string. These variables are then printed to the console using the `print()` function.

# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:

45
1456.8
John

Python Data Types

In Python, data types classify data items and determine what operations can be performed on them. Since everything in Python is an object, data types are represented by classes, and variables are instances (objects) of these classes. Python has various built-in data types, including:

1. Integers (int): Whole numbers without a decimal point.
2. Floating-point numbers (float): Numbers with a decimal point or numbers in scientific notation.
3. Strings (str): Ordered sequences of characters enclosed in single, double, or triple quotes.
4. Lists (list): Ordered collections of items, mutable and can contain different data types.
5. Tuples (tuple): Ordered collections of items, immutable once created.
6. Dictionaries (dict): Unordered collections of key-value pairs.
7. Sets (set): Unordered collections of unique items.
8. Booleans (bool): Represents True or False.

Python Basics

These data types determine how data is stored, manipulated, and used in Python programs.

Example

In the provided Python example, the variable `x` is assigned different values of various data types:

x = "Hello World"  # string
print(type(x))  # <class 'str'>

x = 50  # integer
print(type(x))  # <class 'int'>

x = 60.5  # float
print(type(x))  # <class 'float'>

x = 3j  # complex
print(type(x))  # <class 'complex'>

x = ["stephano", "for", "stephano"]  # list
print(type(x))  # <class 'list'>

x = ("stephano", "for", "stephano")  # tuple
print(type(x))  # <class 'tuple'>

x = {"name": "Suraj", "age": 24}  # dict
print(type(x))  # <class 'dict'>

x = {"stephano", "for", "stephano"}  # set
print(type(x))  # <class 'set'>

x = True  # bool
print(type(x))  # <class 'bool'>

x = b"Stephano"  # binary
print(type(x))  # <class 'bytes'>

Each assignment changes the value of `x` and demonstrates different data types in Python, printed using the `type()` function.

Python Input/Output

In the provided Python example, the `input()` function is used to take input from the user, which is then stored in the variable `val`. The `input()` function always returns a string, so even if the user enters a number or any other type of input, it will be treated as a string. The entered value is then printed using the `print()` function.

# Python program to demonstrate input and output
val = input("Enter your value: ")
print(val)

When you run this program, it will prompt you to enter a value. Whatever value you enter will be displayed back to you as output.

Python Operators

In Python, operators are symbols used to perform operations on values and variables. There are several types of operators in Python, including arithmetic, logical, bitwise, and assignment operators.

Arithmetic Operators:

These operators are used for basic mathematical operations like addition, subtraction, multiplication, division, and modulus.

Example:
a = 9
b = 4
add = a + b  
sub = a - b  
mul = a * b  
div = a / b  
mod = a % b  
p = a ** b  
print(add)  
print(sub)  
print(mul)  
print(div)  
print(mod)  
print(p)

Output:

13
5
36
2.25
1
6561

Logical Operators:

These operators are used to perform logical operations like AND, OR, and NOT.

Example:
a = True
b = False
print(a and b)  
print(a or b)  
print(not a)

Output:

False
True
False

Bitwise Operators:

These operators are used to perform bitwise operations on binary numbers.

Example:
a = 10
b = 4
print(a & b)  
print(a | b)  
print(~a)  
print(a ^ b)  
print(a >> 2)  
print(a << 2)

Output:

0
14
-11
14
2
40

Assignment Operators:

These operators are used to assign values to variables.

Example:
a = 10
b = a  
print(b)  
b += a  
print(b)  
b -= a  
print(b)  
b *= a  
print(b)  
b <<= a  
print(b)

Output:

10
20
10
100
102400

Python If Else

The `if` statement in Python executes a block of code if a condition is true. If the condition is false, an optional `else` statement can be used to execute a different block of code. Additionally, the `elif` (short for else if) statement can be used to check multiple conditions.

Example 1: `if-else`

i = 20
if i < 15:
    print("i is smaller than 15")
    print("I'm in the if block")
else:
    print("i is greater than or equal to 15")
    print("I'm in the else block")
print("I'm not in the if or else block")

Output:

i is greater than or equal to 15
I'm in the else block
I'm not in the if or else block

Example 2: `if-elif-else` ladder

i = 20
if i == 10:
    print("i is 10")
elif i == 15:
    print("i is 15")
elif i == 20:
    print("i is 20")
else:
    print("i is not present")

Output:

i is 20

In the `if-elif-else` ladder, only the block corresponding to the first true condition is executed. If none of the conditions are true, the `else` block is executed.

Python For Loop

The `for` loop in Python is used for sequential traversal, iterating over an iterable like a string, tuple, list, set, or dictionary. In this example, we use the `range()` function to generate a sequence of numbers starting from 0, up to (but not including) 10, with a step size of 2. For each number in the sequence, the loop prints its value using the `print()` function.

Example:
for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

In this loop, `i` takes on the values 0, 2, 4, 6, and 8 in each iteration, and these values are printed to the console.

Python While Loop

In the provided Python example, a `while` loop is used to repeatedly execute a block of code as long as the condition `count < 3` is true. The `count` variable is initialized to 0, and with each iteration of the loop, it is incremented by 1. The loop prints "Hello Geek" three times because the condition becomes false after the third iteration.

Example:

# Python program to illustrate while loop
count = 0
while count < 3:
    count = count + 1
    print("Hello Stephano")

This will output:

Hello Stephano
Hello Stephano
Hello Stephano

In this example, the `while` loop executes three times, printing "Hello Stephano" in each iteration, until the condition `count < 3` is no longer true.

Python Functions

In Python, a function is a block of code that performs a specific task. The main purpose of a function is to group together a set of statements that are commonly or repeatedly used, allowing you to reuse the code without rewriting it. Functions can also accept inputs (arguments) and return outputs.

Here's an example of a simple function that takes two arguments and returns their sum:

def add_numbers(a, b):
    """This function adds two numbers."""
    sum = a + b
    return sum

# Call the function
result = add_numbers(5, 3)
print(result)  # Output: 8

In this example, `add_numbers` is a function that takes two arguments (`a` and `b`), calculates their sum, and returns the result. The function is defined using the `def` keyword, followed by the function name and its parameters in parentheses. The indented block of code following the colon is the body of the function. The `return` statement is used to return a value from the function.

You can call the function by using its name followed by parentheses containing the arguments you want to pass to it. The result of the function call is stored in the `result` variable and then printed to the console.

In Python, there are two main types of functions:

1. Built-in library functions: These are standard functions in Python that are available for use without the need for explicit declaration. Examples include `print()`, `len()`, `type()`, etc.

2. User-defined functions: These are functions created by the user based on their requirements. Users can define their own functions using the `def` keyword.

Here's an example of a simple user-defined function to check whether a number is even or odd:

# A simple Python function to check whether x is even or odd
def evenOdd(x):
    if x % 2 == 0:
        print("even")
    else:
        print("odd")

# Driver code to call the function
evenOdd(2)  # Output: even
evenOdd(3)  # Output: odd

In this example, `evenOdd` is a user-defined function that takes a single argument `x`. It checks if `x` is divisible by 2 (i.e., even) and prints "even" if it is, otherwise it prints "odd". The function is then called with different values to demonstrate its usage.

What’s Next

After grasping the Python Basics, you can explore several paths to further enhance your skills and delve deeper into the language:

1. Continuous Python Learning: Python is a vast language with constantly evolving features and best practices. Stay updated with the latest developments by reading blogs, following influential developers on social media, attending conferences, and taking online courses or tutorials.

2. Advanced Python Concepts: Dive into more advanced topics such as decorators, generators, context managers, and metaprogramming. Understanding these concepts will give you a deeper understanding of Python’s capabilities and help you write more efficient and elegant code.

3. Python Packages and Frameworks: Python has a rich ecosystem of libraries and frameworks tailored for various domains. Depending on your interests, you can explore web development with frameworks like Django or Flask, data analysis and visualization with libraries like Pandas and Matplotlib, machine learning and artificial intelligence with TensorFlow or PyTorch, or automation with libraries like Selenium or BeautifulSoup.

4. Build Python Projects: Apply your newfound knowledge by working on real-world projects. Whether it’s building a web application, developing a machine learning model, automating repetitive tasks, or creating a game, projects provide valuable hands-on experience and help solidify your understanding of Python concepts.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.