- Output in Python
- Input in Python
- Printing to Screen – Part 1
- Printing to Screen – Part 2
- Variables
- Comments
- Summary
- Tasks
In Python, you can use the print()
function to display output. The print()
function can take multiple arguments, and you can customize the separator and end character.
print("Hello, World!")
print("Python", "is", "fun", sep="-")
print("Hello", end=" ")
print("World")
Output:
Hello, World!
Python-is-fun
Hello World
To get input from the user, you can use the input()
function. The input()
function reads a line from the input and returns it as a string.
name = input("Enter your name: ")
print(f"Hello, {name}!")
Output:
Enter your name: John
Hello, John!
You can print multiple items in a single print()
statement by separating them with commas.
print("Hello", "World", "!")
Output:
Hello World !
You can customize the separator and end character in the print()
function.
print("Hello", "World", sep="-", end="!")
Output:
Hello-World!
Variables are used to store data that can be used later in the program. You can assign values to variables using the assignment operator =
.
a = 10
b = 50
print("Before: ", a, b)
a, b = b, a
print("After: ", a, b)
Output:
Before: 10 50
After: 50 10
Comments are used to explain the code and make it more readable. In Python, you can use #
for single-line comments and triple quotes '''
or """
for multi-line comments.
# This is a single-line comment
print("Hello, World!") # This is an inline comment
'''
This is a multi-line comment
that spans multiple lines
'''
print("Python")
Output:
Hello, World!
Python
In this chapter, we learned how to use the print()
function to display output, the input()
function to get input from the user, and how to use variables and comments in Python.
- Write a program that asks the user for their name and age, and then prints a message with that information.
- Write a program that prints a multiplication table for numbers 1 to 10.
- Write a program that swaps the values of two variables and prints the result.
- Write a program that includes both single-line and multi-line comments.