How to get started with Python?
In this tutorial, you will learn how to install and run Python on your computer. Once we do this, we will also write our first Python program.
Video: Introduction to Python
Python is a cross-platform programming language that can run on multiple platforms such as Windows, MacOS, Linux, and is even optimized for Java and .NET virtual machines. It is free and open source.
Although Python is pre-installed in most current Linux and Mac operating systems, the version may be outdated. Therefore, it is always a good idea to install the most current version.
The easiest way to run Python
The easiest way to run Python is the Thonny IDE.
Thonny IDE comes with the latest version of Python. Therefore you do not need to install Python separately.
Follow the steps below to run Python on your computer.
Download Thonny IDE.
Run the installer to install Thonny on your computer.
Go to: File> New. Then save the file with the extension .py. For example hello.py, example.py etc.
You can give the file any name. However, the filename must end with .py
Write Python code inside the file and save it.
Run python on your computer
Running Python using Thonny IDE
After that go to Run> Run current script or click to run F5.
Install python separately
If you do not want to use Thonny, this is how you will install and run Python on your computer. Python on your computer.
Download the latest version of Python.
Run the setup file and follow the steps to install Python
During the installation process, add Python to the environment variable. It can add python to environment variables, and it will run python from anywhere on the PC.
Also, it will choose the path where Python is installed.
Install python on your computer
Installing Python on PC
Once the installation process is complete, it will run Python.
- Run Python in Immediate mode
Once Python is installed, typing python within the instruction will invoke the interpreter in immediate mode. we will directly type in Python code, and press Enter to urge the output.
Try typing in 1 + 1 and press enter. We get 2 because the output. This prompt are often used as a calculator. To exit this mode, type quit() and press enter.
Run Python in Immediate mode
Running Python on the instruction
- Run Python within the Integrated Development Environment (IDE)
We can use any text editing software to write down a Python script file.
We just got to reserve it with the .py extension. But using an IDE can make our life tons easier. IDE may be a piece of software that gives useful features like code hinting, syntax highlighting and checking, file explorers, etc. to the programmer for application development.
By the way, once you install Python, an IDE named IDLE is additionally installed. you’ll use it to run Python on your computer. it is a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Python IDLE
Python IDLE
Now you’ll create a replacement file and reserve it with .py extension. for instance , hello.py
Write Python code within the file and reserve it . To run the file, attend Run > Run Module or just click F5.
Run Python programs in IDLE
Running a Python program in IDLE
Your first Python Program
Now that we’ve Python up and running, we will write our first Python program.
Let’s create a really simple program called Hello World. A “Hello, World!” may be a simple program that outputs Hello, World! on the screen. Since it is a very simple program, it’s often wont to introduce a replacement programing language to beginners.
Type the subsequent code in any text editor or an IDE and reserve it as hello_world.py
print(“Hello, world!”)
Then, run the file. you’ll get the subsequent output.
Hello, world!
Congratulations! you only wrote your first program in Python.
As you’ll see, this was a reasonably easy task. this is often the sweetness of Python programing language .
Python identifiers and keywords
In this tutorial, you’ll study keywords (reserved words in Python) and identifiers (names given to variables, functions, etc.).
Python keywords
Keywords are the reserved words in Python.
We cannot use a keyword like variable name, function name, or the other identifier. they’re wont to define the syntax and structure of the Python language.
In Python, keywords are case-sensitive.
There are 33 keywords in Python 3.7. This number may vary slightly over time.
All keywords except True, False, and None are in lowercase and must be entered as is. The list of all keywords is shown below.
False await more import pass
None break except rising
The true class is finally the return
and still lambda try
as def from nonlocal while
affirm from global not with
async elif yes or yield
Looking at all the keywords directly and trying to work out what they mean are often overwhelming.
If you would like to possess an summary , here is that the complete list of all keywords with examples.
Python identifiers
An identifier may be a name that’s given to entities like classes, functions, variables, etc. It helps to differentiate one entity from another.
Rules for writing identifiers
Identifiers are often a mixture of lowercase letters (a to z) or uppercase letters (A to Z) and digits (0 to 9) or an underscore _. Names like myClass, var_1, and print_this_to_screen are all valid examples.
An identifier cannot start with a digit. 1variable isn’t valid, but variable1 may be a valid name.
Keywords can’t be used as identifiers.
global = 1
Departure
File “”, line 1
global = 1
^
Syntax error: invalid syntax
We cannot use some special symbols like !, @, #, $,%, Etc. in our identifier.
a @ = 0
Departure
File “”, line 1
a @ = 0
^
Syntax error: invalid syntax
An identifier are often any length.
Things to recollect
Python may be a case-sensitive language. this suggests that Variable and variable aren’t an equivalent .
Always give identifiers a reputation that creates sense. While c = 10 may be a valid name, typing count = 10 would make more sense and it might be easier to work out what it represents once you check out your code after an extended space.
Multiple words are often separated with an underscore, like this_is_a_long_variable.
Python Statement
Instructions that a Python interpreter can execute are called statements. for instance , a = 1 is an assignment statement. if statement, for statement, while statement, etc. are other forms of statements which can be discussed later.
Multi-line statement
In Python, the top of a press release is marked by a newline character. But we will make a press release extend over multiple lines with the road continuation character (). For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is a particular line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }. as an example , we will implement the above multi-line statement as:
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
Here, the encompassing parentheses ( ) do the road continuation implicitly. Same is that the case with [ ] and { }. For example:
colors = [‘red’,
‘blue’,
‘green’]
We can also put multiple statements during a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the primary unindented line. the quantity of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This leads to Python programs that look similar and consistent.
Indentation are often ignored in line continuation, but it is often an honest idea to indent. It makes the code more readable. For example:
if True:
print(‘Hello’)
a = 5
and
if True: print(‘Hello’); a = 5
both are valid and do an equivalent thing, but the previous style is clearer.
Incorrect indentation will end in IndentationError.
Python Comments
Comments are vital while writing a program. They describe what’s happening inside a program, in order that an individual watching the ASCII text file doesn’t have a tough time figuring it out.
You might forget the key details of the program you only wrote during a month’s time. So taking the time to elucidate these concepts within the sort of comments is usually fruitful.
In Python, we use the hash (#) symbol to start out writing a comment.
It extends up to the newline character. Comments are for programmers to raised understand a program. Python Interpreter ignores comments.
This may be a comment
print out Hello
print(‘Hello’)
Multi-line comments
We can have comments that reach up to multiple lines. a method is to use the hash(#) symbol at the start of every line. For example:
This may be a long comment
and it extends
to multiple lines
Another way of doing this is often to use triple quotes, either ”’ or “””.
These triple quotes are generally used for multi-line strings. But they will be used as a multi-line comment also . Unless they’re not docstrings, they are doing not generate any extra code.
“””This is additionally a
perfect example of
multi-line comments”””
To learn more about comments, visit Python Comments.
Docstrings in Python
A docstring is brief for documentation string.
Python docstrings (documentation strings) are the string literals that appear right after the definition of a function, method, class, or module.
Triple quotes are used while writing docstrings. For example:
def double(num):
“””Function to double the worth “””
return 2*num
Docstrings appear right after the definition of a function, class, or a module. This separates docstrings from multiline comments using triple quotes.
The docstrings are related to the thing as their doc attribute.
So, we will access the docstrings of the above function with the subsequent lines of code:
def double(num):
“””Function to double the value”””
return 2*num
print(double.doc)
Output
Function to double the value
To learn more about docstrings in Python, visit Python Docstrings.
Python Variables
A variable may be a named location wont to store data within the memory. it’s helpful to consider variables as a container that holds data which will be changed later within the program. for instance ,
number = 10
Here, we’ve created a variable named number. we’ve assigned the worth 10 to the variable.
You can consider variables as a bag to store books in it which book are often replaced at any time.
number = 10
number = 1.1
Initially, the worth of number was 10. Later, it had been changed to 1.1.
Note: In Python, we do not actually assign values to the variables. Instead, Python gives the reference of the object(value) to the variable.
Assigning values to Variables in Python
As you’ll see from the above example, you’ll use the assignment operator = to assign a worth to a variable.
Example 1: Declaring and assigning value to a variable
website = “apple.com”
print(website)
Output
apple.com
In the above program, we assigned a worth apple.com to the variable website. Then, we printed out the worth assigned to website i.e. apple.com
Note: Python may be a type-inferred language, so you do not need to explicitly define the variable type. It automatically knows that apple.com may be a string and declares the web site variable as a string.
Example 2: Changing the worth of a variable
website = “apple.com”
print(website)
assigning a replacement value to website
website = “programiz.com”
print(website)
Output
apple.com
programiz.com
In the above program, we’ve assigned apple.com to the web site variable initially. Then, the worth is modified to programiz.com.
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, “Hello”
print (a)
print (b)
print (c)
If we would like to assign an equivalent value to multiple variables directly , we will do that as:
x = y = z = “same”
print (x)
print (y)
print (z)
The second program assigns an equivalent string to all or any the three variables x, y and z.
Constants
A constant may be a sort of variable whose value can’t be changed. it’s helpful to consider constants as containers that hold information which can’t be changed later.
You can consider constants as a bag to store some books which can’t be replaced once placed inside the bag.
Assigning value to constant in Python
In Python, constants are usually declared and assigned during a module. Here, the module may be a new file containing variables, functions, etc which is imported to the most file. Inside the module, constants are written altogether capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a continuing
Create a continuing .py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a continuing .py module file. Then, we assign the constant value to PI and GRAVITY. then , we create a main.py file and import the constant module. Finally, we print the constant value.
Note: actually , we do not use constants in Python. Naming them altogether capital letters may be a convention to separate them from variables, however, it doesn’t actually prevent reassignment.
Rules and Naming Convention for Variables and constants
Constant and variable names should have a mixture of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). for instance :
snake_case
MACRO_CASE
camelCase
CapWords
Create a reputation that creates sense. For example, vowel makes more sense than v.
If you would like to make a variable name having two words, use underscore to separate them. For example:
my_name
current_salary
Use capital letters possible to declare a continuing . For example:
PI
G
MASS
SPEED_OF_LIGHT
TEMP
Never use special symbols like !, @, #, $, %, etc.
Don’t start a variable name with a digit.
Literals
Literal may be a data given during a variable or constant. In Python, there are various sorts of literals they’re as follows:
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to three different numerical types: Integer, Float, and sophisticated .
Example 4: the way to use Numeric literals in Python?
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
Float Literal
float_1 = 10.5
float_2 = 1.5e2
Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
Output
10 100 200 300
10.5 150.0
3.14j 3.14 0.0
In the above program,
We assigned integer literals into different variables. Here, a is binary literal, b may be a decimal literal, c may be a n octal literal and d is a hexadecimal literal.
once we print the variables, all the literals are converted into decimal values.
10.5 and 1.5e2 are floating-point literals. 1.5e2 is expressed with exponential and is like 1.5 * 102.
We assigned a posh literal i.e 3.14j in variable x. Then we use imaginary literal (x.imag) and real literal (x.real) to make imaginary and real parts of complex numbers.
To learn more about Numeric Literals, ask Python Numbers.
String literals
A string literal may be a sequence of characters surrounded by quotes. we will use both single, double, or triple quotes for a string. And, a personality literal may be a single character surrounded by single or quotation mark .
Example 7: the way to use string literals in Python?
strings = “This is Python”
char = “C”
multiline_str = “””This may be a multiline string with quite one line code.”””
unicode = u”Ünicöde”
raw_str = r”raw \n string”
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Output
This is Python
C
This is a multiline string with quite one line code.
Ünicöde
raw \n string
In the above program, this is often Python may be a string literal and C may be a character literal.
The value in triple-quotes “”” assigned to the multiline_str may be a multi-line string literal.
The string u”Ünicöde” may be a Unicode literal which supports characters aside from English. during this case, Ü represents Ü and ö represents ö.
r”raw \n string” may be a raw string literal.
Boolean literals
A Boolean literal can have any of the 2 values: True or False.
Example 8: the way to use boolean literals in Python?
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print(“x is”, x)
print(“y is”, y)
print(“a:”, a)
print(“b:”, b)
Output
x is True
y is False
a: 5
b: 10
In the above program, we use boolean literal True and False. In Python, True represents the worth as 1 and False as 0. the worth of x is True because 1 is adequate to True. And, the worth of y is fake because 1 isn’t adequate to False.
Similarly, we will use truth and False in numeric expressions because the value. the worth of a is 5 because we add True which features a value of 1 with 4. Similarly, b is 10 because we add the False having value of 0 with 10.
Special literals
Python contains one special literal i.e. None. We use it to specify that the sector has not been created.
Example 9: the way to use special literals in Python?
drink = “Available”
food = None
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
Output
Available
None
In the above program, we define a menu function. Inside menu, once we set the argument as drink then, it displays Available. And, when the argument is food, it displays None.
Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.
Example 10: the way to use literals collections in Python?
fruits = [“apple”, “mango”, “orange”] #list
numbers = (1, 2, 3) #tuple
alphabets = {‘a’:’apple’, ‘b’:’ball’, ‘c’:’cat’} #dictionary
vowels = {‘a’, ‘e’, ‘i’ , ‘o’, ‘u’} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
Output
[‘apple’, ‘mango’, ‘orange’]
(1, 2, 3)
{‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cat’}
{‘e’, ‘a’, ‘o’, ‘i’, ‘u’}
In the above program, we created an inventory of fruits, a tuple of numbers, a dictionary dict having values with keys designated to every value and a group of vowels.
To learn more about literal collections, ask Python Data Types.
Python Data Types
Data types in Python
Every value in Python features a datatype. Since everything is an object in Python programming, data types are literally classes and variables are instance (object) of those classes.
There are various data types in Python. a number of the important types are listed below.
Python Numbers
Integers, floating point numbers and sophisticated numbers fall into Python numbers category. they’re defined as int, float and sophisticated classes in Python.
We can use the type() function to understand which class a variable or a worth belongs to. Similarly, the isinstance() function is employed to see if an object belongs to a specific class.
a = 5
print(a, “is of type”, type(a))
a = 2.0
print(a, “is of type”, type(a))
a = 1+2j
print(a, “is complex number?”, isinstance(1+2j,complex))
Output
5 is of type
2.0 is of type
(1+2j) is complex number? True
Integers are often of any length, it’s only limited by the memory available.
A number is accurate up to fifteen decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 may be a number .
Complex numbers are written within the form, x + yj, where x is that the real part and y is that the imaginary part of a complex number . Here are some examples.
a = 1234567890123456789
a
1234567890123456789
b = 0.1234567890123456789
b
0.12345678901234568
c = 1+2j
c
(1+2j)
Notice that the float variable b got truncated.
Python List
List is an ordered sequence of things . it’s one among the foremost used datatype in Python and is extremely flexible. All the things during a list don’t got to be of an equivalent type.
Declaring an inventory is pretty simple . Items separated by commas are enclosed within brackets [ ].
a = [1, 2.2, ‘python’]
We can use the slicing operator [ ] to extract an item or a variety of things from an inventory . The index starts from 0 in Python.
a = [5,10,15,20,25,30,35,40]
a[2] = 15
print(“a[2] = “, a[2])
a[0:3] = [5, 10, 15]
print(“a[0:3] = “, a[0:3])
a[5:] = [30, 35, 40]
print(“a[5:] = “, a[5:])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the worth of elements of an inventory are often altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
Tuple is an ordered sequence of things same as an inventory . the sole difference is that tuples are immutable. Tuples once created can’t be modified.
Tuples are wont to write-protect data and are usually faster than lists as they can’t change dynamically.
It is defined within parentheses () where items are separated by commas.
t = (5,’program’, 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,’program’, 1+3j)
t[1] = ‘program’
print(“t[1] = “, t[1])
t[0:3] = (5, ‘program’, (1+3j))
print(“t[0:3] = “, t[0:3])
Generates error
Tuples are immutable
t[0] = 10
Output
t[1] = program
t[0:3] = (5, ‘program’, (1+3j))
Traceback (most recent call last):
File “test.py”, line 11, in
t[0] = 10
TypeError: ‘tuple’ object doesn’t support item assignment
Python Strings
String is sequence of Unicode characters. we will use single quotes or quotation mark to represent strings. Multi-line strings are often denoted using triple quotes, ”’ or “””.
s = “This may be a string”
print(s)
s = ”’A multiline
string”’
print(s)
Output
This is a string
A multiline
string
Just like an inventory and tuple, the slicing operator [ ] are often used with strings. Strings, however, are immutable.
s = ‘Hello world!’
s[4] = ‘o’
print(“s[4] = “, s[4])
s[6:11] = ‘world’
print(“s[6:11] = “, s[6:11])
Generates error
Strings are immutable in Python
s[5] =’d’
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File “”, line 11, in
TypeError: ‘str’ object doesn’t support item assignment
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items during a set aren’t ordered.
a = {5,2,3,1,4}
printing set variable
print(“a = “, a)
data sort of variable a
print(type(a))
Output
a = {1, 2, 3, 4, 5}
We can perform set operations like union, intersection on two sets. Sets have unique values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator [] doesn’t work.
a = {1,2,3}
a[1]
Traceback (most recent call last):
File “”, line 301, in runcode
File “”, line 1, in
TypeError: ‘set’ object doesn’t support indexing
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used once we have an enormous amount of knowledge . Dictionaries are optimized for retrieving data. We must know the key to retrieve the worth .
In Python, dictionaries are defined within braces {} with each item being a pair within the form key:value. Key and value are often of any type.
d = {1:’value’,’key’:2}
type(d)
We use key to retrieve the respective value. But not the opposite way around.
d = {1:’value’,’key’:2}
print(type(d))
print(“d[1] = “, d[1]);
print(“d[‘key’] = “, d[‘key’]);
Generates error
print(“d[2] = “, d[2]);
Output
d[1] = value
d[‘key’] = 2
Traceback (most recent call last):
File “”, line 9, in
KeyError: 2
Conversion between data types
We can convert between different data types by using different type conversion functions like int(), float(), str(), etc.
float(5)
5.0
Conversion from float to int will truncate the worth (make it closer to zero).
int(10.6)
10
int(-10.6)
-10
Conversion to and from string must contain compatible values.
float(‘2.5’)
2.5
str(25)
’25’
int(‘1p’)
Traceback (most recent call last):
File “”, line 301, in runcode
File “”, line 1, in
ValueError: invalid literal for int() with base 10: ‘1p’
We can even convert one sequence to a different .
set([1,2,3])
{1, 2, 3}
tuple({5,6,7})
(5, 6, 7)
list(‘hello’)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
To convert to dictionary, each element must be a pair:
dict([[1,2],[3,4]])
{1: 2, 3: 4}
dict([(3,26),(4,44)])
{3: 26, 4: 44}