Input command in dept ( how to convert string to integer)
In this Python tutorial, we're going to write a program that will ask the year that we were born in, and then it will calculate our age and print it on the terminal.
So, let's start with our input function, input let's print birth here, followed by a colon
and a space. Now let's get the return value and store it in a variable, called birth_year.
So as I told you before, we use an underscore to separate multiple words. Next, we need to calculate the age, so we define another variable called age, and here we do some basic math, currently we are in 2022, so let's write an expression like this. 2022 - birth year.
Now finally lets print age on the terminal. Let's run our program and see what happens.
So, my birth year is 2007, enter, oops, we got an error, what is going on here? So whenever you see this message, that means there is something wrong with your program.
So the problem after the first line we executed we have this birth year variable set
to a string, so whatever we type in the terminal is always treated as a string, even if you type the number, in other words, when we run this program, this birth year variable will be set to a string, with four characters. 2007. This string is different from the actual number 2007 . One is an integer and the other is a string.
Right? So, back to line 2, where this error occurred. At run time, which means when we run our program this expression on the right side of the assignment operator is going to look like this. integer 2022 - string 2007.
Python doesn't know how to interpret or how to evaluate this expression. To fix this problem we need to convert this 2007 into an integer and then we'll be able to subtract it from 2022 and that is easy.
So far you have learned about two built in functions one is print the other is input. We have a few other functions for converting values into different types. So we have int for converting a string into an integer.
So to fix this problem, we need to go back on line 2, and pass this birth year variable to the int function like this. int parenthesis, like this so we pass this string to the int function, int will convert it into an integer and then Python interpreter will be able to evaluate this expression.
Now let's run this program one more time, so birth year is 2007 enter so I am 15 years old.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Input command in dept ( how to convert string to integer)», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.