kode2go / python

Lessons on learning python programming.
0 stars 0 forks source link

Python Exercises: Q41 #11

Open kode2go opened 3 years ago

kode2go commented 3 years ago
  1. Given:
    a = 10
    b = 20
    mysum = a + b

    Explore the different ways to output variables with the print function that should output the following sum of 10 and 20 is 30, using

    • string concatenation
    • convert variable into str
    • using a tuple
    • new style string formatting using .format
    • using f-string formatting
kode2go commented 3 years ago
a = 10
b = 20
mysum = a + b

#1. Normal string concatenation
print("sum of", a , "and" , b , "is" , mysum) 

#2. convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(mysum)) 

#3. if you want to print in tuple way
print("sum of %s and %s is %s " %(a,b,mysum))  

#4. New style string formatting
print("sum of {} and {} is {}".format(a,b,mysum)) 

print("sum of {0} and {1} is {2}".format(a,b,mysum))

print("sum of {num1} and {num2} is {sum1}".format(num1=a,num2=b,sum1=mysum))

#5. New f-string formatting from Python 3.6:
print(f'sum of {a} and {b} is {mysum}')