Python Input & Output Notes
Python Input & Output Notes
Objectives
Understanding Variables & Data Types
Converting Between Data Types
Input and Output Operations:
Using the
printfunctionUsing the
inputfunctionPrint Hello World as a first exercise:
Code:
python print("Hello World!")
Variables & Data Types
Variables: Containers for storing data values.
Use meaningful names (e.g.,
first_name,last_name,age) instead of generic names (e.g.,a,b,c).
Common Data Types
String (str): Sequence of characters.
Example:
python first_name = "John"Integer (int): Whole numbers.
Example:
python age = 20Float: Decimal numbers.
Example:
python interest_rate = 5.2Boolean (bool): Values of True or False.
Example:
python scan_completed = True
Checking Data Types
Use
type(...)to check the data type of a variable:Example:
python print(type(first_name))
Returns:
Important Rules
Variable Naming Convention:
Use lowercase with underscores for normal variables.
Use uppercase with underscores for constants.
Input Handling
Getting Input from the User:
Use
input()to prompt users for information.Example:
python first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") full_name = first_name + " " + last_name print("My name is " + full_name + ".")Converting Input to Desired Data Type:
Input is taken as a string by default. To convert it:
For integers:
python number = int(input("Enter an integer: "))For floats:
python decimal_number = float(input("Enter a decimal number: "))
Converting Between Data Types
Common Conversions:
To convert strings to integers:
int(variable)To convert strings to floats:
float(variable)To convert numbers to strings:
str(variable)Python does not allow concatenating strings and numbers directly. Convert numbers to strings first.
Output Formatting
Use the
print()function effectively, including features likeendto control line endings.Example:
python print("Hello", end=" ") print("World")String Addition (Concatenation):
python full_name = "John" + " " + "Smith"Output:
My name is John Smith.
Comments
Use comments generously to explain code.
Comments can be added anywhere in the program for clarity.
Always write comments before the related code.
Python Keywords
Important keywords to remember include:
if,else,elif,for,while,def,import,print, etc.
Conclusion
Always follow best practices with naming conventions, data types, and code structure to write clean and maintainable Python code.