Skip to content
Programs · Program 5-9

Q.Program 5-9: Program to show explicit type conversion.

Punjab PsebTextbookSubjective· 2mImportance★★★★★est
37% · 18/49 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

One program, all three conversion functions: float() widens an int, int() narrows a float, and int()/str() decide whether "5" and 7 are added (12) or joined (75).

The idea (explicit type conversion). Python gives one conversion function per basic type — int(), float(), str() — and the programmer calls them deliberately whenever the current type is not the needed one. The most instructive part is that the same two values can produce completely different results depending on which way you convert, because the resulting types choose the meaning of the operator.

Program

# prog5-9.py
# Program to show explicit type conversion
a = 7        # int
b = 3.0      # float
c = "5"      # str

print(float(a))      # int -> float
print(int(b))        # float -> int
print(int(c) + a)    # str -> int : arithmetic addition
print(str(a) + c)    # int -> str : string concatenation

Expected output

7.0
3
12
75

Line-by-line reasoning

LineConversionResultWhy
float(a)int → float7.0widening; value preserved, gains .0
int(b)float → int3narrowing; fractional part truncated
int(c) + astr → int12"5" becomes 5, so + is addition: 5 + 7

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.