☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 2 : Data (Input) : User Input

User Input

Subscribe Contact


Contents

Overview

So far, the variables and data values we have seen have been hardcoded, that is, we've written the data values directly in our code. This is not a very common approach in programming. More often we acquire data from outside of our programs, for example, by reading a file, querying a database, or prompting the user to type in values. Prompting a user is called user input. In Python, to prompt a user for a value, we use the input() function.

Concept: User Input
Full Concepts List: Alphabetical  or By Chapter 

User input in Python is a way to interact with users by allowing them to enter data into your program. This interaction is crucial as it makes your programs dynamic and responsive to the user's needs. In Python, you can gather user input through the input() function. When input() is used, the program pauses and waits for the user to type something into the console and press Enter. The text entered by the user is then returned by input() as a string and can be stored in a variable for further use. For example, name = input("Enter your name: ") will display the prompt 'Enter your name: ' and allow the user to type their name. This makes your Python scripts more interactive, as they can now respond to user-provided information, leading to a more engaging experience. Whether it's asking for a name, a choice, or a specific piece of data, user input is a simple yet powerful tool in your Python programming toolkit.

General Form

The general form of the input() function is:

variable = input("user_prompt")

Here is a code example:

age = input("Plese enter your age: ")

The user would see Please enter your age: on the screen and the cursor would be positioned to the right of the prompt on the same line. When they type in a value and press Enter, their entry is assigned to our variable, age in this example.

It is important to be aware that anything the user types will be read by the input() function as a string (str) data type, even if they enter numbers. Consider the following code example:

age = input("Plese enter your age: ")
print(age)
print(type(age))

The following is an example run of this program and the output after a user enters a value:


Please enter your age: 25
25
class 'str'

Notice that the user entered 25 but when we print(type(age)) it informs us that the data type is a string. Remember that the digits 0 to 9 can be of string data type if surrounded by quotes or, in this case, if entered by a user through the input() function. The more likely intent is that we want the user's age as an integer, so we need to cast the entered string value into an integer value.

Casting

In programming we often need to convert values of one data type into another data type, this process is called casting. There are two types of casting: implicit and explicit. Implicit casting is automatically handled by the Python interpreter when needed, for example, when dividing two integers and the resulting value is a floating-point number. Explicit casting is when the programmer uses built-in functions to intentionally cast one data type to another.

Concept: Casting
Full Concepts List: Alphabetical  or By Chapter 

In programming, we often need to transform (convert) data from one type to another type. In Python, this is accomplished using casting functions. Here is a list of the casting functions:

  • int() - Converts a value to an integer.
  • float() - Converts a value to a floating point number.
  • str() - Converts a value to a string.
  • bool() - Converts a value to a boolean.
  • list() - Converts a value to a list.
  • tuple() - Converts a value to a tuple.
  • set() - Converts a value to a set.
  • dict() - Converts a value to a dictionary.

And an example:

print("Age: " + str(21))
print("Sum: " + str(10 + 20 + 30))

Because the print() function's object need to be strings, it requires us to cast (convert) the numeric values to strings to concatenate those values with our string labels Age and Sum. In this case, we do this using the str() function, which casts numeric values to string values.\

Casting Examples

Let's take a look at examples of implicit and explicit casting with some code.

Implicit Casting Example

Consider the following code:

x = 10
y = 3
z = x / y
print(z)
print(type(z))

We have not yet learned how to do math with Python (we'll get to that over the next few pages), but simple division is accomplished using the division symbol in Python (/). From simple mathematics though, we know that dividing 10 by 3 will not produce a whole number (integer), rather it will result in a decimal number (float). Python automatically sets the appropriate data type of our variable z because the result of the division is a floating-point number rather than an integer and this is implicit casting.

3.3333333333333335
class 'float'

Explicit Casting

In Python, we can explicitly cast using built-in functions such as int(), float() and str(). Each of these functions are used in the following general form:

variable = cast_function(expression)

Where expression is a value or operation that results in a value of a particular data type that you want to convert (cast) to another type.

Consider the following code example:

x = "999"
print(x)
print(type(x))
x = int(x)
print(x)
print(type(x))

And the output:

999
class 'str'
999
class 'int'

Based on the example above, answer the following question...

Question 1

Explain the above code example and the output.


We will use casting frequently throughout our work in this book.

Data Validation

One possible problem we have with user input is, what if the user types in something we do not expect?

Concept: Data Validation
Full Concepts List: Alphabetical  or By Chapter 

Data validation in programming is the process of ensuring that the input data a program receives meets specific criteria and is within acceptable parameters before it is processed or used in computations. This process is crucial for maintaining the integrity and reliability of a program. Validation can involve checking for data type correctness (ensuring an input is an integer when an integer is expected), range constraints (such as verifying dates fall within a certain period), format correctness (like validating email addresses or phone numbers against a specific pattern), and presence of necessary data (ensuring required fields are not empty). Data validation helps prevent errors, inconsistencies, and security vulnerabilities by catching incorrect or malicious data before it can cause problems in the system. It is an essential aspect of robust software development, particularly in applications involving user input, file handling, or network communications. By incorporating thorough data validation routines, programmers can ensure their applications behave predictably and handle invalid or unexpected inputs gracefully.

For example, reusing our input function code above:

age = input("Plese enter your age: ")
print(age)
print(type(age))

Say a user runs this program and enters something like this:

Please enter your age: blahblahblah
blahblahblah
class 'str'

That is an invalid entry, what do we do about it? For now, not much. We need to learn a few more basics of Python and then we will revisit this problem in detail. For now, just be aware that any time we collect data from outside of our program we will need to take steps to validate the data we are receiving is valid.


 





© 2023 John Gordon
Cascade Street Publishing, LLC