Python Variables

JK JK 2026 
Created at
Updated at  
7,425 0 0

Variables are containers for storing data values.


Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after they have been set.

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)

Casting

If you want to specify the data type of a variable, this can be done with casting.

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

Get the Type

You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

x = "John"
# is the same as
x = 'John'

Case-Sensitive

Variable names are case-sensitive.

a = 4
A = "Sally"
#A will not overwrite a

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • A variable name cannot be any of the Python keywords.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal variable names:

2myvar = "John"
my-var = "John"
my var = "John"

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

 

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "John"

 

Pascal Case

Each word starts with a capital letter:

MyVariableName = "John"

 

Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

Many Values to Multiple Variables

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

x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking.

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

Output Variables

The Python print() function is often used to output variables.

x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

For numbers, the + character works as a mathematical operator:

x = 5
y = 10
print(x + y)

 

In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error:

x = 5
y = "John"
print(x + y)

 

The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types:

x = 5
y = "John"
print(x, y)

Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

x = "awesome"

def myfunc():
  print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

 

Tags Python Python Casting Python Global Keyword Python Global Variables Python Variable Name Python Variable Naming Convention Python Variable Type Python Variables Facebook X
Comments 0
Similar posts
  1. Python Comments
    7,566
  2. Python Syntax
    7,415
  3. Python Data Types
    7,456
  4. Python Getting Started
    7,473
  5. Python Introduction
    7,109
  6. What is Python?
    7,748
  7. Python String Operations
    7,441
  8. Python Lists
    7,354
  9. String concatenation by join()
    7,142
  10. Printing string n times
    7,077
  11. Python Arithmetic Operators
    7,087
  12. Python Comparison Operators
    7,254
  13. Python Tuples
    7,181
  14. Python Sets
    7,107
  15. Python Dictionaries
    7,069
  16. Python Conditions and If statements
    7,136
  17. Python While Loops/For Loops
    7,519
  18. Python Functions
    7,068
  19. Python Lambda
    7,110
  20. Python Arrays
    7,095
  21. Python Classes/Objects
    7,487
  22. Python Inheritance
    7,200
  23. Python Iterators
    7,114
  24. Python Polymorphism
    7,095
  25. Python Scope
    7,067
  26. Python Modules
    7,114
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,381
  28. Machine Learning Types and Programming Languages
    7,250
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,915
  30. Mastering Excel Data Manipulation with Python
    7,084
  31. Challenge: One Code Problem Per Day
    1,133
  32. Clean Python Environments: The Power of venv vs. Docker
    886
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    858
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,243
  3. RegExp example in Python to exclude javascript from HTML code
    7,061
  4. Python code to convert from Lunar to Solar
    7,751
  5. Python example to download webpage
    8,639
Recently updated
  1. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    108
  2. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    105
  3. Watch This Dazzling Dancer’s Mind-Blowing Moves
    145
  4. Michael Jackson's Billie Jean
    211
  5. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    179
  6. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    587
  7. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    301
  8. The Evolution and Production Reality of Agentic AI
    268
  9. How to Activate or Waive Your UIUC Student Health Insurance
    345
  10. Complete Guide to Building a Machine Learning Model
    378
  11. My life cuts at Las Vegas during Thanksgiving day holiday
    7,462
  12. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    404
  13. Harness vs. OpenClaw: Two Very Different "Agents"
    1,045
  14. What is Docker? Why is Docker also useful in a development environment?
    664
  15. UIUC 2026-2027 Academic Calendar
    1,682
  16. Open-Source LLMs: The AI Revolution
    810
  17. Resume 2.0: Leveling Up for My First Software Gig
    2,367
  18. Not everyone will understand what this man just did
    1,981
  19. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,645
  20. Unpacking IU's Shopper
    820
  21. Jackie Chan's Police Story: The Action Masterpiece
    705
  22. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,008
  23. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,229
  24. Open Databases for Sex Crime Occurrences in the U.S.
    759
  25. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,779
  26. My First Day at University of Illinois-Urvana Champaign
    1,244
  27. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,192
  28. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,275
  29. Sipping the Stars: My Starbucks Adventure
    9,741
  30. Exciting explore at Sequoia National Park
    7,718
  31. My Life Shot at Death Valley
    1,781
  32. Ip Man fights with Muay Thai Master
    988
  33. Mad Clown - Don't Die
    1,083
  34. How to get Student Enrollment and Degree Verification at UIUC
    5,052
  35. LAX Thanksgiving Rush: A Joyful Reunion
    958
  36. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,175
  37. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,028
  38. 10CM - To Reach You (너에게 닿기를)
    1,201
  39. Feeling weak? Transform yourself at the UIUC ARC!
    1,610
  40. BOYNEXTDOOR - If I Say I Love You
    1,221
  41. The Future of Software Engineer - AI Engineering
    964
  42. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    956
  43. Lie - Legend song by BIGBANG
    7,860
  44. Why ROLLBACK is useful when you work with Google Gemini CLI?
    887
  45. Reimbursement after Vaccination at McKinley Health Center
    1,064
  46. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,002
  47. Common Questions from UIUC school life in terms of CS Program
    1,168
  48. UIUC Immunization Compliance
    1,261
  49. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,139
  50. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,132