Python is a very popular and easy-to-learn programming language. Python is designed with a philosophy that prioritizes code readability, making it suitable for beginners who are new to programming.
Why is Python the favorite choice of many programmers? Python has syntax similar to everyday English, making it easy to understand. Imagine reading a recipe written in clear and easy-to-follow language. Python is also used for many purposes, from web development, data analysis, machine learning, to artificial intelligence.
For more complete information about Python, you can visit the docs.python.org. This documentation serves as the main reference source that is always updated with the latest Python features.
The tradition in learning programming is to create the first program that displays the text "Hello World!". This is a simple way to ensure Python is installed correctly and you're ready for coding.
hello.py
print("Hello World!")
The print() command is a built-in Python function used to display text or data to the screen. Whatever you write inside the parentheses will be displayed as output.
Interactive mode allows you to write and run Python code directly in the terminal. This is very useful for testing simple code or quick experiments.
Here's how to use interactive mode. First open a terminal or command prompt, then type python or python3 and press Enter. You'll see the >>> prompt indicating Python is ready to receive commands. Next, write Python code and press Enter to execute it.
terminal
$ python3Python 3.8.5 (default, Sep 4 2020, 02:22:02)[Clang 10.0.0 ] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print("Hello World!")Hello World!>>> 2 + 35>>> name = "Alice">>> print(f"Hello, {name}!")Hello, Alice!>>>
Script mode is a way to run saved Python files. This is suitable for more complex programs or programs you want to save for repeated use.
The steps to run Python scripts are quite simple. First create a file with .py extension using a text editor, then write Python code inside the file and save it. After that, open a terminal and navigate to the folder where the file is saved, then run it with the command python filename.py.
greeting.py
# Simple program to greet usersname = input("What's your name? ")age = input("How old are you? ")print(f"Hello {name}!")print(f"You are {age} years old.")print("Happy learning Python!")
To run the file above:
terminal
$ python3 greeting.pyWhat's your name? JohnHow old are you? 20Hello John!You are 20 years old.Happy learning Python!
Jupyter is an interactive environment very popular for data science and learning. Imagine Jupyter like a digital notebook that can run code. Jupyter allows you to write code, see results immediately, and add explanations in one document.
Jupyter has many advantages. You can run code per cell or section, output results are immediately visible below the code, you can add text explanations, images, and graphs, and it's ideal for experiments, data analysis, and learning.
Using Jupyter is quite easy. First install Jupyter via pip:
terminal
# Install jupyterpip install jupyter# Or install via Anaconda (recommended)conda install jupyter
Second, run Jupyter Lab:
terminal
# Run Jupyter Labjupyter lab# Will open browser with Jupyter interface
Third, create a new notebook with .ipynb extension and write code in cells, then press Shift+Enter to execute.
Example usage in Jupyter:
jupyter_example.ipynb
# Cell 1: Import and setupimport math# Cell 2: Variables and operationsradius = 5area = math.pi * radius ** 2print(f"Circle area with radius {radius} is {area:.2f}")# Cell 3: Create functiondef calculate_circle_area(r): """Function to calculate circle area""" return math.pi * r ** 2# Cell 4: Test functiontest_radius = 7result = calculate_circle_area(test_radius)print(f"Circle area with radius {test_radius} is {result:.2f}")
Python has several basic data types you need to understand. Variables in Python are like boxes that can store various types of data, and you can give labels or names to those boxes.
User interaction is an important part of programming. Like a conversation, your program can ask users questions and provide answers or information.
input_output.py
# Input from useruser_name = input("Enter your name: ")user_age = input("Enter your age: ")# Data type conversionage_number = int(user_age) # Convert string to integer# Output with neat formattingprint(f"Hello {user_name}!")print(f"You are {age_number} years old.")# Mathematical operationsnext_year = age_number + 1print(f"Next year you will be {next_year} years old.")# Output with different formatprint("Name:", user_name)print("Age:", age_number)print("Age next year:", next_year)
# Basic mathematical operationsa = 10b = 3# Arithmetic operationsaddition = a + b # 13subtraction = a - b # 7multiplication = a * b # 30division = a / b # 3.333...floor_division = a // b # 3 (division result rounded down)modulus = a % b # 1 (remainder)exponent = a ** b # 1000 (10 to the power of 3)print(f"{a} + {b} = {addition}")print(f"{a} - {b} = {subtraction}")print(f"{a} * {b} = {multiplication}")print(f"{a} / {b} = {division}")print(f"{a} // {b} = {floor_division}")print(f"{a} % {b} = {modulus}")print(f"{a} ** {b} = {exponent}")# Operations with assignmentx = 5x += 3 # x = x + 3, result is x = 8x *= 2 # x = x * 2, result is x = 16print(f"Current value of x: {x}")
# Temperature converter from Celsius to Fahrenheit and Kelvinprint("=== TEMPERATURE CONVERTER ===")# Input temperature in Celsiuscelsius = float(input("Enter temperature in Celsius: "))# Convert to Fahrenheit and Kelvinfahrenheit = (celsius * 9/5) + 32kelvin = celsius + 273.15# Output conversion resultsprint(f"Conversion results from {celsius}°C:")print(f"Fahrenheit: {fahrenheit:.1f}°F")print(f"Kelvin: {kelvin:.1f}K")# Bonus: Additional informationif celsius < 0: print("This temperature is below water freezing point!")elif celsius == 0: print("This temperature is water freezing point!")elif celsius == 100: print("This temperature is water boiling point!")elif celsius > 100: print("This temperature is above water boiling point!")