📓 Python Programming - Python Basics


1. Data Types & Variables

What are Variables? - Variables are containers for storing data values.

  • No need to declare the type explicitly (Python is dynamically typed).

Common Data Types in Python: - str → String (text)

  • int → Integer (whole numbers)

  • float → Floating-point numbers (decimals)

  • complex → Complex numbers (real + imaginary)

  • bool → Boolean (True/False)

  • None → Represents the absence of a value (null-like)

# String
name = "Alice"
print(name,type(name))

# Integer
age = 25
print(age,type(age))

# Float
height = 5.7
print(height,type(height))

# Complex
z = 2 + 3j
print(z,type(z))

# Boolean
is_student = True
print(is_student,type(is_student))

# None Type
data = None
print(data,type(data))

Variable Naming Rules:

  • Must start with a letter or underscore (_)

  • Can contain letters, numbers, and underscores

  • Case-sensitive (name and Name are different)

  • Cannot use Python keywords (like if, for, class)

Naming Conventions:

  • Use descriptive names: user_age instead of a

  • Use snake_case: first_name instead of firstName

  • Constants in UPPER_CASE: MAX_SIZE = 100

# Valid variable names
user_name = "Alice"
age_2024 = 25
_private_var = "hidden"

# Multiple assignment
x, y, z = 1, 2, 3
print(f"x={x}, y={y}, z={z}")

# Same value to multiple variables
a = b = c = 10
print(f"a={a}, b={b}, c={c}")

# Invalid examples (commented out to avoid errors)
# 2name = "Invalid"      # Cannot start with number
# my-name = "Invalid"    # Cannot contain hyphens
# class = "Invalid"      # Cannot use Python keywords
one = 1
two = 2
three = one + two
print(three)

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

2. Input and Output Functions

Output: print() - Used to display information to the console.

Input: input() - Takes input from the user as a string.

# Output
print("Hello, World!")

# Input
name = input("Enter your name: ")
print("Welcome,", name)

Important Note about input():

  • input() always returns a string, even if the user enters a number

  • You need to convert it to the appropriate type if needed

# Input is always a string
user_input = input("Enter a number: ")
print(f"You entered: {user_input} (type: {type(user_input)})")

# Convert to integer for calculations
try:
    number = int(user_input)
    result = number * 2
    print(f"Double of your number: {result}")
except ValueError:
    print("That's not a valid number!")

# Alternative: Convert directly (but handle errors)
# age = int(input("Enter your age: "))  # This can crash if not a number

3. Working with format() Method, f-Strings, & Escape Sequences

** String Formatting: - format() method inserts variables into strings.

  • f-strings (Python 3.6+) provide a concise way to embed expressions inside string literals.

** Escape Sequences: - \n → New line

  • \t → Tab space

  • \\ → Backslash

  • \" or \' → Quotes

# Using format()
name = "Vini"
age = 23
print("My name is {} and I am {} years old.".format(name, age))

# Using f-strings
print(f"My name is {name} and I am {age} years old.")

# Escape sequences
print("Hello\tWorld")  # Tab
print("Line 1\nLine 2")  # New line
print("She said, \"Python is fun!\"")
name = "John"
print("Hello, %s!" % name)

mylist = [1,2,3]
print("A list: %s" % mylist)

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

4. Basic Arithmetic & Operators

Arithmetic Operators: - + → Addition

  • - → Subtraction

  • * → Multiplication

  • / → Division

  • // → Floor Division (discards remainder)

  • % → Modulus (remainder)

  • ** → Exponent (power)

a = 10
b = 3

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)

Comparison Operators:

  • == → Equal to

  • != → Not equal to

  • > → Greater than

  • < → Less than

  • >= → Greater than or equal to

  • <= → Less than or equal to

Logical Operators:

  • and → Both conditions must be True

  • or → At least one condition must be True

  • not → Reverses the result

# Comparison operators
x = 10
y = 5

print("Comparison Results:")
print(f"x == y: {x == y}")
print(f"x != y: {x != y}")
print(f"x > y: {x > y}")
print(f"x < y: {x < y}")
print(f"x >= y: {x >= y}")
print(f"x <= y: {x <= y}")

# Logical operators
age = 20
has_license = True

print("\nLogical Operations:")
print(f"Can drive: {age >= 18 and has_license}")
print(f"Student or senior: {age < 25 or age > 65}")
print(f"Not a teenager: {not (13 <= age <= 19)}")

5. Type Casting, Type Checking, & Validation

Type Casting: - Convert one data type to another using functions like int(), float(), str(), etc.

Type Checking: - Use type() function to check the data type.

Simple Validation Example: - Check if the input is numeric using .isdigit().

# Type Casting
x = "5"
y = int(x)  # Convert string to integer
print(y + 2)  # Output: 7

# Type Checking
print(type(y))  # Output: <class 'int'>

# Validation Example
user_input = input("Enter a number: ")
if user_input.isdigit():
    print("You entered:", int(user_input))
else:
    print("Invalid input. Please enter a number.")

More Type Conversion Examples:

# Various type conversions
print("=== Type Conversions ===")

# String to numbers
str_int = "42"
str_float = "3.14"
print(f"String to int: {int(str_int)}")
print(f"String to float: {float(str_float)}")

# Numbers to string
num = 100
pi = 3.14159
print(f"Int to string: '{str(num)}'")
print(f"Float to string: '{str(pi)}'")

# Float to int (truncates decimal)
print(f"Float to int: {int(pi)}")

# Boolean conversions
print(f"Bool to int: {int(True)}, {int(False)}")
print(f"Bool to string: '{str(True)}'")

# Truthy and Falsy values
print(f"bool(0): {bool(0)}")
print(f"bool(''): {bool('')}")
print(f"bool('hello'): {bool('hello')}")
print(f"bool(None): {bool(None)}")

# Common conversion errors (commented to avoid crashes)
# int("hello")  # ValueError
# float("not_a_number")  # ValueError

6. Constants and Variable Scope

Constants:

  • Python doesn't have true constants, but convention is to use ALL_CAPS

  • These are variables that shouldn't be changed after assignment

# Constants (by convention)
PI = 3.14159
MAX_USERS = 100
APP_NAME = "My Python App"

print(f"Pi value: {PI}")
print(f"Maximum users: {MAX_USERS}")
print(f"App name: {APP_NAME}")

# Using constants in calculations
radius = 5
area = PI * radius ** 2
print(f"Area of circle with radius {radius}: {area}")

# Variable scope example
global_var = "I'm global"

def demo_function():
    local_var = "I'm local"
    print(f"Inside function: {global_var}")
    print(f"Inside function: {local_var}")

demo_function()
print(f"Outside function: {global_var}")
# print(local_var)  # This would cause an error - local_var not accessible

Quick Recap

✅ Python supports multiple data types (string, int, float, etc.)

✅ Variables store data values dynamically

✅ Use print() for output and input() for taking user input

✅ String formatting with format() and f-strings

✅ Arithmetic operations are straightforward

✅ Type casting, checking, and basic input validation enhance reliability

📝 Practice Exercises

Q. The target of this exercise is to create a string, an integer, and a floating point number. The string should be named mystring and should contain the word "hello". The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.

  1. Declare variables for your name, age, and height. Print them using f-strings.

  2. Ask the user for two numbers and print their sum.

  3. Write a program to check if the user entered a valid number.

  4. Experiment with escape sequences to format output.

  5. Use nested loops to print a pattern like:

Additional Practice Exercises:

  1. Calculator Program: Create a simple calculator that takes two numbers and an operation (+, -, *, /) from the user.

  2. Temperature Converter: Write a program that converts temperature between Celsius and Fahrenheit.

  3. Data Type Explorer: Create variables of different types and use type() to display their types.

  4. Boolean Logic: Write a program that checks if a number is positive, negative, or zero using comparison operators.

  5. String Manipulation: Take a user's full name and display it in different formats (uppercase, lowercase, title case).

  6. Age Calculator: Calculate someone's age in years, months, and days given their birth year.

  7. Input Validation: Create a program that keeps asking for a number until the user provides a valid integer.

*
**
***
****
*****

******
*****
****
***
**
*

     *
    ***
   *****
  *******
 *********
***********

** Solution

max = 6
print("="*15)
for i in range(max):
    print(f'{"*" * (i)}')

print("="*15)
for i in range(max):
    print(f'{"*" * (max - i)}')

print("="*15)
for i in range(1,max+1):
    print(" " * (max - i) + "*" * (2 * i - 1))
print("="*15)

Solution:

# change this code
mystring = "hello"
myfloat = 10.0
myint = 20

# testing code
if mystring == "hello":
    print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
    print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
    print("Integer: %d" % myint)