CyberCodeAcademy

Home / Python / Variable

Variable

Aapko Variable tutorial ka content chahiye, to ye ready content WordPress ke editor me paste kar sakte ho:

Variable in Python

A variable is a name used to store data in a Python program.

In Python, you don’t need to declare the data type of a variable separately. Python automatically determines the type based on the value assigned to it.

Creating a Variable

A variable is created when you assign a value to it using the = operator.

name = "Krishna"
age = 25
salary = 25000

Here:

  • name stores a string.
  • age stores an integer.
  • salary stores an integer.

Example

name = "Krishna"
age = 25

print(name)
print(age)

Output:

Krishna
25

Different Types of Variables

Python variables can store different types of data.

name = "Krishna"       # String
age = 25               # Integer
height = 5.8           # Float
is_student = True      # Boolean

Multiple Variables

Python allows you to assign values to multiple variables in one line.

x, y, z = 10, 20, 30

print(x)
print(y)
print(z)

Output:

10
20
30

Same Value to Multiple Variables

You can assign the same value to multiple variables.

x = y = z = 100

print(x)
print(y)
print(z)

Output:

100
100
100

Changing the Value of a Variable

A variable’s value can be changed during program execution.

age = 20

print(age)

age = 25

print(age)

Output:

20
25

Rules for Naming Variables

Python variable names follow these rules:

  1. A variable name must start with a letter or underscore _.
  2. It cannot start with a number.
  3. It can contain letters, numbers, and underscores.
  4. Variable names are case-sensitive.
  5. Python keywords cannot be used as variable names.

Valid Variable Names

name = "Krishna"
age1 = 25
student_name = "Rahul"
_marks = 90

Invalid Variable Names

1name = "Krishna"      # Invalid
student-name = "Rahul" # Invalid
class = 10             # Invalid

Case-Sensitive Variables

Python is case-sensitive.

name = "Krishna"
Name = "Rahul"

print(name)
print(Name)

Here, name and Name are two different variables.

Checking Variable Type

You can use the type() function to check the data type of a variable.

age = 25
name = "Krishna"

print(type(age))
print(type(name))

Output:

<class 'int'>
<class 'str'>

Conclusion

Variables are one of the fundamental concepts in Python. They are used to store and manipulate data throughout a program.


WordPress me

Tutorials → Add New Tutorial

Title: Variable

Slug: variable

Category: Python

Phir upar wala content Content area me paste karke Publish kar do.

Uske baad URL hoga:

cybercodeacademy.com/python/variable/

Aur aapke left sidebar me Variable automatically add ho jayega.

CyberCodeAcademy