Halloween Sale: Flat 70% + Addl. 25% Off + 30 Days Extra Lab on all Courses | Use Coupon HS25 in Checkout | Offer Expires In

  Enroll Now

Operations with Other Types

Operators on different types behave differently in Python.

For example, + operator

  • On integers it just sums up the integers

    print(5 + 8)
    

    It will print 13

  • While on strings it paste together(joins) the strings. To print the full name of person having first name as John and last name as Barley

    print("John" + " " + "Barley")
    

    Notice " " here, it adds space while joining the strings. It will print John Barley

Now since we know the + operator we can print a message like this:

print("BMI is " + 25)

Run above code in the notebook. Did it run?

This will not work as you cannot simply sum strings and integers.

How do we fix it then?

To fix this error, you'll need to explicitly convert 25, which is an integer, to a string. You'll need str() to convert a value into a string. str(25) will convert the integer 25 to a string.

Pro Tip - Remember, we can only add variables of same data types

INSTRUCTIONS
  • Define a variable bmi with 25 interger value in it
  • Run print("BMI is " + bmi) on the notebook on the right hand side. Try to understand error message.
  • Now run the below codes in a new cell.
  • Convert bmi to a string and assign it to bmi_str
  • Concatenate "BMI is " and bmi_str and assign the result to message
  • Print message variable

No hints are availble for this assesment

Answer is not availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...