Python Code Examples: A Beginner's Guide

Python Code Examples: A Beginner's Guide
Hey there! If you're just starting out in the world of programming, Python is an amazing place to begin. It's super popular, easy to read, and versatile enough for almost anything – from web development and data analysis to AI. Think of it as learning to ride a bike with training wheels; it gives you a solid foundation without being overly complicated.
Let's dive into some basic concepts with simple examples. You can just copy these code snippets and try them out yourself!
1. Printing Text (Hello World!)
The very first thing most programmers learn is how to make their program say "Hello World!" In Python, it's incredibly simple.
Python
print("Hello, World!")
What's happening here?
print() is a built-in function that displays whatever you put inside the parentheses () on your screen.
The text "Hello, World!" is a string, which is just a fancy way of saying text. We put it inside double quotes "" so Python knows it's text.
2. Variables: Storing Information
Think of variables as named boxes where you can store different kinds of information.
Python
# Storing a number
age = 30
# Storing text (a string)
name = "Kamal"
# Storing a true/false value (Boolean)
is_student = True
print(name)
print(age)
print(is_student)
What's happening here?
We're creating variables called age, name, and is_student.
The = sign is the assignment operator; it puts the value on the right into the variable on the left.
Python figures out what type of data you're storing automatically (like number, text, true/false).
3. Basic Math Operations
Python can do all your basic math for you!
Python
num1 = 10
num2 = 5
add_result = num1 + num2
subtract_result = num1 - num2
multiply_result = num1 * num2
divide_result = num1 / num2 # This will give a float (decimal)
power_result = num1 ** 2 # num1 to the power of 2 (10*10)
print("Addition:", add_result)
print("Subtraction:", subtract_result)
print("Multiplication:", multiply_result)
print("Division:", divide_result)
print("Power:", power_result)
What's happening here?
We're performing addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**).
print() can also combine text with variable values using a comma ,.
4. Conditional Statements (If, Elif, Else): Making Decisions
Programs often need to make decisions. if, elif (else if), and else statements let them do just that.
Python
temperature = 25
if temperature > 30:
print("It's a hot day!")
elif temperature >= 20: # This means between 20 and 30
print("It's a pleasant day.")
else:
print("It's a bit chilly.")
What's happening here?
The if statement checks a condition. If it's True, the code indented below it runs.
elif checks another condition if the if condition was False.
else runs if none of the above conditions were True.
Indentation matters in Python! The spaces before print() tell Python which lines belong to which if/elif/else block.
5. Loops: Repeating Actions
Loops are super handy when you need to do something multiple times without writing the same code over and over.
For Loop: For a known number of repetitions
Python
# Printing numbers from 0 to 4
for i in range(5):
print(i)
# Looping through a list of items
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop: For repeating as long as a condition is true
Python
count = 0
while count < 3:
print("Count is:", count)
count = count + 1 # Or count += 1
What's happening here?
for i in range(5) means "for each number from 0 up to (but not including) 5".
for fruit in fruits means "for each item in the fruits list".
while count < 3 means "keep repeating as long as count is less than 3".
Remember to change the condition inside a while loop (like count = count + 1), otherwise, it might run forever!
6. Functions: Reusable Blocks of Code
Functions let you group a set of instructions together so you can use them multiple times without rewriting them.
Python
# Defining a function that greets someone
def greet(name):
print("Hello,", name + "!")
# Calling the function
greet("Nimal")
greet("Sarath")
# Function that adds two numbers and returns the result
def add_numbers(a, b):
result = a + b
return result
sum_of_two = add_numbers(7, 3)
print("The sum is:", sum_of_two)
What's happening here?
def is used to define a function.
greet(name) means the greet function takes one piece of information (called an argument), which we'll refer to as name inside the function.
return sends a value back from the function.
Wrapping Up Python
This is just the tip of the iceberg, but it gives you a solid start with Python. The best way to learn is by doing! Try changing these examples, building small programs, and exploring more on your own. Good luck!
Comments
Post a Comment