The Wayback Machine - https://web.archive.org/web/20240922224015/https://www.geeksforgeeks.org/python-basics/
Open In App

Learn Python Basics

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

If you want to explore Python beyong its Basics, why not deepen your knowledge with our Master Python: Complete Beginner to Advanced course? This comprehensive course is designed to take you from a beginner to an advanced Python programmer, covering everything from the basics to more complex concepts

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 + b 

sub = a - b 

mul = a * b 

mod = a % b 

p = a ** b 
print(add) 
print(sub) 
print(mul) 
print(mod) 
print(p) 

Output
13
5
36
1
6561

Logical Operators

Python Logical operators perform Logical AND , Logical 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 = 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 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 our course and 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.


Similar Reads

How to Learn Python Basics With ChatGPT
Python is one of the most popular programming languages, known for its simplicity and versatility. Whether you're a complete beginner or an experienced programmer looking to expand your skillset, mastering the basics of Python is essential. In this guide, we'll walk you through the fundamentals of Python programming with the help of ChatGPT. By the
4 min read
Basics Of Python Modules
A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard library modules. Creating our module We will be crea
3 min read
Selenium Python Basics
Selenium is a portable framework for testing web applications. Selenium provides a playback tool for authoring functional tests without the need to learn a test scripting language. Before Going Ahead Please refer to this page if you had not installed Selenium. This article revolves around Locators in Selenium and various strategies. ContentsWebdriv
5 min read
Python 3 basics
Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the very basics of Python programming language . We al
10 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Basics of Discrete Event Simulation using SimPy
SimPy is a powerful process-based discrete event simulation framework written in Python. Installation : To install SimPy, use the following command - pip install simpy Basic Concepts : The core idea behind SimPy is the generator function in Python. The difference between a normal function and a generator is that a normal function uses the "return"
3 min read
Basics of NumPy Arrays
NumPy stands for Numerical Python. It is a Python library used for working with an array. In Python, we use the list for the array but it's slow to process. NumPy array is a powerful N-dimensional array object and is used in linear algebra, Fourier transform, and random number capabilities. It provides an array object much faster than traditional P
5 min read
Django Basics
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a
4 min read
10 reasons to learn Python in 2019
Python is a high-level, interpreted, general-purpose programming language that supports both object-oriented programming and structured programming. It is quite versatile and offers a lot of functionalities using standard libraries which allows the easy implementation of complex applications. Python is also the most popular and fastest growing prog
4 min read
Is it Worth to Learn Python in 2020?
Researches &amp; reports reveal that Python is one of the most preferred languages in this 21st century. The reason behind its back is its simplicity, huge community, and easy inbuilt functions that help in easy learning curves. Though the question depends upon who is asking that i.e. for a beginner learning python makes sense because it's easy to
5 min read
Java vs Python - Which One Should I Learn?
Many times you heard people saying Java is faster than Python or Python is more secure than Java and many other kinds of comparisons between them. In this article, we will explain and differentiate both these languages on a few important factors that will land you to a clear conclusion on which is better and why? First, both languages are general-p
7 min read
Why You Should Learn Python in 2021?
Python is one of those programming languages that has seen tremendous growth in its demand and popularity within the last 4-5 years. Whether we talk about the PYPL index, Stack Overflow, or any other platform - the language is ranking at the top positions among numerous programming languages. However, many individuals believe that these ranking cha
8 min read
How Much Python Should You know To Learn Django?
How much python is required to learn Django?? This question comes to the mind of every beginner and experienced developer who wants to learn Django and build an application in it. No doubt most developers or beginner wants to learn any framework or library as soon as possible. We all want to know the minimum prerequisite that is needed to learn any
6 min read
7 Reasons Why You Should Learn Python in 2022
Believe it or not, Python has become one of the hottest topics in the field of programming in the past few years and has been widely used among big tech giants and developers today. Especially today when it’s all about data in almost every field, Python is giving a glorious touch to data mining, machine learning, and many other fields that were not
7 min read
10 Reasons Why Kids Should Learn Python
In today's digital age, programming has become an essential skill. As technology continues to shape our world, the demand for individuals proficient in coding is increasing. Python, a versatile and beginner-friendly programming language, has emerged as a popular choice for learners of all ages. The increase in demand for Python leads to the reason
7 min read
Top 10 Python Packages to Learn in 2024
Python is one of the most popular programming languages which is used by more than 80% of the developers. Top Python packages offer some amazing features like easy to learn and understand, enhanced security and performance. It consists of modules, packages, and libraries that play a major role in keeping a project sorted and fueling up different pr
6 min read
Best way to learn python
Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time. This article guide to help you start your journey
11 min read
R vs Python: Which is Easier to Learn
Choosing between R and Python for ease of learning depends on your background and what you aim to achieve with the programming language. Both languages have their unique advantages and are preferred for different reasons in the data science community. R vs Python: Which is Easier to LearnDeciding between R and Python? Consider your goals! Python is
5 min read
12 Reasons Why You Should Learn Python (2024)
In the fast-paced world of technology, learning a versatile and in-demand programming language like Python can open doors to numerous opportunities. Python has established itself as a powerhouse in various domains, from web development and data analysis to artificial intelligence and automation. As of 2024, the demand for Python skills continues to
8 min read
How to Learn Python from Scratch in 2024
Python is a general-purpose high-level programming language and is widely used among the developers’ community. Python was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. If you are new to programming and want to learn Python Programming from Scratch, then this complet
15+ min read
How to Learn Python in 21 Days
At present, Python is one of the most versatile and demanded programming languages in the IT world. Statistically, there are around 8-9 Million Python developers across the world and the number is increasing rapidly. Meanwhile, the average salary of an Entry-Level Python Developer in India is around 4-6 LPA , and its rich features such as easier sy
9 min read
7 Best Python Frameworks to Learn in 2024
Python is one of the most lucrative programming languages that is used as the main coding language by most of the developers. It is one of the fastest-growing programming languages that is embedded with extensive libraries and frameworks to fuel up different processes. Popular companies like Oracle, Amazon, Instagram, Google, and many more are usin
6 min read
Top 7 Python ETL Tools To Learn
ETL (extract, transform, load) means extracting data from various sources, transforming that extracted data into a well-organized and readable format via techniques like data aggregation &amp; data normalization, and at last loading (the readable data) into storage systems like data warehouses to gain business insights for better decision-making. N
5 min read
How to Get Regression Model Summary from Scikit-Learn
In this article, we are going to see how to get a regression model summary from sci-kit learn. It can be done in these ways: Scikit-learn PackagesStats model packageExample 1: Using scikit-learn. You may want to extract a summary of a regression model created in Python with Scikit-learn. Scikit-learn does not have many built-in functions for analyz
3 min read
Plot Multinomial and One-vs-Rest Logistic Regression in Scikit Learn
Logistic Regression is a popular classification algorithm that is used to predict the probability of a binary or multi-class target variable. In scikit-learn, there are two types of logistic regression algorithms: Multinomial logistic regression and One-vs-Rest logistic regression. Multinomial logistic regression is used when the target variable ha
4 min read
How to split the Dataset With scikit-learn's train_test_split() Function
In this article, we will discuss how to split a dataset using scikit-learns' train_test_split(). sklearn.model_selection.train_test_split() function: The train_test_split() method is used to split our data into train and test sets. First, we need to divide our data into features (X) and labels (y). The dataframe gets divided into X_train, X_test, y
8 min read
Simple 1D Kernel Density Estimation in Scikit Learn
In this article, we will learn how to use Scikit learn for generating simple 1D kernel density estimation. We will first understand what is kernel density estimation and then we will look into its implementation in Python using KernelDensity class of sklearn.neighbors in scikit learn library. Kernel density estimationA non-parametric method for est
4 min read
Comparing various online solvers in Scikit Learn
Scikit Learn is a popular Python library that provides a wide range of machine-learning algorithms and tools. One of the key features of Scikit Learn is the ability to solve optimization problems using various online solvers. In this article, we will compare some of the most commonly used online solvers in Scikit Learn. What is an Online Solver?An
4 min read
Imputing Missing Values Before Building an Estimator in Scikit Learn
The missing values in a dataset can cause problems during the building of an estimator. Scikit Learn provides different ways to handle missing data, which include imputing missing values. Imputing involves filling in missing data with estimated values that are based on other available data in the dataset. Related topic of concepts:Missing Data: Mis
3 min read
Article Tags :
Practice Tags :