Python-03

/

/

/

python/03-convert-types

Convert Your Data Types

Let's create a simple calculator together and understand the importance of providing correct data-types. And most importantly, how to control it.

Python-03

/

/

/

python/03-convert-types

Convert Your Data Types

Let's create a simple calculator together and understand the importance of providing correct data-types. And most importantly, how to control it.

Lesson Objectives

  • Get user input with input() function.

  • Check types withy type() function.

  • Convert Types in python

  • Create a simple calculator

Are you Ready?

Summary

Intro

You've learnt about basic and collection data types in python and how to store all that data in variables.

Let's practice and create a very simple calculator together, and I will explain you a few more things along the way.

We will need to ask user to provide us 2 numbers and then we can join them and report the sum of 2 numbers. I know it sounds too simple, but it will be a good excercise.

Input

To ask user for an input we can use built-in function called input().

Since it's a function we need to use its name and then place parenthesis for any arguments. There are functions that don't need any arguments, or have many of them, but in case of input it needs a string with instructions that will be shown to the user.

This function will return you a string with whatever the user is going to provide, so let's get 2 numbers and then add them together.

Like this:

num_a = input(’Enter First Number: )
num_b = input(’Enter Second Number: )
total = num_a + num_b
print(total)

Now if you run this code you will notice that you need to provide input in the console. I will provide 2 and 3.

And then we can see we printed the total value as 23.

Hold on a second, 2+3 is not equal 23. What's going on?

The thing is that when we used input() function, we actually got a string back. So we are not making an arithmetic math here, we are just adding 2 strings together.

Similar to `ab` + `cd` = 'abcd'


So if we want to do math, we need to convert our strings to numbers first. But before that, let's make a quick test by using another great function called type(). This allows you to find out what is a type of any object in your code, and you can print the result.

print(type(num_a)) #str
Convert Types in Python

Alright, so we know that values we get from input are strings. So let's convert them to integers like this:

# Get User INput
str_num_a = input(’Enter First Number: )
str_num_b = input(’Enter Second Number: )

# Convert String to Int
num_a = int(str_num_a)
num_b = int(str_num_b)

# Calculate Total
total = num_a + num_b
print(total)

This time if you run your code and provide 2 and 3 you will get 5 as total.
So this time we are actually doing math!

Floating numbers

But what if we decide to add floating numbers like 2.5 + 2.5 ?

Alright, so we can't convert "2.5" into an integer…

So let's try to convert it to a float number.

# Get User INput
str_num_a = input(’Enter First Number: )
str_num_b = input(’Enter Second Number: )

# Convert String to Int
num_a = float(str_num_a)
num_b = float(str_num_b)

# Calculate Total
total = num_a + num_b
print(total)

This time 2.5 + 2.75 = 5.25

It works again.

Convert Types

Alright so you've just learnt about converting data types. And it's not just string to integers or floats. We can convert all data types between each other as long as it make sense.

You won't get great results if you try to convert random text into an integer…

Here are other built-in functions you can use to convert your data.

# Functions for DataType Convertion
str()
float()
int()
bool()

list()
tuple()
set()
dict()

I've already showed you that we can convert lists to sets and back previously, and now we changed strings to numbers. And it will be important to make sure you provide correct data types.

Examples

Alright, let's go through multiple examples quickly, so you get an idea of what's going on when you convert your basic data types.

# Numbers
x          = 10
str_x      = str(x)       # Convert integer to string: '10'
float_x    = float(x)     # Convert integer to float: 10.0
bool_x     = bool(x)      # Convert integer to boolean: True (non-zero is True)
bool_neg_x = bool(0)      # Convert 0 to boolean: False

# Strings
s          = "123"
int_s      = int(s)       # Convert string to integer: 123
float_s    = float(s)     # Convert string to float: 123.0
bool_s     = bool(s)      # Convert  string to boolean: True (if not empty)
bool_empty = bool("")     # Convert empty string to boolean: False
# Booleans
bool_true  = bool(1)       # True
bool_false = bool(0)      # False
bool_list  = bool([])      # Convert empty list to boolean: False
bool_dict  = bool({})      # Convert empty dict to boolean: False
bool_str   = bool("Hello")  # Convert non-empty string to boolean: True
Outro

By now you should have a good understanding of basic data types in python and how to control them. It's very crucial to keep track of what data type is your data, so you can provide correct arguments later on.

And as you've seen with our simple calculator, if you forget to convert strings to numbers, you might have a faulty calculator.

HomeWork

Now it's time to build your own calculator.

Try different operators and make your code a little different to mind. You won't learn by simple copy-pasting... You learn by actually experimenting yourself.

⌨️ Happy Coding!

Questions:

What should I write in __init__.py file?

What should I write in __init__.py file?

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API