Open In App

Learn Python Basics

Improve
Improve
Like Article
Like
Save
Share
Report

Welcome to Python Basics! This page is your gateway to mastering the fundamentals of Python programming. Whether you’re a newcomer or looking to brush up on your skills, this guide will equip you with the essential knowledge needed to write Python code confidently. Let’s dive in!

What is Python

Python’s simplicity, readability, and versatility make it an excellent choice for beginners and experienced programmers alike. In this article, we’ve covered the basics of Python, from setting up your environment to writing your first program and understanding syntax, control flow, and functions. As you continue your journey with Python Basics, don’t hesitate to explore its vast ecosystem of libraries, frameworks, and tools to unleash its full potential in various domains of programming.

Writing your first Python Program

Here we provided the latest Python 3 version compiler where you can edit and compile your written code directly with just one click of the RUN Button. So test yourself with Python’s first exercises.

Python




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


Output

Hello World! I Don't Give a Bug

Comments in Python

Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Also, Comments enhance the readability of the code and help the programmers to understand the code very carefully.

Python




# sample comment 
# This is Python Comment
name = "geeksforgeeks"
print(name) 


Output

geeksforgeeks

Keywords in Python

Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier.

Keywords

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

Python Variable is containers that store values. Python is not “statically typed”. An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name.

Rules for Python variables

  • A Python variable name must start with a letter or the underscore character.
  • A Python variable name cannot start with a number.
  • A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
  • The reserved words(keywords) in Python cannot be used to name the variable in Python.

Example

Python




# 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

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are classes and variables are instances (objects) of these classes.

Example: This code assigns variable ‘x’ different values of various data types in Python.

Python




x = "Hello World" # string
x = 50  # integer
x = 60.5  # float
x = 3j  # complex
x = ["geeks", "for", "geeks"# list 
x = ("geeks", "for", "geeks"# tuple
x = {"name": "Suraj", "age": 24} # dict
x = {"geeks", "for", "geeks"} # set
x = True  # bool
x = b"Geeks" # binary


Python Input/Output

This function first takes the input from the user and converts it into a string. The type of the returned object always will be <class ‘str’>. It does not evaluate the expression it just returns the complete statement as String, and will print it.

Python




# Python program show input and Output
val = input("Enter your value: "
print(val)


Python Operators

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. In this article, we will look into different types of Python operators.

Arithmetic Operators

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

Precedence of Arithmetic Operators

The precedence of Arithmetic Operators in Python is as follows:

  1. P – Parentheses
  2. E – Exponentiation
  3. M – Multiplication (Multiplication and division have the same precedence)
  4. D – Division
  5. A – Addition (Addition and subtraction have the same precedence)
  6. S – Subtraction

Example

Python




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


Output

13
5
36
1
6561

Logical Operators

Python Logical operators perform Logical ANDLogical OR, and Logical NOT operations. It is used to combine conditional statements.

Python




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


Output

False
True
False

Bitwise Operators

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Python




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

Python Assignment operators are used to assign values to the variables.

Python




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


Output

10
20
10
100
102400

Python If Else

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the if statement to execute a block of code when the if condition is false.

Example 1: Python IF-Else

Python




i = 20
if (i < 15): 
    print("i is smaller than 15"
    print("i'm in if Block"
else
    print("i is greater than 15"
    print("i'm in else Block"
print("i'm not in if and not in else Block"


Output

i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Example 2: Python if-elif-else ladder

Python




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

Python For Loop

Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like String, Tuple, List, Set, or Dictionary. Here we will see a “for” loop in conjunction with the range() function to generate a sequence of numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each number in the sequence, the loop prints its value using the print() function.

Python




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


Output

0
2
4
6
8

Python While Loop

In this example, the condition for while will be True as long as the counter variable (count) is less than 3. 

Python




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


Output

Hello Geek
Hello Geek
Hello Geek

Also See: Use of break, continue and pass in Python

Python Functions

Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Note: There are mainly two types of functions in Python.

  1. Built-in library function: These are Standard functions in Python that are available to use.
  2. User-defined function: We can create our own functions based on our requirements.

Example

Python




# 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)
evenOdd(3)


What’s Next

After understanding the Python Basics, there are several paths you can explore 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.


Last Updated : 28 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads