|
| 1 | +--- |
| 2 | +sidebar_position: 3 |
| 3 | +--- |
| 4 | + |
| 5 | +# Variable And Literal |
| 6 | + |
| 7 | +## Literals: |
| 8 | + |
| 9 | +### Definition |
| 10 | + |
| 11 | +Fixed values directly written in the code. |
| 12 | + |
| 13 | +### Examples |
| 14 | + |
| 15 | +1. **Numbers**: 4, 102, -21, 4_000_000 (underscores for readability). |
| 16 | +2. **Booleans**: True or False. |
| 17 | +3. **Text**: "python" or 'This language is fun!'. |
| 18 | +4. **Lists**: [1, 2, 3]. |
| 19 | + |
| 20 | +## Variables: |
| 21 | + |
| 22 | +### Definition |
| 23 | + |
| 24 | +Names that store values in memory. |
| 25 | + |
| 26 | +### Creation |
| 27 | + |
| 28 | +Use a name, =, and a value (e.g., price = 45.50). |
| 29 | + |
| 30 | +### Naming Rules |
| 31 | + |
| 32 | +Use letters, numbers, or underscores without spaces. Must start with a letter or underscore. |
| 33 | + |
| 34 | +## Data Types: |
| 35 | + |
| 36 | +1. **Integer**: Whole numbers (e.g., -2, 0, 23). |
| 37 | +2. **Float**: Numbers with decimals (e.g., 3.14, -0.001). |
| 38 | +3. **Boolean**: True or False. |
| 39 | +4. **String**: Text (e.g., "Thailand"). |
| 40 | +5. **NoneType**: Represents no value (None). |
| 41 | + |
| 42 | +## Type Function: |
| 43 | + |
| 44 | +### Usage |
| 45 | + |
| 46 | +Check the type of a value (e.g., type(4) returns int). |
| 47 | + |
| 48 | +## Type Casting: |
| 49 | + |
| 50 | +### Definition |
| 51 | + |
| 52 | +Changing a value from one type to another. |
| 53 | + |
| 54 | +### Examples |
| 55 | + |
| 56 | +1. **String to Float**: float("4.5"). |
| 57 | +2. **Float to Integer**: int(3.14) (removes decimal). |
| 58 | +3. **String to Boolean**: bool("") is False, any other string is True. |
| 59 | + |
| 60 | +## Code Example |
| 61 | + |
| 62 | +```python title="example.py" |
| 63 | +# Numeric literals |
| 64 | +price = 45.50 |
| 65 | +age = 24 |
| 66 | + |
| 67 | +# Boolean literal |
| 68 | +is_printed = True |
| 69 | + |
| 70 | +# String literal |
| 71 | +course_name = "Python for Beginners" |
| 72 | + |
| 73 | +# Performing an operation with a variable |
| 74 | +tax = price * 0.09 |
| 75 | + |
| 76 | +# Receiving input from the console |
| 77 | +user_input = input("Enter a number: ") |
| 78 | + |
| 79 | +# Type casting the input to a float |
| 80 | +user_number = float(user_input) |
| 81 | + |
| 82 | +# Printing the results |
| 83 | +print("Price:", price) |
| 84 | +print("Age:", age) |
| 85 | +print("Is Printed:", is_printed) |
| 86 | +print("Course Name:", course_name) |
| 87 | +print("Tax:", tax) |
| 88 | +print("User Number:", user_number) |
| 89 | +``` |
0 commit comments