Type Conversion in Python
In programming languages like Python, there are times when you need to convert a variable from one type to another. In this tutorial, I'll show you a bunch of cool things you can do with strings using Python for beginners.
In Python, the index of the first character in a string is 0. So, when we run this program, you're going to see 1 on the terminal because the index is 1.
print("Hello World"[1]) # Output: e
The float function is used to convert a string to a float value.
first = float(input("Enter the first number: "))
We can also change this expression to first + second, which is another way to write this piece of code.
The lower method is used to convert a string to lowercase or to find a character or a sequence of characters.
string = "Hello World"print(string.lower()) # Output: hello worldprint(string.find('o')) # Output: 4print(string.replace('o','a')) # Output: Hella Warld
The in operator can be used to check if a string contains a character.
string = "Python is a programming language for beginners."print('language' in string) # Output: True
Arithmetic Operators in Python
Python has various arithmetic operators that we can use, such as addition (+), subtraction (-), multiplication (*), and division (/).
print(10 + 3) # Output: 13
We also have an augmented assignment operator in Python that means incrementing a variable by a value.
x = 5x += 3 # Output: 8
Operator precedence in Python is similar to math, but we can always use parentheses to change the order of operations.
x = 10 + 3 * 2 # Output: 16
Multiplication and division have a higher order, so they are evaluated first. That's why the answer is 16.
x = 10 + 3 / 2print(x) # Output: 11.5
When we print x, we get 11.5.
x += 3print(x) # Output: 14.5
When we run x += 3, we get 14.5 as the result. When we run x == 13, it will store False in the x variable.
x = 1000 # Output: 1000