Simple Python Programs: Examples and a beginner's Guide
Python is a powerful and user-friendly programming language that has become popular not only among professionals, but also among beginners. Its simplicity makes it easy to understand the basic constructs and the principle of operation. In this article, we will look at some simple Python programs to help you familiarize yourself with this language and understand how it works. We will start with the basics and gradually move on to more complex examples so that you can see the gradual development of your skills.
Getting to know Python: Why it?
Python was created in the late 1980s and quickly gained popularity due to its readability and simplicity. The main features that make Python suitable for beginners are as follows:
-
Code readability: Python syntax is intuitive. Programs written in Python often look like plain English text, which makes them easier to understand.
-
Multifunctional: Python can be used to create web applications, data analysis, machine learning, task automation, and more.
Large community: A huge number of developers work in Python, which makes it easier to find answers to emerging questions. There are many resources, tutorials, and forums.
Now that we've seen the benefits of Python, let's move on to practical examples to take a look at its capabilities.
Example 1: The program "Hello world!»
The first program, which is usually written by novice programmers, is called "Hello, world!". This is the simplest script that displays text on the screen. Let's see how to do this in Python.
print("Hello world!")
When you run this program, it simply outputs the line "Hello, world!" to the console. This is a simple but important first exercise that introduces you to the print() function used to output data. Although the program looks very simple, it shows you how to process text and display it on the screen.
Example 2: A simple calculator
The following example is a simple calculator that performs basic arithmetic operations. This will allow you to get familiar with variables, data entry, and conditional statements.
# Function for performing arithmetic operations
def calculator():
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter the operation number (1/2/3/4): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
print(f"{num1} / {num2}= {num1 / num2}")
else:
print("Incorrect input")
calculator()
In this program, we first ask the user to select an operation, and then enter two numbers. Depending on the choice, the corresponding arithmetic operation is performed. This example allows you to get acquainted with how a function can organize code, as well as how to process user input.
Example 3: The "Guess the Number" game
Are you ready for a little fun? Let's create a game in which the computer generates a random number, and the player has to guess it. This example will allow you to familiarize yourself with the random library, conditional constructions, and loops.
import random
def guess_the_number():
number_to_guess = random.randint(1, 100)
attempts = 0
print("I have conceived a number from 1 to 100. Guess it!")
while True:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number_to_guess:
print("The number is too small. Try again.")
elif guess > number_to_guess:
print("The number is too large. Try again.")
else:
print(f"Congratulations! You guessed the number {number_to_guess} in {attempts} attempts.")
break
guess_the_number()
In this example, we use the randint() function to generate a random number from 1 to 100. The player enters his guess, and the program tells him whether it is too big or too small. The game continues until the player guesses the number. This example demonstrates how loops and conditions can be used to create interactive programs.
Example 4: A dictionary with student data
Dictionaries are one of the powerful data structures in Python that allows you to store data in the "key-value" format. Let's look at an example where we will create a dictionary with some data about students and display them on the screen.
students = {
"Ivan": {"age": 20, "group": "A"},
"Maria": {"age": 22, "group": "B"},
"Sergey": {"age": 19, "group": "A"},
}
for name, info in students.items():
print(f"Student: {name}, Age: {info['age']}, Group: {info['group']}")
This code creates a dictionarystudents, where the keys are the names of the students, and the values are other dictionaries with their age and group. Then we use the for loop to go through all the students and output their information. This shows how the data structure works and what features Python provides for organizing information.
Example 5: Working with files
Understanding how to work with files is an important aspect of programming. Let's create a simple program that will write data to a text file and then read it back.
def write_to_file():
with open('students.txt', 'w') as file:
file.write("Ivan\n")
file.write("Maria\n")
file.write("Sergey\n")
def read_from_file():
with open('students.txt', 'r') as file:
print("List of students:")
for line in file:
print(line.strip())
write_to_file()
read_from_file()
Here we have written two functions: the first onewrite_to_file()writes the names of students to a filestudents.txt , and the secondread_from_file()reads the contents the file and displays it on the screen. Using the with open() construction, we ensure that the file is automatically closed after operations are completed. This example demonstrates an important concept of working with external data.
Example 6: A simple web application with Flask
Flask is a popular Python web framework that makes it easy to create web applications. Let's take a simple example of a web application that displays "Hello world!" in a browser.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, world!"
if __name__ == '__main__':
app.run(debug=True)
In this code, we create a Flask application and define a route/ that returns a simple message. To run the application, you need to install Flask and run the script. After that, you can open a browser and go to http://127.0.0.1:5000 / to see your message.
Creating web applications is not only an interesting, but also a useful area of programming, especially if you want to create interactive pages and applications for users.