Introduction to Python Programming Basics
Introduction to Python Programming Basics
Introduction To Python
History In
1980, Python was introduced by Guido van Rossum. He was doing research in the Netherlands at
the National Research Institute for Mathematics and Computer Science, where he invented the
Python programming language. Unlike other languages that have hard syntax and are quite tough
to learn, he wanted to create an easy programming language similar to English so it can be easy
to read and write. Though it took him 11 years to launch the first version, and that too had only a
few basic functionalities and data types.
Later on in 1994, it became popular among a group of scientists, and Python 1.0 was released
with more advanced features like map, lambda, and filter functions. The further versions
introduced in Python are as follows:
Python Syntax
Python has intuitive syntax that is easy to learn and write because of its resemblance to a natural
English language. For beginners who are just entering the programming world, it is very
beneficial.
Example
1. # code
2. print("Hello World")
Execute Now
Output:
Hello World
Features of Python
Python has plenty of features that make it the most demanding and popular. Let's read about a
few of the best features that Python has:
Applications of Python
Python is among the most widely used programming languages. Due to its user-friendliness,
readability, and extensive library ecosystem, whether you are a novice or an expert developer,
the first step to accomplish this is to install Python on Windows if you wish to write and
execute Python programs.
o Mac: how-to-install-python-on-mac
o CentOS: how-to-install-python-on-centos
o Ubuntu: how-to-install-python-in-ubuntu
Installing Python on Windows
Python doesn't come with prepackage in Windows, but it doesn't mean that Window user cannot
be flexible with Python. Some operating systems such as Linux come with the Python package
manager that can run to install Python. Below are the steps to install Python in Windows.
o Latest stable releases, such as Python 3.13.2, are recommended for all users.
o To view the older version, scroll down the page and click on "View all Python releases."
1.3 Installer Download
o To begin, click on the button that has the "Download Python 3.13.2" text.
o Checking this box will ensure that using the command prompt, you can control the use of
Python at any given location or position.
2. Decide from the given options:
o After completing the process, the statement "Setup was successful" will appear.
o To exit the installer, click on the "Close" button.
o Open the Command Prompt window by pressing Win + R, followed by typing cmd and
pressing Enter.
4.2 Check Python Version
o To check if the application was successfully installed, type the following command and
press enter:
1. $ python --version
o In the event Python was installed properly, it will show the following:
variables
Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Eg.
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Eg.
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
x = "John"
# is the same as
x = 'John'
Case-Sensitive:
Camel Case:
Pascal Case:
Snake Case:
Each word is separated by an underscore character:
my_variable_name = "John"
And you can assign the same value to multiple variables in one line:
Eg.
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Python Operators
Operators are special symbols that perform operations on variables and values. For
example,
Here, + is an operator that adds two numbers: 5 and 6.
Types of Python Operators
Here's a list of different types of Python operators that we will learn in this tutorial.
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
For example,a=5
Here, = is an assignment operator that assigns 5 to a.
Here's a list of different assignment operators available in Python.
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator Meaning Example
a=5 ,b=6
print((a>2)and(b>=6)
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
5. Python Bitwise operators:Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
6. Python Special operators:Python language offers some special types of operators like
the identity operator and the membership operator. They are described below with examples.
Identity operators:In Python, is and is not are used to check if two values are located at the
same memory [Link]'s important to note that having two variables with equal values doesn't
necessarily mean they are identical.
True if the operands are not identical (do not refer x is not
is not
to the same object) True
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical.
The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them
separately in memory, although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or
variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary, we can only test for the presence of a key, not the value.
Output
True
True
True
False
Here, 'H' is in message, but 'hello' is not present in message (remember, Python is case-
sensitive).
Similarly, 1 is key, and 'a' is the value in dictionary dict1. Hence, 'a' in y returns False.
Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
You can get the data type of any object by using the type() function:
Example
x=5
print(type(x))
In Python, the data type is set when you assign a value to a variable:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
id(): The id() function returns a unique id for the specified object.
Syntax
id(object)
Parameter Values
Parameter Description
Example
Syntax
Parameter Description
x = type(a)
y = type(b)
z = type(c)
range(): The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Values
Parameter Description
More Examples
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Example
x = range(3, 20, 2)
for n in x:
print(n)
"""This is
a
multiline comment"""
3. Wrap lines so that they don't exceed 79 characters : The Python standard library is
conservative and requires limiting lines to 79 characters. The lines can be wrapped using
parenthesis, brackets, and braces. They should be used in preference to backslashes. Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \
open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:
file_two.write(file_one.read())
4. Use of regular and updated comments are valuable to both the coders and users : There
are also various types and conditions that if followed can be of great help from programs and
users point of view. Comments should form complete sentences. If a comment is a full
sentence, its first word should be capitalized, unless it is an identifier that begins with a lower
case letter. In short comments, the period at the end can be omitted. In block comments, there
are more than one paragraphs and each sentence must end with a period. Block comments and
inline comments can be written followed by a single '#'. Example of inline comments:
geek = geek + 1 # Increment
5. Use of trailing commas : This is not mandatory except while making a tuple. Example:
tup = ("geek",)
5. Use Python's default UTF-8 or ASCII encodings and not any fancy encodings, if it is
meant for international environment. 6. Use spaces around operators and after commas, but
not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions : There are few naming conventions that should be followed in order
to make the program less complex and more readable. At the same time, the naming
conventions in Python is a bit of mess, but here are few conventions that can be followed
easily. There is an overriding principle that follows that the names that are visible to the user as
public parts of API should follow conventions that reflect usage rather than implementation.
Here are few other naming conventions:
b (single lowercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
Capitalized_Words_With_Underscores
In addition to these few leading or trailing underscores are also considered.
Examples: single_leading_underscore: weak "internal use" indicator. E.g. from M import *
does not import objects whose name starts with an
underscore. single_trailing_underscore_: used to avoid conflicts with Python keyword.
Example:
[Link](master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling.
(inside class FooBar, __boo becomes
_FooBar__boo;). __double_leading_and_trailing_underscore__: "magic" objects or
attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Only
use them as documented. 8. Characters that should not be used for identifiers : 'l'
(lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character
variable names as these are similar to the numerals one and zero. 9. Don’t use non-ASCII
characters in identifiers if there is only the slightest chance people speaking a different
language will read or maintain the code. 10. Name your classes and functions consistently
: The convention is to use CamelCase for classes and lower_case_with_underscores for
functions and methods. Always use self as the name for the first method argument. 11. While
naming of function of methods always use self for the first argument to instance methods
and cls for the first argument to class [Link] a functions argument name matches with
reserved words then it can be written with a trailing comma. For e.g., class_ You can refer to
this simple program to know how to write an understandable code:
# Python program to find the
# factorial of a number provided by the user.
factorial = 1
Input /output
Meaning:
Input: Refers to taking data from the user or from an external source into a Python
program.
Output: Refers to displaying or writing data from a Python program to the user or to an
external destination.
Example:
Syntax of print()
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters
print(object= separator= end= file= flush=)
Here,
Good Morning!
It is rainy today
In the above example, the print() statement only includes the object to be printed. Here, the
value for end is not used. Hence, it takes the default value '\n'.
So we get the output in two different lines.
Output
Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.
Output
In the above example, the print() statement includes multiple items separated by a comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.
Example: Print Python Variables and Literals
We can also use the print() function to print Python variables. For example,
number = -10.6
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
Run Code
Output
5
-10.6
Programiz
We can also join two strings together inside the print() statement. For example,
print('Programiz is ' + 'awesome.')
Run Code
Output
Programiz is awesome.
Here,
Output formatting:Sometimes we would like to format our output to make it look attractive.
This can be done by using the [Link]() method. For example,
x=5
y = 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
To learn more about formatting the output, visit Python String format().
Python Input:While programming, we might want to take the input from the user. In Python, we
can use the input() function.
Syntax of input()
input(prompt)
Output
Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>
In the above example, we have used the input() function to take input from the user and stored
the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'>.
To convert user input into a number we can use int() or float() functions as:
Here, the data type of the user input is converted from string to integer .
Control Structures
Decision-making functions as an essential programming language component for most modern
languages. Programming languages enable programs to run specific program sections after
satisfying specific conditions.
Conditional Statements are the statements that allow a program to make decisions based on
conditions. These statements enable the execution of different blocks of code relying on whether
a condition is True or False.
1. if statement
2. if-else statement
3. Nested if statement
4. if-elif-else statement
if Statement
Programs execute the code inside the if block when the condition evaluates as True.
This represents the simplest decision-making construct. Programs can determine dynamic
responses through the if statement because it activates specific actions based on defined
conditions.
Syntax:
1. if condition:
2. # Code to execute if condition is True
Let us consider a simple example showing the implementation of if statement in Python:
Example 1
Example 2
1. # asking age from the user
2. age = int(input("Enter your age: "))
3.
4. # multiple if blocks
5. if age < 18: # checking if age is less than 18
6. # printing a message
7. print("You are not eligible to vote")
8.
9. if age >= 18: # checking if age is greater than or equal to 18
10. # printing a message
11. print("You are eligible to vote.")
12.
13. if age >= 21: # checking if age is greater than or equal to 21
14. # printing a message
15. print("You are allowed to consume alcohol in some countries.")
16.
17. if age >= 60: # checking if age is greater than or equal to 60
18. # printing a message
19. print("You are eligible for senior citizen benefits.")
20.
21. if age >= 80: # checking if age is greater than or equal to 80
22. # printing a message
23. print("You are a very senior citizen. Take extra care of your health.")
Execute Now
Output:
# Output 1:
Enter your age: 20
You are eligible to vote.
# Output 2:
Enter your age: 65
You are eligible to vote.
You are allowed to consume alcohol in some countries.
You are eligible for senior citizen benefits.
if…else Statement
Programming contains the if…else statement as its core element for making decisions in code
execution. One block of code executes through the if statement when conditions prove true, but a
different block activates with conditions evaluated false.
.
Syntax:
Example
# Output 1:
Enter your age: 20
You are eligible to vote.
# Output 2:
Enter your age: 16
You are not eligible to vote.
Syntax:
Example 1
# Output 1:
Enter your password: secure123
Password is strong.
# Output 2:
Enter your password: password
Password must contain at least one number.
Example 2
# Output 1:
Enter your marks: 80
Congratulations! You passed with distinction.
# Output 2:
Enter your marks: 35
You failed the exam. Better luck next time.
if…elif…else Statement
A program requires the if…elif…else statement to evaluate sequential conditions for multiple
tests. A program can check several conditions in succession to locate a condition which produces
a True outcome.
Syntax:
Example 1
# Output 1:
Enter the temperature in Celsius: 35
It's a hot day.
# Output 2:
Enter the temperature in Celsius: 22
The weather is warm.
Example 2
# Output 1:
Enter your marks: 95
Grade: A
# Output 2:
Enter your marks: 64
Grade: C
In Python, we use for loops for sequential traversal. For example, traversing the elements of
a string, list, tuple, etc. It is the most commonly used loop in Python that allow us to iterate over
a sequence when we know the number of iterations beforehand.
Syntax:
Example
Output:
1
2
3
4
5
We can use for loop to iterate over strings, lists, tuples, and dictionaries in Python, as shown in
the following example:
Example
Output:
T
p
o
i
n
t
T
e
c
h
Welcome
to
Tpoint
Tech
Python
for
Beginners
1 : Tpoint
2 : Tech
In Python, we can also use the index of the elements in the given sequence for iteration. The
basic idea for this approach is first to determine the size of the sequence (e.g., list, tuple) and
then iterate over it within the range of the determined length.
Example
1. # python example to iterate over sequence using index
2.
3. # given list
4. fruit_basket = ['apple', 'banana', 'orange', 'mango', 'kiwi']
5.
6. # iterating over the index of elements in the list
7. for i in range(len(fruit_basket)):
8. # printing the index and the item
9. print(i, ":", fruit_basket[i])
Execute Now
Output:
0 : apple
1 : banana
2 : orange
3 : mango
4 : kiwi
In Python, we can also use the else statement with the for loop. The for loop does not consist of
any condition on the basis of which the execution will stop. Thus, the code inside the else block
will only run once the for loop finishes iterations.
The syntax of the else statement with Python for loop is shown below:
Syntax:
Example
Output:
guava
apple
orange
mango
banana
melon
Welcome to else Block.
A while loop in Python allows us to execute a block of code repeatedly as long as a particular
condition evaluates to True. It is usually utilized when the number of iterations is unknown
beforehand.
Syntax:
1. while given_condition:
2. # some block of code
Let us now see a simple example of the while loop in Python.
Example
Output:
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
Similar to the use of the else statement with the for loop, we can use it with Python while loop.
The else block will run only when the loop condition becomes false, implying that the loop
terminates normally.
The syntax of the else statement with Python for loop is shown below:
Syntax:
Example
Output:
guava
apple
orange
mango
banana
melon
Welcome to else Block.
In Python, we can also create a loop to execute a block of code for infinite times using
the while loop, as shown in the following example:
Example
Output:
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
...
Note: It is suggested not to use this type of loop. It is a never-ending loop where the condition
always remains true and we have to terminate the interpreter forcefully.
A nested loop is a loop inside another loop. In Python, we can nest both for and while loops.
Nested loops are useful while working with multi-dimensional data like grids or matrices or
while performing certain complex operations.
Syntax:
1. while outer_condition:
2. # some block of code in outer loop
3. while inner_condition:
4. # some block of code in inner loop
We can also use one type of loop inside another other type of loop in Python. For example, we
can use a while loop inside a for loop or vice versa.
Example
Output:
*
**
***
****
*****
******
*******
********
*********
**********
In Python, we use loop control statements in order to change the sequence of execution. Once
the execution leaves a scope, the objects created in the same scope are also destroyed
automatically.
Let us take a look at the following example demonstrating the use of these control statements in
Python.
Example
Output:
The 'break' statement in the 'for' loop permanently stops the current iteration.
Example
Tata
Honda
Explanation:
In the above example, we used the break statement in the 'for' loop to stop the iterations when the
current iteration value is "Mahindra".
2) continue Statement
The 'continue' statement in the 'for' loop skip the current iteration and move to the next.
Example
Tata
Honda
BMW
Explanation:
In this example, we used the continue statement to skip the current iteration of the 'for' loop.
3) pass Statement
In 'for' loop, the 'pass' statement in Python is used as a placeholder. It means that we can use it
when we need to write something in our code but don't want it to do anything or want to leave
space to write something in the future.
Example
1
2
4
5
7
8
10
The 'else' statement in the 'for' loop is used to provide an output when the previous condition is
not met or cannot be achieved.
Example
1
2
3
4
5
6
7
8
9
Loop Finished