Programming Basics · Lesson 7 of 17
Python Basics Introduction
This tutorial provides you with the fundamentals of Python programming. It includes how to create and run Python scripts, how to use the `import` keyword to import Python modules, an explanation of variables, functions, and while loops in Python.
Creating and Running Python Scripts
Python script is a file with a `.py` extension that contains Python code. Write your code in a text editor, save it with the .py extension, and run it using the Python interpreter in the command line:
Imports in Python
'import' is a keyword in Python used to include various Python modules into your current program. Once a module is imported, you have access to all the functions, classes, and variables defined in that module.
import math
print(math.pi) # prints the value of pi
Variables in Python
Variables in Python are references that are used to store data values. Python has no command for declaring a variable.
a = 10 # a becomes 10
print(a)
Creating Functions in Python
A function is a group of statements performing specific tasks. Functions in Python are defined by using the `def` keyword.
def greeting():
print('Hello, world!')
greeting() # This will print 'Hello, world!'
While Loops in Python
A while loop in Python repeatedly executes a block of statements as long as the given condition is true.
i = 0
while i < 5:
print(i)
i += 1 # This will print numbers from 0 to 4
For Loops in Python
'for' loop in Python is used for sequential traversals, such as going through every item in a list or string.
The `for` loop can also be used to iterate over a list directly:
my_list = ['apple', 'banana', 'cherry']
for i in my_list:
print(i) # This will print 'apple', 'banana', 'cherry'