DEV Community

Cover image for Python : Part 1 - Programming (Python 101)
Srinivasulu Paranduru for AWS Community Builders

Posted on • Edited on

Python : Part 1 - Programming (Python 101)

IDE's used for development : Visual studio code

Extension used in visual studio code :

  1. Python
  2. Code Runner

Create a simple python file - helloworld.py and run it using the extension Code Runner and will see more details

print('Hello World!')
Enter fullscreen mode Exit fullscreen mode

Image description

To see clear output in visual studio code
Go to Visual studio code -> settings ( follow step 1 and step 2)

Step 1: Unselect the checkbox shown in the below image

Image description

Step 2 : Clear the previous outputs in visual studio by
Searching Clear Previous Output in settings and select the option

Image description

Step 3: Run the code and see the output is clean and clear

Image description

Using IDLE :
Go run and search with IDLE and select IDLE App

Image description

Run the below commands in IDLE

2+2
print('Hello world!')
name = 'srinivas'
name = + 'ulu'

Image description

New window in IDLE, copy the below mentioned code and save it as Hello.py

Image description

Hello.py

print('Hello world!')
print('What is your name?') #ask for name
myName=input()
print('Nice to meet you,' + myName)
print('The length of your name is :')
print(len(myName))
print('What is ur age?')
myAge= input()
print('You will be ' + str(int(myAge)+1) + ' in a year.')

Enter fullscreen mode Exit fullscreen mode

Table 1.1 - Comparison Operators

Operator Meaning
== Equal to
!= Not Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Try the below statements in IDLE

42 == 42
42 == 99
2 != 3
2 != 2
'hello' == 'hello'
'hello' == 'Hello'
42 < 100

Table 1.2 - The and Operator’s Truth Table

Expression Evaluates to
True and True True
True and False False
False and True False
False and False False

Table 1.3 - The or Operator’s Truth Table

Expression Evaluates to
True or True True
True or False True
False or True True
False and False False

Table 1.4 - The not Operator
Unlike and and or, the not operator operates on only one Boolean value (or expression). This makes it a unary operator

Expression Evaluates to
not True False
not False True

1.Flow Control Statements
1.1 if Statements : If the statement clause is true then it will execute else it will skip

if.py

 name = 'Srini'
 if name == 'Srini':
    print('Hi, Srini.')
Enter fullscreen mode Exit fullscreen mode

1.2 else statements: If the statement clause is false then else condition will be executed

else.py

 name = 'Srini'
 if name == 'Srini':
    print('Hi, Srini.')
 else
    print('Hello Stranger')
Enter fullscreen mode Exit fullscreen mode

1.3 elif Statements: You may have a case where you want one of many possible clauses to execute.

elif.py

name = 'Carol'
age = 9999
if name == 'Alice':
    print('Hi, Alice.')
elif age < 12:
    print('You are not Alice, kiddo.')
elif age > 2000:
    print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
    print('You are not Alice, grannie.')
Enter fullscreen mode Exit fullscreen mode

2. Visualisation: If we wanted to see the visualisation of your program then render the url -https://pythontutor.com/

Image description

copy the code in the editor and click on visualise execution

Image description

By clicking on Next, we can see the result

Image description

3. While loop:

  • When the execution reaches the end of a "while" statement's block, it jumps back to the start to re-check the condition.
  • You can press ctrl-c to interrupt an infinite loop.
  • A "break" statement causes the execution to immediately leave the loop, without re-check the condition.
  • A "continue" statement causes the execution to immediate jump back to the start of the loop and re-check the condition.

3.1 Simple while loop program - while1.py

name = ''
while name != 'Srinivas' :
    print('Enter your name:')
    name = input()
print('thank you!')

Enter fullscreen mode Exit fullscreen mode

3.3 While with infinite looping - while_Infinite_Loop.py

while True :
    print('How are you doing buddy')

Enter fullscreen mode Exit fullscreen mode

Note : To break the infinite loop, press Ctrl+C to come out of the loop

Image description

3.3 While loop using break - While_break.py

name = ''
while True :
    print('Enter your name:')
    name = input()
    if name == 'srinivas' :
       break
print('Thank you!')

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

3.4 While loop with continue - While_Continue.py

count = 0
while count < 5 :
    count = count + 1
    if count == 2 :
        continue
    print(' count is ' + str(count))

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

4. for loop :

  • "for" loop will loop a specific number of times.
  • The range() function can be called with one, two, or three arguments.
  • The break and continue statements can be used in for loops just like they're used in while loops.

Using range function in for loop
range(param1,param2,param3)
param1 : start index
param2 : end index
param3 : can be used as increment / decrement the range

4.1 forloop.py

print('My name is')
for i in range(5):
    print('Srinivas Five Times ' + str(i))
Enter fullscreen mode Exit fullscreen mode

Output of the above program :
My name is
Srinivas Five Times 0
Srinivas Five Times 1
Srinivas Five Times 2
Srinivas Five Times 3
Srinivas Five Times 4

4.2 For loop with ranges with single parameter- forloop1.py

total =0
for num in range(101):
   total = total + num
print(total)

Enter fullscreen mode Exit fullscreen mode

Output of the above program :
5050
4.3 For loop with ranges with double parameter- forloop2.py

print('My name is')
for i in range(5,8):
    print('Srinivas Five Times ' + str(i))
Enter fullscreen mode Exit fullscreen mode

Output of the above program :
My name is
Srinivas Five Times 5
Srinivas Five Times 6
Srinivas Five Times 7

4.3 For loop with ranges with triple parameter with incrementing by 1(third parameter) - forloop3.py

print('My name is')
for i in range(0,10,1):
    print('Srinivas Five Times ' + str(i))
Enter fullscreen mode Exit fullscreen mode

Output of the above program :
My name is
Srinivas Five Times 0
Srinivas Five Times 1
Srinivas Five Times 2
Srinivas Five Times 3
Srinivas Five Times 4
Srinivas Five Times 5
Srinivas Five Times 6
Srinivas Five Times 7
Srinivas Five Times 8
Srinivas Five Times 9

4.4 For loop with ranges with triple parameter with decrementing by 1(third parameter) - forloop4.py

print('My name is')
for i in range(5,-1,-1):
    print('Srinivas Five Times ' + str(i))
Enter fullscreen mode Exit fullscreen mode

Output of the above program :
My name is
Srinivas Five Times 5
Srinivas Five Times 4
Srinivas Five Times 3
Srinivas Five Times 2
Srinivas Five Times 1
Srinivas Five Times 0

5.Python Builtin Functions:

5.1 Built in functions:

  • print()
  • len()
  • input()

5.1.1 Import the modules

5.2.1 Import single library

import random
random.randint(1,10)
Enter fullscreen mode Exit fullscreen mode

Note: Try the above command in IDLE shell, we will keep getting random numbers.

5.1.2 Import multiple libraries

import random,sys,os,math
from random import *   # this is alternative to import statement
randint(1,10)

Enter fullscreen mode Exit fullscreen mode

Note : No need to call random.randint(1,10) in the above scenario

5.1.3 sys.exit()

import sys
print('Hello')
sys.exit()
print('Good bye')
Enter fullscreen mode Exit fullscreen mode

Output is
Hello

5.1.4 Third party modules : We can install the third party modules using pip program and which also comes with python

Image description

import pyperclip
pyperclip.copy('Hello World!')
pyperclip.paste()
Enter fullscreen mode Exit fullscreen mode

Output of the above program is
Hello World!

5.2.Write your own functions:

Example 1 : function1.py

def hello() :
    print('Ireland')
    print('UK')
    print('Chennai')

hello()
hello()
hello()
Enter fullscreen mode Exit fullscreen mode

Output of the above program is
Ireland
UK
Chennai
Ireland
UK
Chennai
Ireland
UK
Chennai

Note : Copy the above code and try in https://pythontutor.com/

5.2.1 Try to add arguments to the functions

def hello(name) :
    print('Hello ' +name)

hello('Srini')
hello('Bob')

Enter fullscreen mode Exit fullscreen mode

5.2.2 Return from function

Image description

Try the below items in IDLE shell
print('Hello')
print('World')

print('Hello', end='')
print('world')
print('cat','dog','mouse')
cat dog mouse

print('cat','dog','mouse',sep='$$')
cat$$dog$$mouse

6.Global and local scope variables

  • The global scope is code outside of all functions. Variables assigned here are global variables.
  • Each function's code is in its own local scope. Variables assigned here are local variables.
  • Code in the global scope cannot use any local variables.
  • If there's an assignment statement for a variable in a function, that is a local variable. The exception is if there's a global statement for that variable; then it's a global variable.

6.1 Example 1

spam =42 # global variable

def sum():
    spam = 42 # local variables
print('Some code here')
print('Some code here')

Enter fullscreen mode Exit fullscreen mode

6.2 Example 2

def spam():
    egg = 99
    bacon()
    print(eggs)

def bacon():
    ham = 101
    eggs = 0

spam()

Enter fullscreen mode Exit fullscreen mode

6.3 Example 3

def spam():
    global eggs  # to use the variable as global 
    eggs = 'Hello'
    print(eggs)

eggs =42
spam()
print(eggs)

Enter fullscreen mode Exit fullscreen mode

7.Exception Handling:

7.1 Example1 : exception.py


def div64by(divideBy):
    return 64  / divideBy

print(div64by(2))
print(div64by(8))
print(div64by(0))
print(div64by(1))
Enter fullscreen mode Exit fullscreen mode

Image description

Code fails in printing the function 3 with division by 0 error

  • Exceptions can be handled using try and except statements

7.1.1 Modify the above code


def div64by(divideBy):
    try:
        return 64  / divideBy
    except ZeroDivisionError :
        print('Error:You tired to divide by zero.')

print(div64by(2))
print(div64by(8))
print(div64by(0))
print(div64by(1))
Enter fullscreen mode Exit fullscreen mode

Output of the above program is

32.0
4.0
Error:You tired to divide by Zero
None
64.0

7.2 Example 2

  • Try the birds count as integer and check the output
  • Then try with string as input, it will fail then handle it using try and except
print('How many birds do you have?')
numbirds = input()
if int(numbirds) >= 4 :
       print('That is a lot of birds')
 else:
        print('That is not that many birds')

Enter fullscreen mode Exit fullscreen mode
print('How many birds do you have?')
numbirds = input()
try:
    if int(numbirds) >= 4 :
       print('That is a lot of birds')
    else:
        print('That is not that many birds')
except ValueError:
    print ('You did not enter a number.')

Enter fullscreen mode Exit fullscreen mode
  • A divide-by-zero error happens when Python divides a number by zero.
  • Errors cause the program to crash.
  • An error that happens inside a try block will cause code in the except block to execute. That code can handle the error or display a message to the user so that the program can keep going.

8. Lists: (using IDLE shell for below demos)

8.1 Simple List

#1. Try the commands in the IDLE Shell
['cat','bat','rat','elephant']

#2. Commands in IDLE Shell
info = ['cat','bat','rat','elephant']
info

# To Access values in a list, use indexes
#3. Try the commands in IDLE Shell
info[0]
info[1]
info[2]
Enter fullscreen mode Exit fullscreen mode

8.2 Lists of Lists

spam = [ ['cat','bat'],[10,20,30,40]]

spam[0]
['cat','bat']

spam[1]
[10,20,30,40]

spam[0][0]
spam[0][1]
spam[1][0]
spam[1][1]
spam[1][2]

# Try all the above commands in python visualise
Enter fullscreen mode Exit fullscreen mode

8.3 Negative Indexes

  • -1 => Refers to last Index
  • -2 => Refers to last but one Index

info = ['cat','bat','rat','elephant']
info[-1]
'elephant'
info[-2]
'rat'

8.4 Try with string concatenation with lists

'The' + info[-1] + ' is afraid of the ' + info[-3] +'.'
Output is
'The elephant is afraid of the bat.'

Index is single Value
Slice is list of values

info[1:3]
['bat','rat']

8.5 Changing a List's item

info = 'Hi Dude !'
info # 'Hi Dude !'
info =[10,20,30]
info[1] =['Cat','Dog','Mouse']
info # [10,'Cat','Dog','Mouse']
Enter fullscreen mode Exit fullscreen mode

8.6 Slice Shortcuts

info=['cat','bat','rat','elephant']
info[:2] # When the start index is empty , it will treat as 0
# output is ['cat','bat']

info[1:] # When the end index is empty, it count till the end
Enter fullscreen mode Exit fullscreen mode

8.7 Delete a item from a list using del statements

del statement is a unassigned statement

del info[2]

info
# output is ['cat','bat','elephant']


del info[2]

info
# output is ['cat','bat']
Enter fullscreen mode Exit fullscreen mode

8.8 String and list similarities

len('Hello')
# output - 5
len([1,2,3])
# output  - 3
'Hello ' +'world'
# output - Hello world
[1,2,3] + [4,5,6]
#output - [1,2,3,4,5,6]

# string replication
'Hello'*3 
#list replication
[1,2,3] * 3   # ouput : [1,2,3,1,2,3,1,2,3]

list('hello')  # ['H','e','l','l','o']

# in and out operators

'howdy' in [ 'hello','hi','howdy','heyas'] # output - True

'howdy' not in [ 'hello','hi','howdy','heyas'] # output - False
Enter fullscreen mode Exit fullscreen mode

8.9 For loops with lists:

#1
for i in range(4):
    print(i)

#2
range(4)
range(0,4)
#output- [0,1,2,3]

#3
for i in [0,1,2,3]:
    print(i)
#ouput
0
1
2
3

#4
list(range(4))
# output : [0,1,2,3]

#5
list(range(0,10,2))
# output :  [0,2,4,6,8,10]
Enter fullscreen mode Exit fullscreen mode

# for i in range(len(somelist)) :


#6
supplies = ['pens','staplers','pins','books']
for i in range(len(supplies)):
    print('Index ' +str(i) +' in supplies is:  ' + supplies[i])

Index 0 in supplies is pens 
Index 1 in supplies is staplers 
Index 2 in supplies is pins 
Index 3 in supplies is books 

Enter fullscreen mode Exit fullscreen mode

8.10. Multiple Assignments in lists:

#1
info = ['fat','orange','loud']
size = info[0]
color = info[1]
di = info[2]
Enter fullscreen mode Exit fullscreen mode

Muliple variable assignments

size,color,di = cat 
#0 index maps to first variables, 1 index maps to second variables and etc.,
size # 'fat'
di # 'loud'
Enter fullscreen mode Exit fullscreen mode

*# n to n variables assignment *

size,color,di = 'skinny','blue','noisy'

a= 'AAA'
b='BBB'
#if you wanted to swap variables
a,b= b,a
Enter fullscreen mode Exit fullscreen mode

8.11 Augmented operators

Augmented Assignment Statement Equivalent Statement
info+=1 info =info+1
info-=1 info =info-1
info*=1 info =info*1
info/=1 info =info/1
info%=1 info =info%1

8.12 List Methods

  • index()
  • append()
  • insert()
  • remove()
  • sort()

8.12.1. index()

spam = ['hello','hi','howdy','heyas']
spam.index('hello')
#output : 0

spam.index('howdy')
#output : 2

#if the list is having duplicate values
spam = ['hello','hi','howdy','howdy']
spam.index('howdy')
#ouput : 2 # it will return the first index

Enter fullscreen mode Exit fullscreen mode

*8.12.2. append(),insert(),remove(),sort() *

#append() method
spam = ['cat','dog','bat']
spam.append('rat')
['cat','dog','bat','rat']


#insert() method
spam = ['cat','dog','bat']
spam.insert(1,'rat')
['cat','rat','dog','bat']


#Try with strings
info= 'hello'
info.append(' world')

#remove() method

info = ['cat','dog','bat']
info.remove('bat')
info
['cat','dog']


#delete using del
del info[0]
info
['dog']

# if the list having duplicate values
info = ['cat','dog','bat','cat','dog','bat']
info.remove('cat')
info

#output :
['dog','bat','cat','dog','bat']

#sort() method

#1
spam = [1,2,3.14.5,-7]
spam.sort()
spam
#ouput - [-7,1,2,3.14,5]

#2
spam = ['ants','badgers','cat','dogs']
spam.sort()
spam

#3
spam.sort(reverse=True)
spam

#4
spam = [2,3,4,'dogs','cats']
spam.sort()

#output : It will fail - unordertable types - str and int


#5
spam = ['Alice','Bob','apple','carol']
spam.sort()

Enter fullscreen mode Exit fullscreen mode

References :
www.python.org
https://pythontutor.com/
https://docs.python.org/3/tutorial/
https://www.online-python.com/

Conclusion : Discussed about basics of python with samples and discussed visual studio code edito and extension in visual studio and IDLE shell command for running the python code

💬 If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it 😀 and share this blog with ur friends and follow me in linkedin

Buy Me A Coffee

Top comments (0)