Python is a powerful general-purpose programming language. It is used in web development, data science, creating software prototypes, and so on. Fortunately for beginners, Python has simple easy-to-use syntax. This makes Python an excellent language to learn to program for beginners.
How to Get Started With Python?
In this tutorial, you will learn to install and run Python on your computer. Once we do that, we will also write our first Python program.
Python is a cross-platform programming language, which means that it can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is free and open-source.
Even though most of today's Linux and Mac have Python pre-installed in it, the version might be out-of-date. So, 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 by using Thonny IDE.
The Thonny IDE comes with the latest version of Python bundled in it. So you don't have to install Python separately.
Follow the following steps 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
.py
extension. For example,hello.py
,example.py
, etc.
You can give any name to the file. However, the file name should end with .py - Write Python code in the file and save it
- Then Go to Run > Run current script or simply click F5 to run it.
Install Python Separately
If you don't want to use Thonny, here's how you can install and run Python on your computer.
- Download the latest version of Python.
- Run the installer file and follow the steps to install Python
During the install process, check Add Python to environment variables. This will add Python to environment variables, and you can run Python from any part of the computer.
Also, you can choose the path where Python is installed.
Once you finish the installation process, you can run Python.
1. Run Python in Immediate mode
Once Python is installed, typing python
in the command line will invoke the interpreter in immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1
and press enter. We get 2
as the output. This prompt can be used as a calculator. To exit this mode, type quit()
and press enter.
2. Run Python in the Integrated Development Environment (IDE)
We can use any text editing software to write a Python script file.
We just need to save it with the .py
extension. But using an IDE can make our life a lot easier. IDE is a piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers, etc. to the programmer for application development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it. To run the file, go to Run > Run Module or simply click F5.
Your first Python Program
Now that we have Python up and running, we can write our first Python program.
Let's create a very simple program called Hello World
. A "Hello, World!" is a simple program that outputs Hello, World!
on the screen. Since it's a very simple program, it's often used to introduce a new programming language to beginners.
Type the following code in any text editor or an IDE and save it as hello_world.py
print("Hello, world!")
Then, run the file. You will get the following output.
Hello, world!
Congratulations! You just wrote your first program in Python.
As you can see, this was a pretty easy task. This is the beauty of the Python programming language.
Python Keywords and Identifiers
In this tutorial, you will learn about 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 as a variable name, function name or any other identifier. They are used 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 can vary slightly over the course of time.
All the keywords except True
, False
and None
are in lowercase and they must be written as they are. The list of all the keywords is given below.
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
Python if...else Statement
What is if...else statement in Python?
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else
statement is used in Python for decision making.
Python if Statement Syntax
if test expression: statement(s)
Here, the program evaluates the test expression
and will execute statement(s) only if the test expression is True
.
If the test expression is False
, the statement(s) is not executed.
In Python, the body of the if
statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True
. None
and 0
are interpreted as False
.
Python if Statement Flowchart
Example: Python if Statement
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number This is always printed This is also always printed.
In the above example, num > 0
is the test expression.
The body of if
is executed only if this evaluates to True
.
When the variable num is equal to 3, test expression is true and statements inside the body of if
are executed.
If the variable num is equal to -1, test expression is false and statements inside the body of if
are skipped.
The print()
statement falls outside of the if
block (unindented). Hence, it is executed regardless of the test expression.
Python if...else Statement
Syntax of if...else
if test expression: Body of if else: Body of else
The if..else
statement evaluates test expression
and will execute the body of if
only when the test condition is True
.
If the condition is False
, the body of else
is executed. Indentation is used to separate the blocks.
Python if..else Flowchart
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero
In the above example, when num is equal to 3, the test expression is true and the body of if
is executed and the body
of else is skipped.
If num is equal to -5, the test expression is false and the body of else
is executed and the body of if
is skipped.
If num is equal to 0, the test expression is true and body of if
is executed and body
of else is skipped.
Python if...elif...else Statement
Syntax of if...elif...else
if test expression: Body of if elif test expression: Body of elif else: Body of else
The elif
is short for else if. It allows us to check for multiple expressions.
If the condition for if
is False
, it checks the condition of the next elif
block and so on.
If all the conditions are False
, the body of else is executed.
Only one block among the several if...elif...else
blocks is executed according to the condition.
The if
block can have only one else
block. But it can have multiple elif
blocks.
Flowchart of if...elif...else
Example of if...elif...else
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
Python Nested if statements
We can have a if...elif...else
statement inside another if...elif...else
statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
Python Nested if Example
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1
Enter a number: 5 Positive number
Output 2
Enter a number: -1 Negative number
Output 3
Enter a number: 0 Zero
Python for Loop
In this article, you'll learn to iterate over a sequence of elements using the different variations of for loop.
Video: Python for Loop
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
loop body
Here, val
is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Flowchart of for Loop
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
When you run the program, the output will be:
The sum is 48
The range() function
We can generate a sequence of numbers using range()
function. range(10)
will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size)
. step_size defaults to 1 if not provided.
The range
object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in
, len
and __getitem__
operations.
This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list()
.
The following example will clarify this.
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Output
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
We can use the range()
function in for
loops to iterate through a sequence of numbers. It can be combined with the len()
function to iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
Output
I like pop I like rock I like jazz
for loop with else
A for
loop can have an optional else
block as well. The else
part is executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0 1 5 No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else
and prints No items left.
This for...else
statement can be used with the break
keyword to run the else
block only when the break
keyword was not executed. Let's take an example:
# program to display student's marks from record
student_name = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
Output
No entry with that name found.
Python while Loop
Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.
Video: Python while Loop
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate beforehand.
Syntax of while Loop in Python
while test_expression: Body of while
In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression
evaluates to True
. After one iteration, the test expression is checked again. This process continues until the test_expression
evaluates to False
.
In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True
. None
and 0
are interpreted as False
.
Flowchart of while Loop
Example: Python while Loop
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
When you run the program, the output will be:
Enter n: 10 The sum is 55
In the above program, the test expression will be True
as long as our counter variable i is less than or equal to n (10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).
Finally, the result is displayed.
While loop with else
Same as with for loops, while loops can also have an optional else
block.
The else
part is executed if the condition in the while loop evaluates to False
.
The while loop can be terminated with a break statement. In such cases, the else
part is ignored. Hence, a while loop's else
part runs if no break occurs and the condition is false.
Here is an example to illustrate this.
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output
Inside loop Inside loop Inside loop Inside else
Here, we use a counter variable to print the string Inside loop three times.
On the fourth iteration, the condition in while
becomes False
. Hence, the else
part is executed.
0 Comments