Writing your first Python program
Python is a programming language that allows you to give instructions to a computer to perform tasks. Think of it as learning a new language to communicate with your computer!
It’s beginner-friendly and versatile, making it a great first programming language.
Why Choose Python?
-
Easy to Learn: Python reads almost like English, making it accessible for beginners.
- Versatile: Use it for web development, data analysis, automation, game development, and more.
- Clean Syntax: You can write less code to get more done.
- Large Community: With tons of tutorials, tools, and libraries, help is always available.
- Fun to Use: Python makes it exciting to see quick results from your code.
Your first Python program
A Python program is a set of instructions that the computer follows, line by line. Python's simplicity shines in its clean syntax: you don’t need semicolons (;
) at the end of each line, making the code easier to read and write.
Let’s dive into writing your first program!
Writing a program
Use the print()
print("Hello, world!")
When you run this code, the output will be:
Hello, world!
Understanding the code
: This is a function in Python that displays text or data.print()
: This is a string, which is text enclosed in quotation marks. Python will display whatever is inside the quotes."Hello, world!"
Adding comments
Comments explain your code and make it easier to understand. In Python, comments start with a hash symbol (#
).
# This is a comment. Python ignores this line.
print("Hello, world!") # This prints the text on the screen.
Making it your own
Customize your program by changing the text in the print()
print("Welcome to Python programming!")
Output:
Welcome to Python programming!
Common errors and fixes
Missing closing quote:
print("Hello, world!) # Error: Missing closing quote
Fix: Ensure the string starts and ends with the same type of quote.
print("Hello, world!")
Forgotten parentheses:
print "Hello, world!" # Error: Missing parentheses
Fix: Always include parentheses with the print()
print("Hello, world!")
Expanding your knowledge
Once you’re comfortable with the basics, explore these key concepts:
-
Variables: Containers for storing data.
name = "Alice" age = 25 print(name, "is", age, "years old.") # Output: Alice is 25 years old.
-
Data Types: Python can handle text, numbers, Booleans, lists, and more.
-
Control Flow: Use
statements and loops to make decisions or repeat actions.if
if age > 18: print("You're an adult.") else: print("You're a minor.")
-
Functions: Reusable pieces of code that perform tasks.
def greet(name): print("Hi,", name) greet("Alice") greet("Bob") # Output: Hi, Alice # Hi, Bob
What can you do with Python?
- Create simple programs like calculators.
- Automate tasks like renaming files or sending emails.
- Build small games or apps.
- Analyze data or work with spreadsheets.
Conclusion
Congratulations! You’ve written your first Python program and learned about the print()