DEV Community

Ajmal Hasan
Ajmal Hasan

Posted on

2

Beginner's Guide to Python: A Quick Tutorial - 2

Python is a versatile programming language, and these examples will help you get started with basic concepts step by step. Let's dive into practical coding!


1. Print Statements

A simple way to display messages or results.

# Print a message
print("Hello, Python World!")
Enter fullscreen mode Exit fullscreen mode

2. Variables and Data Types

Variables store data, and Python automatically identifies the data type.

# Variables and their types
name = "John"       # String
age = 30            # Integer
height = 5.9        # Float
is_programmer = True  # Boolean

# Print them
print(f"My name is {name}, I'm {age} years old, and my height is {height} meters.")
print(f"Am I a programmer? {is_programmer}")
Enter fullscreen mode Exit fullscreen mode

3. Taking Input

Use the input() function to accept user input.

# Get input from the user
name = input("What's your name? ")
print(f"Welcome, {name}!")
Enter fullscreen mode Exit fullscreen mode

4. If-Else Statements

Control the flow of your program based on conditions.

age = int(input("Enter your age: "))

if age >= 18:
    print("You're eligible to vote!")
else:
    print("You're not eligible to vote yet.")
Enter fullscreen mode Exit fullscreen mode

5. Loops

Loops help execute a block of code multiple times.

a) For Loop

# Print numbers from 1 to 5
for i in range(1, 6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

b) While Loop

# Countdown from 5
count = 5
while count > 0:
    print(count)
    count -= 1
Enter fullscreen mode Exit fullscreen mode

6. Functions

Functions are reusable blocks of code.

# Define a function
def greet(name):
    return f"Hello, {name}!"

# Call the function
print(greet("Alice"))
Enter fullscreen mode Exit fullscreen mode

7. Lists

Lists store multiple items in a single variable.

# Create a list
fruits = ["apple", "banana", "cherry"]

# Access and modify elements
print(fruits[1])  # Output: banana
fruits.append("orange")
print(fruits)     # Output: ['apple', 'banana', 'cherry', 'orange']
Enter fullscreen mode Exit fullscreen mode

8. Dictionaries

Dictionaries store key-value pairs.

# Create a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

# Access and update values
print(person["name"])  # Output: Alice
person["age"] = 26
print(person)
Enter fullscreen mode Exit fullscreen mode

9. File Handling

Read and write to files.

a) Writing to a File

with open("example.txt", "w") as file:
    file.write("Hello, Python!")
Enter fullscreen mode Exit fullscreen mode

b) Reading from a File

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
Enter fullscreen mode Exit fullscreen mode

10. Simple Calculator

Combine multiple concepts to create a basic calculator.

def calculator():
    num1 = float(input("Enter the first number: "))
    operator = input("Enter an operator (+, -, *, /): ")
    num2 = float(input("Enter the second number: "))

    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 != 0:
            result = num1 / num2
        else:
            result = "Error: Division by zero!"
    else:
        result = "Invalid operator!"

    print(f"The result is: {result}")

calculator()
Enter fullscreen mode Exit fullscreen mode

11. Handling Errors

Handle unexpected errors gracefully.

try:
    num = int(input("Enter a number: "))
    print(100 / num)
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("Invalid input! Please enter a number.")
Enter fullscreen mode Exit fullscreen mode

12. A Fun Game: Guess the Number

Test your Python skills with a mini-game.

import random

# Generate a random number
secret_number = random.randint(1, 10)

print("I'm thinking of a number between 1 and 10. Can you guess it?")
while True:
    guess = int(input("Your guess: "))
    if guess == secret_number:
        print("Congratulations! You guessed it!")
        break
    elif guess < secret_number:
        print("Too low! Try again.")
    else:
        print("Too high! Try again.")
Enter fullscreen mode Exit fullscreen mode

Next Steps for Beginners

  1. Practice: Try creating your own mini-projects like a to-do list or a quiz game.
  2. Learn Libraries: Explore NumPy, Pandas, and Matplotlib for advanced tasks.
  3. Join Communities: Engage with Python communities for learning and support.

Happy coding! πŸŽ‰

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay