Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • 1. What is User Input in Python?
  • 2. Basic Example
  • 3. Input with Conversion: Numbers
  • 4. Multiple Inputs in One Line
  • 5. List Input for ML or Data Science
  • 7. Advanced Tip: Loop Until Valid Input
  • Summary Table
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Introduction and Basics

Input From User

Nerd Cafe

1. What is User Input in Python?

Definition: User input allows the program to take data from a human using the keyboard while the program is running.

In Python, we use:

input("Prompt message")

Practical Note:

  • The input is always stored as a string by default.

  • You must convert it to numbers (if needed) using int(), float(), etc.

2. Basic Example

name = input("What is your name? ")
print("Hello,", name)

Output:

What is your name? Mr Nerd
Hello, Mr Nerd

3. Input with Conversion: Numbers

Integers

age = int(input("Enter your age: "))
print("You will be", age + 1, "next year.")

Practical Note:

  • int() will cause an error if user enters non-integer like twenty.

  • Use try-except for error handling (covered below).

Float (Decimal)

weight = float(input("Enter your weight (kg): "))
print("Your weight in grams is", weight * 1000)

4. Multiple Inputs in One Line

Example:

x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)

Output:

Enter two numbers separated by space: 5 7
Sum: 12

Practical Note:

  • .split() breaks input into list based on space.

  • You can also split by comma split(',').

5. List Input for ML or Data Science

Often in ML we need to input feature vectors.

features = input("Enter feature values separated by comma: ").split(',')
features = [float(x) for x in features]
print("Feature vector:", features)

Output:

Enter feature values separated by comma: 5.1,3.5,1.4,0.2
Feature vector: [5.1, 3.5, 1.4, 0.2]

Machine Learning Insight:

This method is commonly used to input values into a trained model for prediction:

import numpy as np
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
# model.fit(X_train, y_train)  # Assume already trained

user_input = input("Enter feature values (comma-separated): ")
features = np.array([float(x) for x in user_input.split(',')]).reshape(1, -1)
# prediction = model.predict(features)
# print("Prediction:", prediction)

7. Advanced Tip: Loop Until Valid Input

while True:
    try:
        score = float(input("Enter your score (0 to 100): "))
        if 0 <= score <= 100:
            break
        else:
            print("Score must be between 0 and 100.")
    except ValueError:
        print("Please enter a valid number.")

print("Your score is:", score)

Summary Table

Purpose
Code Example
Notes

Basic text input

name = input()

Always string

Number input

num = int(input()) or float(input())

Convert types

Multiple inputs

a, b = input().split()

Use .split()

List for ML

[float(x) for x in input().split(',')]

For feature vector

Error handling

try-except

Catch invalid inputs

Keywords

input,output,string,integer,float,split,try,except,loop,while,if,elif,else,function,list,tuple,dictionary,conversion,error,prompt,feature, nerd cafe

PreviousPrint FunctionNextData Types

Last updated 2 months ago