🐍 Basics of Python : Syntax, Data Types, Type Casting, Variables, Operators, and More!
Python is known for its simplicity and readability, making it an ideal choice for beginners. In this post, we’ll go through fundamental Python concepts, including data types, variable scope, operators, and a few hands-on examples. If you're just starting out or need a refresher, this guide will get you up to speed!
📝 Python Syntax and Basics
Python has a unique syntax that makes code easy to read. Here are some essential points:
Case Sensitivity: Python is case-sensitive, so
Name
andname
are considered different variables.New Statements: Each statement starts on a new line, making the code easy to follow.
Example:
x = 2
y = 3.14
name = "Krishna"
is_active = True
With Python’s print()
function, you can display multiple values in a formatted way:
print("The value of x is {}, y is {}, name is {}, active status is {}".format(x, y, name, is_active))
# Using f-strings
print(f"The value of x is {x}, y is {y}, name is {name}, active status is {is_active}")
🔍 Data Types in Python
Python supports several basic data types, such as:
int (integer)
float (floating-point number)
str (string)
bool (boolean)
Example:
x = 2
y = 3.14
name = "Krishna"
is_active = True
🔄 Type Casting
Type casting allows you to convert one data type to another, which is essential when dealing with different data formats. Here’s how it’s done in Python:
x = 2
y = float(x) # Converts int to float
print(y) # Output: 2.0
c = 3.14
d = int(c) # Converts float to int
print(d) # Output: 3
x = "123"
f = int(x) # Converts str to int
print(f) # Output: 123
x = 123
s = str(x) # Converts int to str
print(s) # Output: '123'
x = "True"
y = bool(x) # Converts str to bool
print(y) # Output: True
🔍 Type Checking
To check a variable's type, use the type()
function, or verify a specific type with isinstance()
:
a = "True"
x = 4
y = 3.144
z = True
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(a)) # Output: <class 'str'>
print(type(z)) # Output: <class 'bool'>
# Using isinstance
print(isinstance(x, float)) # Output: False
print(isinstance(x, int)) # Output: True
🌐 Scope of Variables in Python
In Python, the scope of a variable refers to where in the code that variable is accessible. Understanding scope is essential to managing variables and avoiding unintended changes to data.
Global vs. Local Scope
Global Scope: Variables declared outside any function are accessible throughout the code, from any function or code block.
codegreeting = "Hello" # Global variable def say_hello(): print(greeting) # Accessing global variable say_hello() # Output: Hello
Local Scope: Variables declared within a function are only accessible within that function. These are known as local variables.
codedef greet(): greeting = "Welcome" # 'greeting' is a local variable print(greeting) # This works fine inside the function greet() # Output: Welcome print(greeting) # Raises an error because 'greeting' is not accessible globally
In the example above, the greeting
variable is defined inside the greet()
function, so it’s only accessible within that function. Trying to access greeting
outside of greet()
will raise a NameError
since it doesn’t exist in the global scope.
🧮 Operators in Python
Python offers several types of operators, including arithmetic, comparison, and logical operators.
Arithmetic Operators
Perform basic math operations like addition, subtraction, multiplication, and division.
a = 4
b = 5
print(a + b) # Output: 9
print(a - b) # Output: -1
print(a * b) # Output: 20
print(a / b) # Output: 0.8
print(a % b) # Output: 4
print(b ** a) # Output: 625 (b raised to the power of a)
Comparison Operators
Comparison operators allow you to compare values:
result1 = (a == b) # Output: False
result2 = (a != b) # Output: True
result3 = (a > b) # Output: False
result4 = (a < b) # Output: True
result5 = (a >= b) # Output: False
result6 = (a <= b) # Output: True
print(result1, result2, result3, result4, result5, result6)
Logical Operators
Logical operators like and
, or
, and not
help in combining conditions:
print((a > b) and (a < b)) # Output: False
print((a > b) or (a < b)) # Output: True
print(not (a > b)) # Output: True
🎉 Real-World Examples
Let's look at two examples using these basics.
1. Discount Calculator
Calculate the discount amount and final price:
original_price = 120.0
discounted_price = 20
discount_amt = (original_price * discounted_price) / 100
final_amt = original_price - discount_amt
print(f"Original price: {original_price}")
print(f"Discount amount: {discount_amt}")
print(f"Final amount: {final_amt}")
2. Age Validator (Voting Eligibility)
Check if a user is eligible to vote:
user_age = int(input("Enter your age: "))
if user_age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
3. Temperature Converter
Convert Celsius to Fahrenheit:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit}")
📌 Wrapping Up
With these Python basics, you’re ready to dive deeper into the language. Practice using these fundamental concepts, and soon you’ll be tackling more complex projects. Whether you're building simple scripts or exploring data science, Python will continue to be your go-to tool.
Subscribe to my newsletter
Read articles from Krishnat Ramchandra Hogale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Krishnat Ramchandra Hogale
Krishnat Ramchandra Hogale
Hi! I’m Krishnat, a Senior IT Associate specializing in Performance Engineering at NTT DATA SERVICES. With experience in cloud technologies, DevOps, and automation testing, I focus on optimizing CI/CD pipelines and enhancing infrastructure management. Currently, I'm expanding my expertise in DevOps and AWS Solutions Architecture, aiming to implement robust, scalable solutions that streamline deployment and operational workflows.