Introduction to Python


Definition of Python:
Python is a high-level, interpreted, and general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability, making it an excellent language for beginners and experienced programmers alike. It is known for its simplicity, versatility, and extensive standard library that provides ready-to-use modules and packages for various tasks.
Variables in Python:
In Python, variables are used to store data values. Unlike some other programming languages, you don't need to declare variables explicitly before using them. The variable's data type is inferred based on the value it holds.
Example:
age = 25
pi = 3.14
name = "John Doe"
numbers = [1, 2, 3, 4, 5]
person = {'name': 'Alice', 'age': 30, 'is_student': True}
Data Type of Python:
Python is a dynamically-typed language, meaning the data type of a variable is determined at runtime. Unlike statically-typed languages, you don't need to explicitly declare the type of a variable before using it. Python supports several built-in data types, including:
Integers: Whole numbers without a fractional component
e.g., 5, -17, 1000
Floating-point numbers: Numbers with decimal points
e.g., 3.14, -0.5, 2.0
Strings: Sequences of characters enclosed in single (' ') or double (" ") quotes
e.g. 'Hello', "Python"
Lists: Ordered collections of items that can be of different data types
e.g. [1, 'apple', True]
Tuples: Similar to lists but immutable, meaning their elements cannot be changed once defined.
e.g. ("apple", "banana", "cherry")
Dictionaries: Key-value pairs enclosed in curly braces { }
e.g., {'name': 'John', 'age': 30}
Operators in Python:
Arithmetic Operators:
+ (addition)
- (subtraction)
\ (multiplication),
/ (division)
% (modulus)
\ (exponentiation)
Comparison Operators:
\== (equal to)
!= (not equal to)
\> (greater than)
< (less than)
\>= (greater than or equal to)
<= (less than or equal to)
Logical Operators:
and (logical AND)
or (logical OR)
not (logical NOT)
Assignment Operators:
\= (assign value)
+= (add and assign)
-= (subtract and assign)
/= (divide and assign)
%= (modulus and assign)
*= (exponentiation and assign).
Loops in Python:
for loop: This loop iterates over a sequence (like a list, tuple, or string) and executes the block of code for each item in the sequence.
while loop: This loop continues to execute the block of code as long as a specified condition is true.
Example Program:
Python program for loop to calculate the sum of the first n natural numbers:
def calculate_sum_of_natural_numbers(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum
n = int(input("Enter a positive integer (n): "))
result = calculate_sum_of_natural_numbers(n)
Subscribe to my newsletter
Read articles from Saurabh Mathuria directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
