What are variables in Python?
Think of variables as labeled boxes where you store data for later use in your program. They act as names that refer to specific values in memory.
Key points:
Creation:
Choose a descriptive name that starts with a letter or underscore (e.g., age, _total_count).
Use the = operator to assign a value to the variable:
Python
name = "Alice"
age = 30
is_active = True
Dynamic Typing: Python automatically determines the variable's data type based on the assigned value.
No Declaration: You don't need to specify the data type beforehand.
Case Sensitivity: name is different from Name.
Common Data Types:
Numbers:
Integers (int): Whole numbers like 42, -10
Floats (float): Decimal numbers like 3.14, -1.56
Strings (str): Textual data enclosed in quotes (single or double)
Booleans (bool): Represent logical values True or False
Naming Conventions:
Descriptive names: Make your code more readable.
Python's style: Use lowercase letters with underscores (e.g., first_name, total_items).
Avoid reserved keywords: Python has specific words for built-in functions and constructs (e.g., if, else, for).
Using Variables:
Access the stored value: Use the variable name in your code:
Python
print(name) # Output: Alice
print(age + 5) # Output: 35Modify the value: Reassign a new value to the variable:
Python
age = 31 # Now age stores the value 31
Additional Insights:
Variable Scope: Variables can be local (within functions) or global (accessible throughout the program).
Memory Management: Python handles memory allocation and deallocation automatically using garbage collection.
What variables are: Containers to store information.
How to create them: Using = assignment.
Data types: Numbers (integers, floats), strings, booleans.
Case sensitivity: Variable names matter (e.g., x is different from X).
Executing code: Using Shift+Enter.
Outputting values: Using print() or directly accessing the variable name.
Multiple assignments: Assigning values to multiple variables simultaneously.
name ='Venkat'
name
'Venkat'
a=20
a
20
a=20
b=30
a+b
50
c=a+b
c
50
print(c)
50
print(name)
Venkat
a=20
b=40
c=50
sum=a+b+c
sum
110
a,b,c=(30,60,90)
z=a+b+c
z
180
a,b,c=(30,60)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[16], line 1 ----> 1 a,b,c=(30,60) ValueError: not enough values to unpack (expected 3, got 2)
a,b,c=(30,60,90)
A
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[18], line 1 ----> 1 A NameError: name 'A' is not defined
name
'Venkat'
Name
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[20], line 1 ----> 1 Name NameError: name 'Name' is not defined
No comments:
Post a Comment
Note: only a member of this blog may post a comment.