Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python How to change the type of values in Python [Tutorial]

James

Active Coder
Hello, I am new to codeforum.org and the main programming language I use is python, so I thought the best way to introduce myself is to make a little tutorial.
In this tutorial I will be showing you how to change the types of values and find out the types of values, example, changing integers to string, booleans to string, strings to integers, etc.

Okay, so let's start with INT - STR
myInt = 5
So first, we created the variable "myInt" this is the integer that we will be changing into a string
Python:
# Here we are going to be using the str() built-in function to change the int to a string
myInt = 5
myStr = str(myInt)
print(myStr)
It's as simple as that.
Now, let us try some other types.
Python:
#Turning a boolean into a string
myBool = True
myString = str(myBool)
Python:
#Turning a string into an int
myString = "555"
myInt = int(myString)

Now to sum all that up,
str() - Turn into string
int() - Turn into integer
bool() -- Turn into bool

Okay, so after we've done that you may now want to know how to find the type of a value.
To do this we simply use the built-in function type()
print(type(55)) # Would output <class 'int'>
If you wanted to check if the type is a value you can do something like,
Python:
if type(55) == int:
    print(True)
else:
    print(False)

Hoped this helped people out!
 
One thing worth mentioning is that int() does need to be used carefully or else it will throw an error.
For example, you cannot turn a non-numerical string into an integer.

Here's an example (below you will see how to handle the errors without breaking your Python script)

Python:
string = 'hello'
int = int(string)
print(int)

ERROR:
ValueError: invalid literal for int() with base 10: 'hello'

This is because 'hello' is a string and can never become an integer. In other languages, using a string-to-int function may change 'hello' to either 1 or 0 to represent true/false, but in Python it will prevent your code from running.

However, we can use isdigit() to see if a string is eligible to become an integer:
Python:
string = 'hello'
if(string.isdigit()):
    value = int(string)
else:
    value = "The string " + string + " is not able to become an integer."
print(value)

This works and if the string is a number, it will become an integer. If it is not, we will see "The string hello is not able to become an integer."

We can change our string to = '5', the string version of the integer 5.
In this case, our script just prints out 5 - a valid integer.

Something worth noting is that we can use a TRY / EXCEPTION combo to prevent Python from breaking.
Here we go!
Python:
string = 'hello'
try:
    value = int(string)
    print("Yay, the value " + value + " is an integer now!")
except ValueError:
    print("The string " + string + " cannot become an integer, but the error won't break this script from running.")

print("See? No break!")

In the first line, we say our string is = to 'hello'
As we know from the steps above, there is no way for this to suddenly become a valid integer.
Instead of just attempting to convert it, we incorporate the 'try' functionality. This tells Python "hey, we want you to TRY this code block...but if there's an error, do something else."
We then follow the try code segment with the 'except' block. ValueError is the type of exception Python will throw at us if the string cannot become an integer, so we use that.
In this case, we see: "The string hello cannot become an integer, but the error won't break this script from running." followed by "See? No break!" which proves the script hasn't stopped because of our error.

If we change string to = 33, our script will print out "Yay, the value 33 is an integer now!"

~~
Feel free to test this out on the official Code Forum online compiler/interpreter!
https://ide.codeforum.org/
Just use the drop down to select Python (3.x+ version)

I am still learning Python and this is my first TRY/EXCEPT code in Python. I know it works as I tested it on my computer, but feel free to test it out online or on your own computer if you don't believe me! And then show me some love for learning / teaching simultaneously ;)
 
Thanks
One thing worth mentioning is that int() does need to be used carefully or else it will throw an error.
For example, you cannot turn a non-numerical string into an integer.

Here's an example (below you will see how to handle the errors without breaking your Python script)

Python:
string = 'hello'
int = int(string)
print(int)

ERROR:
ValueError: invalid literal for int() with base 10: 'hello'

This is because 'hello' is a string and can never become an integer. In other languages, using a string-to-int function may change 'hello' to either 1 or 0 to represent true/false, but in Python it will prevent your code from running.

However, we can use isdigit() to see if a string is eligible to become an integer:
Python:
string = 'hello'
if(string.isdigit()):
    value = int(string)
else:
    value = "The string " + string + " is not able to become an integer."
print(value)

This works and if the string is a number, it will become an integer. If it is not, we will see "The string hello is not able to become an integer."

We can change our string to = '5', the string version of the integer 5.
In this case, our script just prints out 5 - a valid integer.

Something worth noting is that we can use a TRY / EXCEPTION combo to prevent Python from breaking.
Here we go!
Python:
string = 'hello'
try:
    value = int(string)
    print("Yay, the value " + value + " is an integer now!")
except ValueError:
    print("The string " + string + " cannot become an integer, but the error won't break this script from running.")

print("See? No break!")

In the first line, we say our string is = to 'hello'
As we know from the steps above, there is no way for this to suddenly become a valid integer.
Instead of just attempting to convert it, we incorporate the 'try' functionality. This tells Python "hey, we want you to TRY this code block...but if there's an error, do something else."
We then follow the try code segment with the 'except' block. ValueError is the type of exception Python will throw at us if the string cannot become an integer, so we use that.
In this case, we see: "The string hello cannot become an integer, but the error won't break this script from running." followed by "See? No break!" which proves the script hasn't stopped because of our error.

If we change string to = 33, our script will print out "Yay, the value 33 is an integer now!"

~~
Feel free to test this out on the official Code Forum online compiler/interpreter!
https://ide.codeforum.org/
Just use the drop down to select Python (3.x+ version)

I am still learning Python and this is my first TRY/EXCEPT code in Python. I know it works as I tested it on my computer, but feel free to test it out online or on your own computer if you don't believe me! And then show me some love for learning / teaching simultaneously ;)
Thanks for adding to this
 
Back
Top Bottom