Python Variable
In Python, a variable is a named location in memory that stores a value. You can create a variable in Python by simply assigning a value to a name using the assignment operator (=). For example:
1 2 3 | x = 5 |
This creates a variable called “x” and assigns the value 5 to it. You can then use the variable in your code by referencing its name. For example:
1 2 3 | print(x) # Outputs 5 |
Naming and Using Variables
When naming variables in Python, there are a few rules that you should follow:
- Variable names can only contain letters, numbers, and underscores. They cannot start with a number.
- Variable names are case-sensitive, so “foo” and “Foo” are considered to be different variables.
- Avoid using Python keywords and built-in function names as variable names, as this can cause conflicts and errors in your code.
Here are some examples of valid and invalid variable names in Python:
1 2 3 4 5 6 7 8 9 10 11 12 | Valid: foo bar _private myVariable123 Invalid: 123abc (starts with a number) my-variable (contains a hyphen) print (a Python keyword) |
It’s a good idea to use descriptive and meaningful names for your variables, as this can make your code easier to read and understand. For example, instead of using “x” and “y” as variable names, you might use “customer_name” and “order_total” instead.
To use a variable in Python, you simply need to reference its name. For example:
1 2 3 4 5 6 7 8 | x = 5 y = 10 result = x + y # result is now 15 print(x) # Outputs 5 print(result) # Outputs 15 |
You can also use variables in expressions and assign the result to a new variable. For example:
1 2 3 4 5 6 7 | x = 5 y = 10 result = x + y # result is now 15 double = result * 2 # double is now 30 |
Remember, you can use the “type” function to find out the data type of a variable:
1 2 3 4 5 | print(type(x)) # Outputs: <class 'int'> print(type(result)) # Outputs: <class 'int'> print(type(double)) # Outputs: <class 'int'> |
Python Data Types
In Python, there are several simple data types that you can use to store values in variables. These include:
- Integer: A whole number, such as 5, 100, or -3.
- Float: A number with a decimal point, such as 3.14, 1.0, or -0.01.
- String: A sequence of characters, such as “hello” or “goodbye”. Strings must be enclosed in quotation marks.
- Boolean: A value that can be either True or False.
Here are some examples of declaring variables with different data types:
1 2 3 4 5 6 | x = 5 # An integer y = 3.14 # A float z = "hello" # A string w = True # A boolean |
You can use the “type” function to find out the data type of a variable:
1 2 3 4 5 6 | print(type(x)) # Outputs: <class 'int'> print(type(y)) # Outputs: <class 'float'> print(type(z)) # Outputs: <class 'str'> print(type(w)) # Outputs: <class 'bool'> |
It’s important to choose the right data type for your variables, as this can affect how they are used and processed in your code. For example, you can’t perform arithmetic operations on a string in the same way that you can with a number.
You can also use variables to store the results of expressions or the output of functions. For example:
1 2 3 4 5 6 7 8 9 10 | x = 5 y = 10 result = x + y # result is now 15 def greet(name): return "Hello, " + name greeting = greet("John") # greeting is now "Hello, John" |
As you can see, variables can be very useful for storing and manipulating values in your code.
Strings in Python
In Python, a string is a sequence of characters used to represent text. Strings are immutable, which means that once they are created, you cannot change the individual characters that make up the string.
To create a string in Python, you can use single or double quotes:
1 2 3 4 | string1 = 'Hello, World!' string2 = "Hello, World!" |
Both of these lines create the same string. You can use whichever type of quotes you prefer, as long as you are consistent within a single string.
You can use the plus (+) operator to concatenate (combine) strings:
1 2 3 4 5 | string1 = "Hello, " string2 = "World!" string3 = string1 + string2 # string3 is now "Hello, World!" |
You can also use the “*” operator to repeat a string multiple times:
1 2 3 | You can also use the "*" operator to repeat a string multiple times: |
To find out the length of a string (i.e., the number of characters it contains), you can use the “len” function:
1 2 3 4 | string = "Hello, World!" length = len(string) # length is now 12 |
You can access individual characters in a string using indexing. In Python, indexes start at 0, so the first character in a string has an index of 0, the second character has an index of 1, and so on. For example:
1 2 3 4 5 | string = "Hello, World!" first_char = string[0] # first_char is now "H" last_char = string[11] # last_char is now "!" |
You can also use slicing to extract a range of characters from a string. For example:
1 2 3 4 | string = "Hello, World!" substring = string[3:8] # substring is now "lo, W" |
This extracts the characters from index 3 to index 7 (not 8) and stores them in a new string.
There are many other operations and functions that you can use with strings in Python. For more information, you can check out the official Python documentation.
Numbers in Python
In Python, there are two main data types for representing numbers: integers and floats.
Integers are whole numbers, such as 1, 2, or 3. You can use the built-in “int” function to convert numbers or strings to integers:
1 2 3 4 | x = int(5) # x is now an integer with a value of 5 y = int("5") # y is also an integer with a value of 5 |
Floats are numbers with decimal points, such as 3.14 or 2.71828. You can use the built-in “float” function to convert numbers or strings to floats:
1 2 3 4 | x = float(5) # x is now a float with a value of 5.0 y = float("5.5") # y is a float with a value of 5.5 |
You can perform arithmetic operations on numbers in Python using the standard operators:
1 2 3 4 5 6 | x = 5 + 3 # x is now 8 y = 10 - 2 # y is now 8 z = 2 * 4 # z is now 8 w = 8 / 2 # w is now 4.0 |
Note that division (/) always returns a float, even if the result is a whole number.
You can use the “**” operator to perform exponentiation:
1 2 3 | x = 2 ** 3 # x is now 8 |
You can also use the “//” operator to perform integer division, which returns the quotient as an integer:
1 2 3 | x = 8 // 3 # x is now 2 |
There are many other functions and operations that you can perform on numbers in Python. For example, you can use the “abs” function to get the absolute value of a number, the “round” function to round a number to a specified precision, and the “min” and “max” functions to find the minimum and maximum values of a set of numbers.
For more information, you can check out the official Python documentation.
Booleans in Python
In Python, a Boolean is a data type that represents a value of true or false. The two Boolean values are written as “True” and “False” (with a capital T and F).
You can use Booleans in Python to test conditions and control the flow of your program. For example:
1 2 3 4 5 6 7 8 9 10 11 | x = 5 y = 8 if x < y: print("x is less than y") else: print("x is not less than y") # Outputs: "x is less than y" |
In this example, the expression “x < y” is a Boolean that evaluates to “True” because x is less than y. This causes the first “print” statement to be executed. If x were greater than or equal to y, the expression would evaluate to “False” and the second “print” statement would be executed instead.
You can also use Boolean values to control loops and other flow control statements. For example:
1 2 3 4 5 6 7 8 9 | x = 0 while x < 10: print(x) x += 1 # Outputs: 0 1 2 3 4 5 6 7 8 9 |
In this example, the Boolean expression “x < 10” is tested at the start of each iteration of the loop. As long as it evaluates to “True”, the loop will continue to execute. Once x becomes equal to or greater than 10, the expression evaluates to “False” and the loop terminates.
Booleans are often used in conjunction with logical operators such as “and”, “or”, and “not”. For example:
1 2 3 4 5 6 7 8 9 10 | x = 5 y = 8 z = 10 if x < y and y < z: print("x is the smallest number") # Outputs: "x is the smallest number" |
In this example, the “and” operator combines two Boolean expressions and returns “True” only if both expressions are “True”.
You can use the “or” operator in a similar way, but it returns “True” if either of the expressions is “True”. The “not” operator negates a Boolean expression, so “not True” is “False” and “not False” is “True”.
For more python topics, click the Python Tutorials link.