Skip to content

Latest commit

 

History

History
131 lines (92 loc) · 2.67 KB

README.md

File metadata and controls

131 lines (92 loc) · 2.67 KB

Chapter 2: Output and Input Basics

Table of Contents

Output in Python

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

Input in Python

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!

Printing to Screen – Part 1

You can print multiple items in a single print() statement by separating them with commas.

print("Hello", "World", "!")

Output:

Hello World !

Printing to Screen – Part 2

You can customize the separator and end character in the print() function.

print("Hello", "World", sep="-", end="!")

Output:

Hello-World!

Variables

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

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

Summary

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.

Tasks

  1. Write a program that asks the user for their name and age, and then prints a message with that information.
  2. Write a program that prints a multiplication table for numbers 1 to 10.
  3. Write a program that swaps the values of two variables and prints the result.
  4. Write a program that includes both single-line and multi-line comments.

Next Chapter: Data Types and Operators