You can copy the code and play around with it. With the integer value, we were able to subtract the user's birth year from the current year to get and print their actual age. We then requested the user's birth year: userBirthYear = input("What is your birth year?")Īfter that we converted the user's birth year (which was returned to us as a string) to an integer using the int() function. With this, we were able to get and store the current year in a variable. In the code above, we first imported the date class from the datetime module. UserAge = currentYear - convertUserBirthYear UserBirthYear = input("What is your birth year?")ĬonvertUserBirthYear = int(userBirthYear) In the next example, similar to the last one, we will get a user's input and perform some calculations to display their age. We converted the userAge variable and stored it in a variable called convertUserAge and then performed our operation again to get the expected result. Now let's convert the variable to an integer and perform the same operation: userAge = "10" In the example above, we are adding 8 to the userAge variable which is a string – but this shows an error because the interpreter assumes we are trying to add (concatenate) two strings. # TypeError: can only concatenate str (not "int") to str Here is an example to help you understand: userAge = "10" So we pass the string to be converted as an argument in the int() function. Here is what the syntax looks like: int(string_value) In Python, we can use the built in int() function to convert strings to integers. In this article, we'll see how to convert a string to an integer in Python with some examples. In both cases, the values returned are strings so we cannot perform mathematical operations with them as this will throw an error our way. Similarly, there are cases where you might want to perform mathematical operations on string values. When creating a program, you may need to get numerical input from users and perform various mathematical operations on the value.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |