Python Variables

JK JK 2038 
Created at
Updated at  
7,541 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,704
  2. Python Syntax
    7,523
  3. Python Data Types
    7,574
  4. Python Getting Started
    7,589
  5. Python Introduction
    7,179
  6. What is Python?
    7,841
  7. Python String Operations
    7,566
  8. Python Lists
    7,483
  9. String concatenation by join()
    7,200
  10. Printing string n times
    7,137
  11. Python Arithmetic Operators
    7,154
  12. Python Comparison Operators
    7,365
  13. Python Tuples
    7,286
  14. Python Sets
    7,193
  15. Python Dictionaries
    7,184
  16. Python Conditions and If statements
    7,207
  17. Python While Loops/For Loops
    7,650
  18. Python Functions
    7,145
  19. Python Lambda
    7,188
  20. Python Arrays
    7,183
  21. Python Classes/Objects
    7,610
  22. Python Inheritance
    7,290
  23. Python Iterators
    7,193
  24. Python Polymorphism
    7,178
  25. Python Scope
    7,153
  26. Python Modules
    7,201
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,483
  28. Machine Learning Types and Programming Languages
    7,348
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    8,093
  30. Mastering Excel Data Manipulation with Python
    7,160
  31. Challenge: One Code Problem Per Day
    1,291
  32. Clean Python Environments: The Power of venv vs. Docker
    1,110
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,083
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,664
  3. RegExp example in Python to exclude javascript from HTML code
    7,134
  4. Python code to convert from Lunar to Solar
    7,938
  5. Python example to download webpage
    8,957
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    954
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    841
  3. Michael Jackson's Billie Jean
    402
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    391
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    340
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    373
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    379
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    399
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,320
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    554
  11. The Evolution and Production Reality of Agentic AI
    433
  12. How to Activate or Waive Your UIUC Student Health Insurance
    567
  13. Complete Guide to Building a Machine Learning Model
    569
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,616
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    590
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,366
  17. What is Docker? Why is Docker also useful in a development environment?
    823
  18. UIUC 2026-2027 Academic Calendar
    2,059
  19. Open-Source LLMs: The AI Revolution
    989
  20. Resume 2.0: Leveling Up for My First Software Gig
    3,020
  21. Not everyone will understand what this man just did
    2,480
  22. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,875
  23. Unpacking IU's Shopper
    983
  24. Jackie Chan's Police Story: The Action Masterpiece
    873
  25. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,211
  26. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,401
  27. Open Databases for Sex Crime Occurrences in the U.S.
    983
  28. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,439
  29. My First Day at University of Illinois-Urvana Champaign
    1,381
  30. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,432
  31. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,497
  32. Sipping the Stars: My Starbucks Adventure
    10,178
  33. Exciting explore at Sequoia National Park
    7,871
  34. My Life Shot at Death Valley
    2,073
  35. Ip Man fights with Muay Thai Master
    1,140
  36. Mad Clown - Don't Die
    1,262
  37. How to get Student Enrollment and Degree Verification at UIUC
    5,940
  38. LAX Thanksgiving Rush: A Joyful Reunion
    1,096
  39. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,364
  40. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,154
  41. 10CM - To Reach You (너에게 닿기를)
    1,332
  42. Feeling weak? Transform yourself at the UIUC ARC!
    1,750
  43. BOYNEXTDOOR - If I Say I Love You
    1,387
  44. The Future of Software Engineer - AI Engineering
    1,112
  45. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,120
  46. Lie - Legend song by BIGBANG
    8,009
  47. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,109
  48. Reimbursement after Vaccination at McKinley Health Center
    1,231
  49. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,159
  50. Common Questions from UIUC school life in terms of CS Program
    1,345