Learning Python fundamentals from basics to practical

By Abhinash Jena on December 10, 2024

Python is a high-level, versatile, and beginner-friendly programming language popularly used to teach computers and machines how to think. Python makes this process as simple and beautiful as writing a story. Python’s rise is a story of democratizing technology and making programming more accessible. If you’re used to analyzing text and understanding subtle communicative structures, you’ll appreciate how Python communicates instructions elegantly and clearly. As the world becomes increasingly data-driven and digital, this Python fundamentals article represents a form of “digital literacy”.

Learning Python is like learning a new language that helps to understand and interpret an increasingly technological world. In the English language, syntax refers to the structure of sentences.

EXAMPLE

In English, “The dragon sleeps” makes sense, but “Sleeps dragon the” does not.

Similarly, Python has its own set of rules for writing instructions. Python’s syntax is designed to be simple and clear, making it one of the most beginner-friendly programming languages.

Learning fundamental programming rules

In Python, parentheses ( ) and quotation marks " " play vital roles in how instructions are written for the computer. Parentheses are like command helpers. They hold information or instructions for a specific Python function.

print("Welcome to Python!") 
Welcome to Python! 

The print() function is like asking Python to “say” something. Everything inside the quotation marks will appear as an output. Print is the function, and the information to process is between the parentheses ( ). Text between quotation " " marks is a string that can represent words, sentences, or any characters to display or manipulate.

While print() is for output, input() is for asking for information from the program user. It allows the program to receive information directly from the user. Think of print() as speaking and input() as listening. Just like a conversation where one person speaks (output) and another listens (input).

name = input() 
print("Hello, " + name)

>> WORLD
Hello, WORLD

Furthermore, in the above example, the information entered by the user was assigned to a variable which was further used in the print function for output. The name is a variable that stores the information “WORLD” as a string. Variables make programming dynamic and flexible. Instead of repeating values, variables are used to store and reuse them in an iterative process. Think of it as a labelled jar on a shelf that can keep a value, like a number, word, or anything else. While other programming languages like Java require explicit declarations of variables beforehand, however in Python variables are dynamically typed. Python figures out the type automatically based on the value entered. Unlike others, Python also allows one to change a variable’s type simply by assigning a new value.

Moreover, in Python, the indentation i.e. the space or a tab at the beginning of some lines of code, is not optional; it’s mandatory.

name = input("Enter name: ")
if name == "Project Guru": 
  print("Welcome back " + name + ".")
  print("Let’s finish the Python module.")
else :
  print("Hello, " + name)
>>Enter name: Project Guru
Welcome back Project Guru.
Let’s finish the Python module.

The indented lines belong to the if block. It tells Python how the code is structured. Without it, Python cannot understand which parts of the code belong together. Python uses indentation to define blocks of code.

TIP

Python is one of the few programming languages where indentation isn’t just style but a rule.

Blocks of code are parts of the program that belong together, like instructions inside a condition or a loop. Python also distinguishes between uppercase and lowercase letters. In programming, a single misplaced character or case can break the entire program.

EXAMPLE

Name and name are treated as two different variables, but Print() is not different from print().

Importance of Python Data Structures

Python provides several data structures to organize, store, and manipulate data. While programming, different data structures solve specific challenges in organizing data. Keep in mind that no single data structure will be able to solve all problems. Each structure has its strengths and limitations.

To store, multiple items in a variable that can be changed when needed a flexible data structure like Lists is required. A Python List is a collection of items stored in a specific order that can be modified when needed.

x = [25, 26, 24, 27, 23] 
x.append(28)
print(x)
[25, 26, 24, 27, 23, 28]

The only limitation with lists is that searching for specific items in a list is slow. To quickly look up specific items from a group of information use dictionaries. Information in a dictionary is indexed with a key. Thus, it makes it easier and simpler to look up information from a dictionary.

age = {
 "Ram": 22,
 "Kapil": 25,
 "Chetan": 23
}
Print(age["Chetan"])
23

The indexes of a dictionary should be unique. When a value is added to an existing index of a dictionary, the old value will be replaced.

ages = { 
 "Ram": 22,
 "Kapil": 25,
 "Chetan": 23,
 "Ram": 26
}
print(age["Ram"])
26 

While lists can have unindexed duplicate values, dictionaries can only have uniquely indexed values. Similarly, Python Sets can also be used to create a unique unindexed group. Sets are also used for mathematical set operations.

fruits = ["apple", "grape", "mango", "apple"]
print(fruits)
fruits = {"apple", "grape", "mango", "apple"}
print(fruits)
['apple', 'grape', 'mango', 'apple'] 
{'mango', 'apple', 'grape'}

To avoid accidental modification of List values, use Tuples. They are like sealed, unchangeable containers. Once created, they cannot be modified. Tuples are immutable, faster and use less memory than lists.

colors = ("red", "green", "blue") 
colors[3] = "black"
TypeError: 'tuple' object does not support item assignment 

Here is a practical decision-making framework for choosing structure:

  • To modify values, create a List.
  • For a key-based lookup create a Dictionary.
  • For unique elements use a Set.
  • For a fixed and protected group create a Tuple.

Arithmetic operators in Python

Arithmetic operators are symbols used to perform mathematical operations on values or variables. They are fundamental to any programming language and are widely used in calculations, data analysis, game development, and problem-solving.

OperatorSymbolExampleExplanationResult
Addition + 5 + 3 Adds two values. 8
Subtraction 10 – 4Subtracts the second value from the first. 6
Multiplication * 7 * 2 Multiplies two values. 14
Division / 8 – 2Divides the first value by the second, returning a float. 4
Floor Division // 9 // 2 Divides and returns the integer part (truncates decimals). 4
Modulus % 10 % 3 Returns the remainder of the division of two numbers. 1
Exponentiation ** 2 ** 3 Raises the first value to the power of the second value. 8
Arithmetic operators commonly used in Python programming

The arithmetic operators make codes concise and efficient, by reducing the need for complex logic in simple tasks.

Essential built-in Python functions to know

Apart from print() & input(), Python also comes equipped with many other built-in functions that make programming easier. These functions perform common tasks and knowing them early provides the tools to write a functional and dynamic program right from the start.

Measuring length

The len() function returns the number of items in a string, list, or other data structure.

name = input() 

length = len(name)

print("The length of " + name + " is " + str(length))
The length of Python is 6
TIP

In the line print("The length of " + name + " is " + str(length)), the str(length) converts the numerical length into a string so it can be combined with the text. It can also be written with use an f-string print(f"The length of {name} is {length}"). The f-string provides a cleaner way to embed variables directly within strings.

Checking data type and conversion

The type() function tells the data type of a variable or value. Python might seem to handle things automatically, but understanding data types is crucial for ensuring accurate calculations.

x = 10 
y = "5"
print(type (x), type(y))
<class 'int'> <class 'str'> 
print(x + y) 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

Treat data types like different objects that have their own properties, strengths, and nuances.

print(x + int(y)) 
15 

The int() function in the above example converts the string value into an integer value for the mathematical operation. Similarly, below is two other functions that are essential for type conversion:

  • Float() converts to a floating-point number such as a decimal value (e.g. 1.50).
  • Str() converts to a string.

Absolute Value

The abs() function returns the mathematical absolute (non-negative) value of a number. It helps in error margin and variance calculations by providing consistent positive values.

current_location = -10 
target_location = 5
distance = abs(current_location - target_location)
print("Distance: " + distance)
Distance: 15

Rounding Numbers

The round() function rounds a number to the nearest integer or specified decimal place.

print(round(4.6))
5
print(round(4.123, 2)) 
4.12

Finding Extremes

  • max() returns the largest value in a list or set of numbers.
  • min() returns the smallest value.
n = [10, 20, 5, 8] 
print(max(n))
print(min(n))
20
5

Exploring other functions

  • help() displays documentation for any function, module, or object.
  • dir() lists available attributes and methods for an object.

These are your best friends when learning and exploring new concepts in Python.

Exercise: Build a simple grade calculator in Python

Create a program that accepts student names and their scores for multiple subjects, calculates the total and average score for each student, and determines their grade based on the average. The program will use Python functions, input, lists or dictionaries, arithmetic operators, and a simple grading algorithm.

The program should

  • Accept the number of students from the user.
  • For each student:
    1. Accept the student’s name.
    2. Input scores for 3 subjects (e.g., Math, Science, English).
  • Store the data in a dictionary, where the key is the student’s name, and the value is a list of their scores.
  • Calculate the total and average score for each student.
  • Determine the grade based on the average score using the following criteria:
    1. 90 and above Grade A
    2. 80 to 89 Grade B
    3. 70 to 79 Grade C
    4. Below 70 Grade D
    5. Display the results in a clear and organized format.

Program flow

>>Enter the student's name: Aman
>>Enter the score for Math: 87
>>Enter the score for Science: 56
>>Enter the score for English: 34
Results:
Name: Aman
Total Score: 177.0
Average Score: 59.0
Grade: D

Open Solution

NOTES

I am an interdisciplinary educator, researcher, and technologist with over a decade of experience in applied coding, educational design, and research mentorship in fields spanning management, marketing, behavioral science, machine learning, and natural language processing. I specialize in simplifying complex topics such as sentiment analysis, adaptive assessments and data visualizatiion. My training approach emphasizes real-world application, clear interpretation of results and the integration of data mining, processing, and modeling techniques to drive informed strategies across academic and industry domains.

Discuss

3 thoughts on “Learning Python fundamentals from basics to practical”