Site icon Console Flare Blog

User Input and Type Casting in Python for Beginners

User Input and Type Casting in Python for Beginners

User Input in Python and Type Casting for Beginners

User input and type casting are two important ideas that you need to understand early on when you start learning Python.
These help you make your programs interactive, dynamic, and realistic, just like apps in the real world, where users enter data and the program reacts in a certain way.


User Input in Python

What does the input() function do in Python?

To put it simply, input() is a command that lets your program get information from the user.

Python sees what you type as a string when the program is running.

For example:

name = input("Enter your name: ")
print("Welcome", name)

If you enter Rahul, the output will be:

Welcome Rahul

In this case, input() takes the name you typed, saves it in the name variable, and prints it.

________________________________________________________________________________________________________________

Why do we need user input?

Think about making:

An app for a calculator

A form to sign up online

A calculator for bills or EMIs

In each of these situations, the program needs to get information from the user, such as numbers, names, or prices.
Your code can’t respond to real-world data unless a user gives it input.

Example (without user input):

num1 = 10
num2 = 20
print(num1 + num2)

No matter how many times you run this, the result is always 30.

But with user input:

num1 = input("Enter first number: ")

num2 = input("Enter second number: ")

print(num1 + num2)

Entering 10 and 20 will result in 1020, not 30.
The reason for this is that input is always a string. Let’s examine that next.


The input’s default data type is

Even if you type numbers, Python treats everything you enter using input() as a string data type.

age = input("Enter your age: ")
print(type(age))

Output:

<class 'str'>

Therefore, Python interprets 25 as ’25’ (string) even if you type it.


Why Does “10 + 20” Turn Into “1020”?

Python joins strings rather than adding them numerically. Concatenation is the term for this process.

Example:

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = num1 + num2
print(result)

Input:

10
20

Output:

1020

Since “10” + “20” = “1020,” both are strings.

In order to correct this, input values must be converted into the appropriate type, which is where type casting is useful.


Display a Message in input()

A message telling the user what to type can be added inside input().

city = input("Enter your city name: ")
print("You live in", city)

Prompt messages are always used by good programs to help users.


Getting Numbers as Inputs

You need to change the string to an integer or a float in order to do math.

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
add = num1 + num2
print("Addition is:", add)

Now, if you put in 10 and 20, you get:

Addition is: 30

Example from Real Life: EMI Calculator

Suppose you wish to figure out a fixed 6-month EMI of ₹600.

emi = 600
months = int(input("Enter number of months: "))
total = emi * months
print("Total payment will be:", total)

If you enter 6, the result will be:

Total payment will be: 3600

Interactive programs operate like this.


Practice Exercises

Try writing:

A basic interest calculator that accepts user input

A tiny calculator with addition, subtraction, multiplication, and division functions

Determine the user’s age by asking for their birth year.


Python Type Casting

Knowing that user input always results in a string, type casting enables you to change data types as necessary.


Type casting: what is it?

Type casting is the process of converting one data type to another.

For example:

Convert “25” from a string to an integer.

Float 2.5 to integer 2 conversion

Convert the number 5 to the string “5”

We take this action to enable Python to execute proper operations.


The Reasons for the Need for Type Casting

Suppose you are developing a shopping cart.

The user types in:

Enter product price: 100
Enter quantity: 3

Both are strings by default.
Python will display an error or produce the incorrect result if you enter price * quantity.

Thus, you must convert them:

price = int(input("Enter product price: "))
quantity = int(input("Enter quantity: "))
total = price * quantity
print("Total amount is:", total)

Output:

Total amount is: 300

Regular Type Casting Operations

Function Description
int() Converts data into an integer
float() Converts data into a float
str() Converts data into a string
bool() Converts data into Boolean (True/False)

1. int() – Convert to Integer

Example 1: Float to Int

x = 4.9
y = int(x)
print(y) # 4

Decimal part gets removed.

Example 2: Bool to Int

print(int(True)) # 1
print(int(False)) # 0

Example 3: String to Int

num = "123"
print(int(num)) # 123

An error will be displayed if the string contains alphabets like “Python.”


2. float() – Convert to Float

Example 1: Int to Float

x = 5
y = float(x)
print(y) # 5.0

Example 2: Bool to Float

print(float(True)) # 1.0
print(float(False)) # 0.0

Example 3: String to Float

num = "123.5"
print(float(num)) # 123.5

An error is displayed if you attempt to use int(“123.5”).
However, you can:

int(float("123.5")) # 123

3. str() – Convert to String

Any data type can be safely converted to a string using str().

age = 25
print(str(age)) # '25'
print(type(str(age))) # <class 'str'>

When displaying messages with numbers, this is helpful.

name = "Rahul"
age = 25
print("Hello " + name + ", you are " + str(age) + " years old.")

Output:

Hello Rahul, you are 25 years old.

4. bool() – Convert to Boolean

Boolean means True or False.

Python treats:

Examples:

print(bool(0)) # False
print(bool("")) # False
print(bool(" ")) # True (space is not empty)
print(bool(123)) # True
print(bool("Python")) # True

Important:
0 (integer) is False
"0" (string) is True — because it’s not empty.


Applications of Type Casting in Real Life

User input is converted to an integer for computations.

Converting string data from a file to numeric values

Verifying True/False fields on switches or login forms

Example:

marks = int(input("Enter your marks: "))
if marks >= 40:
print("You Passed!")
else:
print("You Failed!")

Quick Summary

Function Converts From Converts To Example
int() String/Float Integer int(“10”) → 10
float() String/Int Float float(“3.5”) → 3.5
str() Any String str(25) → “25”
bool() Any Boolean bool(“”) → False

Resource:

Official Python Input Documentation

W3Schools Python Input Tutorial

Activities for Practice

  1. Create a program that uses user input (length, width) to determine a rectangle’s area.
  2. Create a program that prints the average of three subjects’ grades.
  3. Determine and show the user’s age after asking for their name and birth year.
  4. Make a check for the login that yields. If the password and username are both non-empty strings, then the statement is accurate.

Conclusion:

The fusion of data science in the finance sector is not just a technological evolution but also a fundamental shift in the way the financial industry operates. From predictive analytics to personalized financial services, the applications of data science are reshaping traditional practices and opening up new possibilities. As we all move forward, the synergy between finance and data science will continue to evolve, creating a more robust, efficient, and resilient financial ecosystem. In this data-driven era, those who embrace the power of data science will be at the forefront of innovations and success in the world of finance.

Want to know what else can be done by Data Science?

If you wish to learn more about data science or want to advance your career in the data science field, feel free to join our free workshop on Master’s in Data Science with Power BI, where you will get to know how exactly the data science field works and why companies are ready to pay handsome salaries in this field.

In this workshop, you will get to know each tool and technology from scratch, which will make you skillfully eligible for any data science profile.

To join this workshop, register yourself on ConsoleFlare, and we will call you back.

Thinking, Why Console Flare?

Recently, ConsoleFlare has been recognized as one of the Top 10 Most Promising Data Science Training Institutes of 2023.

Console Flare offers the opportunity to learn Data Science in Hindi, just like how you speak daily.
Console Flare believes in the idea of “What to learn and what not to learn,” and this can be seen in their curriculum structure. They have designed their program based on what you need to learn for data science and nothing else.

Want more reasons?

Register yourself on ConsoleFlare, and we will call you back.
Log in or sign up to view
See posts, photos, and more on Facebook.

Console Flare

Exit mobile version