You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Python is a high-level, interpreted programming language known for its readability, flexibility, and vast ecosystem of libraries. Designed with simplicity in mind, Python’s syntax is straightforward, making it an excellent choice for beginners and professionals alike. Created by Guido van Rossum in the late 1980s, Python has evolved into one of the most popular programming languages in the world.
12
+
13
+
## Variables in Python
14
+
15
+
In Python, declaring a variable is as simple as assigning a value to a name using the = operator:
16
+
17
+
```Python
18
+
# Examples of variables
19
+
name ="Alice"# string variable
20
+
age =25# integer variable
21
+
height =5.7# float variable
22
+
is_student =True# boolean variable
23
+
24
+
```
25
+
26
+
### Variable Naming Rules
27
+
28
+
- Variable names must start with a letter (a-z, A-Z) or an underscore _.
29
+
- Variable names cannot start with a number.
30
+
- Only letters, numbers, and underscores are allowed in variable names.
31
+
- Variable names are case-sensitive (age and Age would be two different variables).
32
+
33
+
1. Examples of valid variable names:
34
+
```Python
35
+
first_name ="Alice"
36
+
_age =30
37
+
height_in_cm =175
38
+
39
+
```
40
+
41
+
2. Examples of invalid variable names:
42
+
```Python
43
+
2nd_variable="invalid"# Starts with a number
44
+
first-name ="invalid"# Contains a hyphen
45
+
```
46
+
47
+
### Dynamic Typing
48
+
49
+
- Integers (int): Whole numbers (e.g., 10, -5)
50
+
- Floating Point Numbers (float): Numbers with decimals (e.g., 5.7, -3.14)
51
+
- Strings (str): Text data (e.g., "hello", "Python")
Although Python does not have a built-in way to declare constants (variables that should not change), it’s a common convention to use all-uppercase names for variables intended to be constant:
85
+
86
+
```Python
87
+
PI=3.14159
88
+
GRAVITY=9.8
89
+
```
90
+
91
+
### Multiple Variable Assignment
92
+
93
+
```Python
94
+
a, b, c =1, 2, 3
95
+
print(a) # Output: 1
96
+
print(b) # Output: 2
97
+
print(c) # Output: 3
98
+
x = y = z =100
99
+
print(x, y, z) # Output: 100 100 100
100
+
```
101
+
102
+
### Variable Scope
103
+
104
+
- Global Variables: Defined outside of a function and can be accessed anywhere in the code.
105
+
- Local Variables: Defined inside a function and can only be accessed within that function.
106
+
107
+
```Python
108
+
global_var ="I am global"
109
+
110
+
defmy_function():
111
+
local_var ="I am local"
112
+
print(global_var) # This works
113
+
print(local_var) # This also works
114
+
115
+
my_function()
116
+
print(global_var) # This works
117
+
# print(local_var) # This would cause an error, as local_var is not accessible outside the function
0 commit comments