0% found this document useful (0 votes)
11 views19 pages

Casting in Python

Uploaded by

laibaabbasi6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views19 pages

Casting in Python

Uploaded by

laibaabbasi6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Casting in Python

“Changing data types easily”


Learning Objective
• Understand what casting is.

• Learn how to convert between data types:

• int() → Integer

• float() → Decimal

• str() → String

• Solve real-world problems using casting


What is Casting?
• Casting means changing one type of data into
another.

• Example:

 "10" (text) → 10 (number)

• Icon: Arrows changing a text box into a number.


Types of Casting
• int() → whole numbers (✊ fist)

• float() → numbers with decimals (🌊 wavy lines)

• str() → text/words (👐 open hands)


Data Types
• Python has various standard data types including:
Data Types.....
• int → (Whole numbers 1, 2,3.. 5, 12 ..)

• float → Numbers with a point (2.5, 3.14…)

• string → Words, sentences, or numbers as text ("123",


"Hello")

• Ask: What type is 10? What about "10"?


Why Do We Need Casting?
• Sometimes we need to do math with numbers that are
stored as text.
• Example:

• Visual: Cross mark on wrong code, check mark on correct code.


• Key note: input() always returns string, must cast for
calculations.
Real-Life Analogy
• Casting is like changing clothes for your data.

 Example: “You can’t add the word ‘ten’ to 5 — you must


turn it into a number first.”
Activity: Fix the Broken Code!
1-Pizza Slices Crisis

• Fix → int(slices)
2-Game Over Message

• Fix → str(score)
Activity: Fix the Broken Code!.......

• Science Experiment

• Fix → float(temp) + 1.5


Practice Task
• Convert:

• "8" → int

• 5 → str

• 3 → float

• Converting Integer to String


• Converting Float to integer
• Converting String To integer
• Write a program:

• user_age = input("Enter your age: ")


• print("Next year you will be " + str(int(user_age) + 1))
Common Mistakes
• Forgetting to cast strings before math.

• Casting non-numeric strings → int("hello") → Error

• Losing decimal precision with int().


Quick Quiz
• What does float(5) become?”

• “Which function converts 3.7 → 3?”

• Fix this:
Quick Quiz(Solution)
• What does float(5) become?

• Answer: 5.0 (an integer 5 is converted into a float 5.0)

• Which function converts 3.7 → 3?

• Answer: int(3.7) (it removes the decimal part and gives 3)


Quick Quiz(Solution)
• Fix this code:

Correct Code:

Answer: 17.5
Correct Code....
• 1. Pizza Slices Crisis

2. Game Over Message


Correct Code....
• 3. Science Experiment

Fixed Code:
Thank You.

You might also like