Introduction to Python Programming - Part - I
Instructor: Dr. Sanasam Ranbir Singh
This tutorial is prepared by Mr. Soumyadeep Jana, OSINT Lab, Dept. of CSE, IIT Guwahati
Introduction
- Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation
- Syntax is much simpler to other mid-level languages like C/C++
- It is an interpreted language
- Widely used today in fields like Machine Learning and AI due to its simplicity and powerful packages developed by the community
1.Installing Python [Version- 3.10]
Windows : Install python and pip
Linux :Install Python
a) pip is a python package manager that lets you install powerful python packages developed by open-source developers.
b) For windows, pip is installed when you install python.
For linux users, you need to install it seperately
c) pip install 'package_name'
d) More on pip
Install a code-editor, Sublime Text or VS-code to write your python scripts
###2.Print Statement
Used to display output in the terminal
print('Welcome to Python Programming Lab')
print('India stands 4th at the Commonwealth Games 2022')
#Multiple items with print
print('MTech','Data','Science')
Welcome to Python Programming Lab India stands 4th at the Commonwealth Games 2022 MTech Data Science
#WARNING[Python 2 and earlier]
print 'Python Programming'
3.Data Types
(3.1) Numeric Types
#Integer
num1 = 100
print(type(num1))
#Float
num2 = 100.1
print(type(num2))
<class 'int'> <class 'float'>
Note : No Concept of short, long, double or other modifiers as in C/C++/Java
(3.2) Boolean Types
var1 = True
print(type(var1))
var2 = False
print(type(var2))
<class 'bool'> <class 'bool'>
(3.3) String type
1. Represents sequence of characters
2. Enclosed within quotes(either single or double)
3. If you want a string literal to contain either a single-quote or an apostrophe as part of the
string, you can enclose the string literal in double-quote marks
x = 'IITG ranks 7th in NIRF Engineering category'
print(x)
y = "IITG ranks 7th in NIRF Engineering category"
print(y)
z = "It's raining cats and dogs"
print(z)
IITG ranks 7th in NIRF Engineering category IITG ranks 7th in NIRF Engineering category It's raining cats and dogs
NOTE :Unlike C/C++/Java there's no char type here, even a single character is treated as a string
4.Variables
A variable is a name that represents a value stored in the computer’s
memory.
4.1) You use an assignment statement to create a variable and make it reference a piece of data.
An assignment statement is written in the following general format:
variable = expression
Example:
dollars = 2.75
print(dollars)
#Reassign variable
dollars = 99.95
print(dollars)
2.75 99.95
WARNING! You cannot use a variable until you have assigned a value to it. An error
will occur if you try to perform an operation on a variable, such as printing it, before
it has been assigned a value.
temperature = 40
print(temp)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-28ce6b64cc4d> in <module>
1 temperature = 40
----> 2 print(temp)
NameError: name 'temp' is not defined 1age = 3
print(1age)
File "<ipython-input-8-844bd70ed252>", line 1
1age = 3
^
SyntaxError: invalid syntax
(4.3) Python is a loosely typed language - You don't have to declare variables with data types unlike JAVA or C or C++ etc
What a relief !!!
int a = 10
float b 100.1
name = "Lakshya Sen"
age = 20
medal = "gold"
print(name,age,medal)
Lakshya Sen 20 gold
#Benefit of loose type - single variable can hold multiple datatypes
dollars = "Virat Kohli"
print(x)
x = 7
print(x)
IITG ranks 7th in NIRF Engineering category 7
###5.Reading Input
1.Most of the programs that you will write will need to read input and then perform an operation on that input
2. input() function is used to do this
3. General Format : var = input("Input Message")
(5.1) Reading string type data from keyboard
x = input("Enter your name")
print(x)
Enter your namesoumyadeep soumyadeep
Note: input() function returns any input as string
x = input("Enter your age")
print(x)
print(type(x))
Enter your age25 25 <class 'str'>
(5.2) Reading numeric data types
#Read integer type data
x = int(input("Enter your age"))
print(x)
print(type(x))
#Read float type data
y = float(input('Enter your cgpa'))
print(y)
print(type(y))
Enter your age25 25 <class 'int'> Enter your cgpa8.9 8.9 <class 'float'>
###6.Output Formatting
(6.1) Print variables with strings
wickets = int(input("Enter wickets"))
print("Hopefully India doesn't lose by {} wickets remaining this time against Pak".format(wickets))
print(f"Hopefully India doesn't lose by {wickets} wickets remaining this time against Pak")
Enter wickets10 Hopefully India doesn't lose by 10 wickets remaining this time against Pak Hopefully India doesn't lose by 10 wickets remaining this time against Pak
(6.2) Suppressing the print Function’s Ending Newline
The print function normally displays a line of output. For example, the following three
statements will produce three lines of output:
print('One')
print('Two')
print('Three')
One Two Three
print('One', end=" ")
print('Two', end=' ')
print('Three')
One Two Three
print('One', end=',')
print('Two', end=',')
print('Three')
One,Two,Three
(6.3) Formatting Numbers
format(variable,specifier) function is used to do this
x = 5000/12
print(x)
416.6666666666667
x = 5000/12
print(format(x,'.2f'))
print(format(x,'.1f'))
416.67 416.7
print(format(123456, ',d'))
123,456
Read more about formatting here
7.Conditional Statements
(7.1) If-Else Statement
```
if condition:
statement
statement
etc.
else:
statement
statement
etc.
```
temperature = 36
if temperature < 40:
print("A little cold,isn't it?")
print("Turn up the heat!!")
else:
print("Nice weather we're having")
print("Pass the sunscreen")
A little cold,isn't it? Turn up the heat!!
Note : Indentation is extremely important! Use TAB instead of Space
INDENTATION HELL !!!
number = 5
if number == 1:
print('One')
else:
if number == 2:
print('Two')
else:
if number == 3:
print('Three')
else:
print('Unknown')
(7.2) If-Elif-Else Statement
When multiple conditions need to be tested
```
if condition_1:
statement
statement
etc.
elif condition_2:
statement
statement
etc.
else:
statement
statement
etc.
```
Need For If-Elif-Else
number = 5
if number == 1:
print("one")
elif number == 2:
print("two")
elif number == 3:
print("three")
else:
print("unknown")
(7.3) Relational Operators and Boolean Expressions
Read about how strings are compared here
(7.4) Logical Operators
a=34
b=26
if a>1 or b>1:
print("something")
something
Short-Circuit Evaluation of Logical Operators
1) In case of and operator, if the left boolean expression evaluates to False, then the entire compound boolean expression evaluated to FALSE without the right boolean expression being checked
2) In case of or operator, if the left boolean expression evaluates to True, then the entire compound boolean expression evaluated to True without the right boolean expression being checked
#Short-circuiting of and operator
num = 10
if num>10 and num%2 == 0:
print("Ok")
else:
print("Not OK")
Not OK
#Short-circuiting of or operator
num = 10
if num==10 or num%2 == 0:
print("Ok")
else:
print("Not OK")
Ok
8.Let's recapitulate what we have learnt so far with this question
Determine whether a customer qualifies for a loan based on the following criteria
(a)Annual salary is greater than 300000
(b)Minimum work Experience is greater than 3 years
9.Some More Operators with their precedence and associativity
Read here
10.Repetition Structures - Loops
(10.1)Motivation
a = 10
print(a)
print(a+1)
print(a+2)
print(a+3)
print(a+4)
#.
#.
#.
print(a+100)
We can do better!!
a = 10
for i in range(100):
print(a+i)
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
Notion of Repetition Structures
(10.2) While Loop
1.Condition Controlled Loop
2.Executes the statements inside until the given condition is TRUE
#Initialize a starting condition
life = 10
#Declare the loop
while life > 0:
print(f'Lives Remaining {life}')
life = life - 1
Lives Remaining 10 Lives Remaining 9 Lives Remaining 8 Lives Remaining 7 Lives Remaining 6 Lives Remaining 5 Lives Remaining 4 Lives Remaining 3 Lives Remaining 2 Lives Remaining 1
BEWARE OF INFINITE LOOPS
#Initialize a starting condition
life = 10
#Declare the loop
while life > 0:
print(f'Lives Remaining {life}')
#Another way to represent infinite loop
while True:
print('DEAD!!')
(10.3) For Loop
1.Count Controlled Loop
2.Used when the no of times the loop needs to execute is known beforehand
#Execute loop for 5 times
for num in [1,2,3,4,5]:
print(num)
1 2 3 4 5
#Use Range function instead of manually typing out the numbers
for num in range(10,0,-1):
print(num)
10 9 8 7 6 5 4 3 2 1