Learn the Basics of Python in 1 Hour With These 13 Steps

Learn the Basics of Python in 1 Hour With These 13 Steps

Interested in learning Python but don’t know where to start? I’ll walk you through the basics of the ever-popular programming language step-by-step. In an hour or so, you’ll go from zero to writing real code.

Настройте свою среду разработки

To start writing and running Python programs locally on your device, you must have Python installed and an IDE (Integrated Development Environment) or text editor, preferably a code editor. First, let’s install Python. Go to the official Python website. Go to Downloads. You should see a button telling you to download the latest Python version (as of writing this, it’s 3.13.3.) It will also show you different operating systems for which you want to download.

Learn the Basics of Python in 1 Hour With These 13 Steps

If you want to install Python on Windows, download the installer. Double-click to open it. Follow the instructions and finish the installation.

If you’re using a Linux distribution such as Ubuntu or macOS, most likely Python has come pre-installed with it. However, if it’s not installed in your distro, you can either use your distro’s package manager to install it or build it from source. For macOS, you can use the Homebrew package manager or the official macOS installer.

After installing, you’ll find a Python shell installed called IDLE on your system. You can start writing Python code on that. But for more features and flexibility, it’s better to go with a good code editor or an IDE. For this tutorial, I’ll be using Visual Studio Code. You can get it on any of the three operating systems.

If you’re using VS Code, one more thing you’ll need is an extension called Code Runner. This isn’t strictly required but will make your life easier. Go to the Extensions tab, and search for Code Runner. Install the extension. After that, you should see a run button at the top right corner of your editor.

Learn the Basics of Python in 1 Hour With These 13 Steps

Now, every time you want to execute your code, you can click on that run button. With that, you’re ready to write some code.

Write Your First Python Program

Create a file and name it «hello.py» without quotes. You can use other names, too, but adding the .py at the end is important. For our first program, let’s print a string or text in the console, also known as the command line interface. For that, we’ll use the print() function in Python. Write this in your code editor:

print(«Hello, Python»)

Now run your code. It should print «Hello, Python» without the quotes on the console.

Learn the Basics of Python in 1 Hour With These 13 Steps

You can write anything between the quotes inside the print() function, which will be displayed. We’ll learn more about functions later.

Write Comments in Your Code

Comments are lines that are not executed when you run your code. You can use comments to explain code segments so that when someone else looks at your program or you come back to it after a long time, you can understand what’s going on. Another use case for comments is when you don’t want to execute a line, you can comment it out.

To comment out a line in Python, we use the # symbol. Start any line with that symbol and it will be treated as a comment.

# This line prints the text Hello, Python in the console

print(«Hello, Python»)

Learn the Basics of Python in 1 Hour With These 13 Steps

The first line is a comment and won’t be picked up when executed. You can add a comment on the right side of your code as well.

print(«Hello, Python») # This line prints the text Hello, Python into the console

You can add as many comments in multiple lines as you want.

# This is my first Python program

# I love Python

# Let’s print some text

print(«Hello, Python»)

Learn the Basics of Python in 1 Hour With These 13 Steps

Another commonly used strategy for multiline comments is using triple quotes. You can do the same as above with this code.

«»»This is my first Python program

я люблю питона

Let’s print some text»»»

print(«Hello, Python»)

Learn the Basics of Python in 1 Hour With These 13 Steps

Store Data in Variables

Variables are like containers. They can hold values for you, such as text, numbers, and more. To assign a value to a variable, we follow this syntax:

a = 5

Here, we’re storing the value 5 in the variable «a». Likewise, we can store strings.

a = «Python»

A best practice for writing variable names is to be descriptive so that you can identify what value it’s storing.

возраст = 18

You can print a variable’s value to the console.

name = «John»

печать (имя)

This will print «John» on the console. Notice that in the case of variables, we don’t require them to be inside quotes when printing. Variable names have some rules to follow.

  1. They can’t start with numbers. But you can add numbers in the middle.
  2. You can’t have non-alphanumeric characters in them.
  3. Both uppercase and lowercase letters are allowed.
  4. Starting with an underscore (_) is allowed.
  5. For longer names, you can separate each word using an underscore.
  6. You can’t use certain reserved words (such as class) for variable names.

Here are some valid and invalid variable name examples:

# Действительный

name = «Alice»

возраст = 30

user_name = «alice123»

number1 = 42

_total = 100

# Invalid

1name = «Bob»

user-name = «bob»

total$ = 50

class = «math»

Learn Python’s Data Types

In Python, everything is an object, and each object has a data type. For this tutorial, I’ll only focus on a few basic data types that cover most use cases.

Целое

This is a numeric data type. These are whole numbers without a decimal point. We use the int keyword to represent integer data.

возраст = 25

год = 2025

Поплавок

These are numbers with a decimal point. We represent them with the float keyword.

цена = 19.99
temperature = -3.5

строка

These are text enclosed in quotes (single ‘ or double » both work.) The keyword associated with strings is str.

name = «Alice»

greeting = ‘Hello, world!’

Логический

This type of variable can hold only two values: True and False.

is_logged_in = True

has_permission = False

To see what data type a variable is of, we use the type() function.

print(type(name))

print(type(price))

print(type(is_logged_in))

Learn the Basics of Python in 1 Hour With These 13 Steps

Convert Between Data Types (Typecasting)

Python has a way to convert one type of data to another. For example, turning a number into a string to print it, or converting user input (which is always a string) into an integer for calculations. This is called typecasting. For that, we have different functions:

Функция

Преобразует в

int ()

Целое

плавать()

Поплавок

bool ()

Логический

str ()

строка

Вот несколько примеров:

age_str = «25»

age = int(age_str)

print(age + 5)

оценка = 99

score_str = str(score)

print(«Your score is » + score_str)

пи = 3.14

rounded = int(pi)

whole_number = 10

decimal_number = float(whole_number)

print(bool(0))

print(bool(«hello»))

print(bool(«»))

Learn the Basics of Python in 1 Hour With These 13 Steps

Take User Input

Until now, we have directly hardcoded values into variables. However, you can make your programs more interactive by taking input from the user. So, when you run the program, it will prompt you to enter something. After that, you can do whatever with that value. To take user input, Python has the input() function. You can also store the user input in a variable.

name = input()

To make the program more understandable, you can write a text inside the input function.

name = input(«What is your name?»)

print(«Hello», name)

Learn the Basics of Python in 1 Hour With These 13 Steps

Know that inputs are always taken as strings. So, if you want to do calculations with them, you need to convert them to another data type, such as an integer or float.

age = int(input(«What is your age?»))

print(«In 5 years, you’ll be», age + 5)

Learn the Basics of Python in 1 Hour With These 13 Steps

Do Math With Python

Python supports various types of mathematics. In this guide, we’ll mainly focus on arithmetic operations. You can do addition, subtraction, multiplication, division, modulus, and exponentiation in Python.

х = 10

y = 3

a = x + y

b = x — y

c = x * y

d = x / y

g = x // y # Divide and take only the integer part of the result

e = x % y

f = x ** y

print(«Addition: «, a)

print(«Subtraction: «, b)

print(«Multiplication: «, c)

print(«Division: «, d)

print(«Floor Division: «, g)

print(«Modulus: «, e)

print(«Exponent: «, f)

Learn the Basics of Python in 1 Hour With These 13 Steps

You can do much more advanced calculations in Python. The Python math module has many mathematical functions. However, that’s not in the scope of this guide. Feel free to explore them.

Use Comparison Operators

Comparison operators let you compare values. The result is either True or False. This is super useful when you want to make decisions in your code. There are six comparison operators.

оператор

Смысл

==

Равно

!=

Не равно

>

Больше

<

Менее

>=

Больше или равно

<=

Меньше или равно

Вот несколько примеров:

a = 10

б = 7

print(a > b)

print(a == b)

print(a < b)

print(a != b)

print(a >= b) # True if a is either greater than or equal to b

print(a <= b) # True if a is either less than or equal to b

Learn the Basics of Python in 1 Hour With These 13 Steps

Apply Logical Operators

Logical operators help you combine multiple conditions and retrurns True or False based on the conditions. There are three logical operators in Python.

оператор

Смысл

и

True if both are true

or

True if at least one is true

Flips the result

Some examples will make it clearer.

возраст = 17

has_license = True

print(age >= 18 and has_license)

day = «Saturday»

print(day == «Saturday» or day == «Sunday»)

is_logged_in = False

print(not is_logged_in)

Learn the Basics of Python in 1 Hour With These 13 Steps

Write Conditional Statements

Now that you’ve learned about comparison and logical operators, you’re ready to use them to make decisions in your code using conditional statements. Conditional statements let your program choose what to do based on certain conditions. Just like real-life decision-making. There are three situations for conditional statements.

если Заявление

We use if when you want to run some code only if a condition is true.

если условие:

   # сделай что-нибудь

Рассмотрим пример:

возраст = 18

если возраст >= 18:

   print(«You’re an adult.»)

Learn the Basics of Python in 1 Hour With These 13 Steps

If the condition is false, the code inside the if block is simply skipped.

In Python, indentation is crucial. Notice that the code inside the if block is indented. Python picks this up to understand which line is part of which block. Without proper indentation, you’ll get an error.

if-else Statement

We use if-else when you want to do one thing if the condition is true, and something else if it’s false.

если условие:

   # do this if true

еще:

   # do this if false

Пример:

is_logged_in = False

if is_logged_in:

   print(«Welcome back!»)

еще:

   print(«Please log in.»)

Learn the Basics of Python in 1 Hour With These 13 Steps

if-elif-else Statement

We use if-elif-else when you have multiple conditions to check, one after the other.

если условие1:

   # do this

Элиф условие2:

   # do this

еще:

   # do this if none match

Посмотрим на пример.

оценка = 85

если оценка >= 90:

   print(«Grade: A»)

elif score >= 80:

   print(«Grade: B»)

еще:

   print(«Keep trying!»)

Learn the Basics of Python in 1 Hour With These 13 Steps

You can add as many elif conditions as you like.

Loop Through Code with for and while

In programming, we often have to do repetitive tasks. For such cases, we use loops. Instead of copying the same code, we can use loops to do the same thing with much less code. We’ll learn about two different loops.

для цикла

The for loop is useful when you want to run a block of code a specific number of times.

для я в диапазоне (n):

   # repeat this n times

Let’s print a text using a loop.

для i в диапазоне (5):

   print(«Hello!»)

Learn the Basics of Python in 1 Hour With These 13 Steps

This prints «Hello!» 5 times. The value of i goes from 0 to 4. You can also start at a different number:

для я в диапазоне (1, 4):

   печать (я)

Learn the Basics of Python in 1 Hour With These 13 Steps

The ending value (4 in this case) in the range() function isn’t printed because it’s excluded from the range.

в то время как цикл

The while loop is used when you’re uncertain how long the loop will run. When you want to keep looping as long as a condition is true.

пока условие:

   # сделай что-нибудь

A quick example.

количество = 1

while count <= 3:

   print(«Count is», count)

   count + = 1

Learn the Basics of Python in 1 Hour With These 13 Steps

Two more useful statements in loops are the break statement and the continue statement. The break statement stops a loop early if something you specify happens.

я = 1

while True:

   печать (я)

   если я == 3:

       перерыв

   я + = 1

Learn the Basics of Python in 1 Hour With These 13 Steps

The continue statement skips the rest of the code in the loop for that iteration, and goes to the next one.

для i в диапазоне (5):

   если я == 2:

       продолжать

   печать (я)

Learn the Basics of Python in 1 Hour With These 13 Steps

Write Your Own Functions

As your programs get bigger, you’ll find yourself typing the same code over and over. That’s where functions come in. A function is a reusable block of code that you can «call» whenever you need it. It helps you avoid repeating code, organize your program, and make code easier to read and maintain. Python already gives you built-in functions like print() and input(), but you can also write your own.

To create a function, use the def keyword:

def function_name():

   # сделай что-нибудь

Then you call it like this:

function_name()

Let’s create a simple function:

def say_hello():

   print(«Hello!»)

   print(«Welcome to Python.»)

say_hello()

Learn the Basics of Python in 1 Hour With These 13 Steps

You can also make your function accept parameters. Parameters are values passed into it.

def greet(name):

   print(«Hello,», name)

To call it with an argument:

greet(«Alice»)

greet(«Bob»)

Learn the Basics of Python in 1 Hour With These 13 Steps

You can use multiple parameters, too.

def add(a, b):

   print(a + b)

add(3, 4)

Learn the Basics of Python in 1 Hour With These 13 Steps

You can reuse the same function multiple times with different inputs.

That covers some of the basics of Python programming. If you want to become a better programmer, you need to start doing some projects, such as an expense tracker or a to-do list app.

Валентин Павлов/ автор статьи
Страсть Влентина к играм началась с Resident Evil, и с тех пор он не переставал играть в хоррор-игры. Пишет экспертные руководства для самых сложных игр и обзоры для самых громких релизов. Является магистром журналистики и имеет степень бакалавра лингвистики. Любимые игры: GTA 5, Silent Hill 2, Call of Duty: Modern Warfare 2, Heavy Rain, Metro 2033 и другие.
Понравилась статья? Поделиться с друзьями:
Добавить комментарий