Python Variables

JK JK 2038 
Created at
Updated at  
7,484 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,647
  2. Python Syntax
    7,474
  3. Python Data Types
    7,524
  4. Python Getting Started
    7,539
  5. Python Introduction
    7,145
  6. What is Python?
    7,796
  7. Python String Operations
    7,509
  8. Python Lists
    7,424
  9. String concatenation by join()
    7,171
  10. Printing string n times
    7,103
  11. Python Arithmetic Operators
    7,121
  12. Python Comparison Operators
    7,321
  13. Python Tuples
    7,243
  14. Python Sets
    7,147
  15. Python Dictionaries
    7,121
  16. Python Conditions and If statements
    7,168
  17. Python While Loops/For Loops
    7,589
  18. Python Functions
    7,104
  19. Python Lambda
    7,154
  20. Python Arrays
    7,137
  21. Python Classes/Objects
    7,552
  22. Python Inheritance
    7,250
  23. Python Iterators
    7,157
  24. Python Polymorphism
    7,133
  25. Python Scope
    7,108
  26. Python Modules
    7,160
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,438
  28. Machine Learning Types and Programming Languages
    7,310
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    8,022
  30. Mastering Excel Data Manipulation with Python
    7,129
  31. Challenge: One Code Problem Per Day
    1,225
  32. Clean Python Environments: The Power of venv vs. Docker
    1,026
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    985
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,425
  3. RegExp example in Python to exclude javascript from HTML code
    7,101
  4. Python code to convert from Lunar to Solar
    7,833
  5. Python example to download webpage
    8,772
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    353
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    317
  3. Michael Jackson's Billie Jean
    325
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    180
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    218
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    252
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    270
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    312
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    923
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    447
  11. The Evolution and Production Reality of Agentic AI
    359
  12. How to Activate or Waive Your UIUC Student Health Insurance
    454
  13. Complete Guide to Building a Machine Learning Model
    472
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,560
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    502
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,225
  17. What is Docker? Why is Docker also useful in a development environment?
    750
  18. UIUC 2026-2027 Academic Calendar
    1,865
  19. Open-Source LLMs: The AI Revolution
    917
  20. Resume 2.0: Leveling Up for My First Software Gig
    2,662
  21. Not everyone will understand what this man just did
    2,216
  22. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,765
  23. Unpacking IU's Shopper
    925
  24. Jackie Chan's Police Story: The Action Masterpiece
    796
  25. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,111
  26. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,323
  27. Open Databases for Sex Crime Occurrences in the U.S.
    879
  28. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,079
  29. My First Day at University of Illinois-Urvana Champaign
    1,318
  30. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,324
  31. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,411
  32. Sipping the Stars: My Starbucks Adventure
    9,951
  33. Exciting explore at Sequoia National Park
    7,815
  34. My Life Shot at Death Valley
    1,932
  35. Ip Man fights with Muay Thai Master
    1,081
  36. Mad Clown - Don't Die
    1,193
  37. How to get Student Enrollment and Degree Verification at UIUC
    5,428
  38. LAX Thanksgiving Rush: A Joyful Reunion
    1,038
  39. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,281
  40. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,109
  41. 10CM - To Reach You (너에게 닿기를)
    1,288
  42. Feeling weak? Transform yourself at the UIUC ARC!
    1,696
  43. BOYNEXTDOOR - If I Say I Love You
    1,311
  44. The Future of Software Engineer - AI Engineering
    1,043
  45. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,043
  46. Lie - Legend song by BIGBANG
    7,943
  47. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,009
  48. Reimbursement after Vaccination at McKinley Health Center
    1,150
  49. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,085
  50. Common Questions from UIUC school life in terms of CS Program
    1,273