I was excited for today’s lesson. This is where the fun begins!
The reason it’s fun for me is because this is the part where I start learning stuff I can really work with. That doesn’t mean everything else wasn’t important. I mean, this is the foundation. You’ll see though.
Today’s lesson was on collecting info from the user and converting strings and numbers.
We play on mobile apps all day without thinking about how the app works behind the scenes.
If I want to ask you your name and I want an answer from you, here’s how it’ll code:
your_name = input(“What’s your name? “)
Yep. We use the input function. The code doesn’t continue until the user responds and presses Enter.
Ok. Now what if I ask you your age and I want to figure out how old you’ll be in 32 years?
age = input(“Age: “)
actual_age = int(age)
year_sum = actual_age + 32
print(“You’ll be ” + year_sum + ” in 32 years.”)
So, I know that was a few more lines of code, but let’s work through this together.
line 1 >> We ask for your age. And wait until we get a response from you.
line 2 >> we convert your age to an actual integer and assign it to a new variable. The input is initially considered a ‘string’ – even numbers. So, in order for your age to be treated as an actual number, we have to convert it to an int (integer for short).
line 3 >> Now, we want to know your age in 32 years. We assign THAT number to another variable. Your age + 32.
line 4>> Finally, we print out how old you’ll be in 32 years by using concatenations. Remember those? 🙂
Just like we converted a string to an integer, a string can be converted to a float. Also, numbers can be converted to a string by using str.
You want examples? I’m glad you asked!
Ex 1: Convert a string to a float. (Side note: A float is a decimal.) You’ll use the float function when you’re working with money or weight.
convert_to_a_float = float(“44.38”)
Ex 2: Convert an integer to a string.
look_at_the_string = str(99)
Ex 3: Convert a float to a string.
same_thing = str(55.79)
Man today I did some ‘splainin, huh? LOL
That’s enough for tonight. We’ll continue another lesson tomorrow.
Thanks for reading this far!