Python casting

codepythonic
0


Casting, also known as type conversion, is the process of changing the data type of a variable from one type to another. Python provides several built-in functions for casting variables to different types.


1. Casting to Integer:

   - Use the `int()` function to convert a variable to an integer.

   - Example: `num = int(3.14)` will convert the float value 3.14 to an integer, resulting in `num` being equal to 3.


2. Casting to Float:

   - Use the `float()` function to convert a variable to a float.

   - Example: `pi = float(3)` will convert the integer value 3 to a float, resulting in `pi` being equal to 3.0.


3. Casting to String:

   - Use the `str()` function to convert a variable to a string.

   - Example: `age = 25` followed by `age_str = str(age)` will convert the integer value 25 to a string, resulting in `age_str` being equal to "25".


Now, let's move on to some exercises and questions to reinforce your understanding:


Exercise 1:

Convert the variable `x` from an integer to a float and print its value.

```python

x = 10

x = float(x)

print(x)

```


Exercise 2:

Convert the variable `y` from a float to an integer and print its value.

```python

y = 3.5

y = int(y)

print(y)

```


Exercise 3:

Convert the variable `z` from an integer to a string and print its value.

```python

z = 7

z = str(z)

print(z)

```


Now, let's test your knowledge with a few questions:


Question 1:

What is the result of the following code snippet?

```python

a = 5

b = float(a)

print(b)

```

A) 5.0

B) "5"

C) 5

D) Error


Question 2:

What will be the output of the code below?

```python

c = 3.14

c = str(c)

print(type(c))

```

A) float

B) integer

C) string

D) Error


Question 3:

What is the value of `d` after executing the following code?

```python

d = int("10") + float("3.5")

```

A) 13.5

B) 13

C) "13.5"

D) Error


Answers:

Exercise 1: The output will be 10.0.

Exercise 2: The output will be 3.

Exercise 3: The output will be "7".

Question 1: A) 5.0.

Question 2: C) string.

Question 3: A) 13.5.


I hope this helps! Let me know if you have any further questions.

Tags:

Post a Comment

0Comments

Post a Comment (0)