DEV Community

Cover image for Day:2 Python 🐍
Aruna Arun
Aruna Arun

Posted on

Day:2 Python 🐍

What is a Variable?
A variable is a name that stores a value in a computer’s memory.
It works like a container where you can keep data and use it later.
Example:
name = "Aruna"
age = 21
Here, name and age are variables.

Rules for Variables in Python
1.A variable must start with a letter or underscore (_)
2.A variable cannot start with a number
3.No spaces are allowed
4.You can use letters, numbers, and underscore only
5.Variable names are case-sensitive
eg.age, Age, and AGE are all different.
6.Do not use Python keywords as variable names
(like if, for, class, while)

Data Types in Python
1.String (str). Eg.name = "Aruna"
2.Integer (int). Eg.age = 20
3.Float. Eg.price = 99.99
4.Boolean (bool). Eg.True / False
5.List. Eg.[90, 85, 76]
6.Tuple. Eg.("red", "blue")
7.Set. Eg.{1, 2, 3}
8.Dictionary. Eg.{"name": "Aruna", "age": 20}

Type Checking
print(type(name))
print(type(age))

Type Conversion
x = "10"
y = int(x) # convert string to integer
print(y + 5)

Input, Output & Type Conversion
1. Input in Python
input() is used to take values from the user.
Example:
name = input("Enter your name: ")
print("Your name is", name)
Everything you get from input() is a string.

2. Taking Numeric Input
Since input returns string, convert it:
Integer input
age = int(input("Enter your age: "))
print(age)

Float input
salary = float(input("Enter your salary: "))
print(salary)

3. Output in Python
You use print() to show output.
Examples:
print("Hello")
print("My age is", age)
print("Sum =", 10 + 5)

4. Type Conversion (Casting)
Convert str → int
x = "10"
y = int(x)
print(y + 5)

Convert int → str
age = 20
text = str(age)
print("Age is " + text)

Convert str → float
num = "3.14"
value = float(num)
print(value)

**5. Multiple Inputs in a Single Line
**Use split() → breaks input into pieces.
Example:
a, b = input("Enter two numbers: ").split()
print(a, b)

Convert to int:
a, b = map(int, input("Enter two numbers: ").split())
print(a + b)

6. Formatting Output (f-string)
Used for beautiful printing.
Example:
name = "Aruna"
age = 20
print(f"My name is {name} and I am {age} years old.")

7. Mini Programs

  1. Add 2 numbers
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))
    print("Sum =", a + b)

  2. Area of Circle
    r = float(input("Enter radius: "))
    area = 3.14 * r * r
    print("Area =", area)

  3. User Details
    name = input("Enter name: ")
    age = int(input("Enter age: "))
    place = input("Enter place: ")
    print(f"I am {name}, {age} years old, from {place}.")

8. Common Errors (Important!)
ValueError
When converting invalid string to number:
int("abc") # Error

TypeError
When adding string + integer:
"age = " + 20 # Error

Fix:
"age = " + str(20)

Top comments (0)