Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python Basic Part 1

The document discusses iteration in Python using while and for loops. It describes the basic components of a while loop including initialization, condition, block of code, and increment/decrement. It also discusses for loops, iterating over sequences using for loops, the range function, nested loops, and some problems involving loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Basic Part 1

The document discusses iteration in Python using while and for loops. It describes the basic components of a while loop including initialization, condition, block of code, and increment/decrement. It also discusses for loops, iterating over sequences using for loops, the range function, nested loops, and some problems involving loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Iteration

When to use: When you want to complete some task that requires you to do
some sort of sub tasks more than one time

Two types of iteration can be done in python


1. While Loop

2. For Loop

While Loop
When to use:
1. If you always want to run a block of code

2. If you want to run any repetitive block of code based on a condition

Building blocks of while loop


1. Initialization (Initializing the starting point of the loop)

2. Condition (To determine when the loop will stop)

3. Block of code (Which part will repetitivly execute)

4. Increment/Decrement (Increment and Decrement of inital value to meet the


stopping condition)

How the while loop looks:

initializing_loop_controller

while (condition):

block_of_code
increment/decrement

initial_val = 0 #3
            #2<3
while initial_val<3:            #2
  print("Doing some task", initial_val)
  initial_val += 1 # 2+1 = 3

print("remaining lines of the code")

Doing some task 0


Doing some task 1
Doing some task 2
remaining lines of the code
Infinite Loop
The loop that never meets an ending condition and always excutes the block of
code

This happens because:


1. The condition is always True

Condition can be simply given as True boolean value


No increment or decrement was done
Increment or Decrement might not be relevant to the condition

2. There is no loop control to break out of the loop

#Condition can be simply given as True boolean value
initial_val = 0
while True:
  print("Doing some task")
  initial_val += 1 

#No increment or decrement was done
initial_val = 0

while initial_val<5:
  print("Doing some task")

#Increment or Decrement might not be relevant to the condition
initial_val = 0 #

while initial_val<5:
  print("Doing some task")
  initial_val -= 1 

Loop Control
We can use some keywords to control the flow of a loop. These keywords are:
1. break (Ends the loop without considering ending condition)

2. continue (Skips the current iteration of the loop and continues to the next one)
#break statement
task_no = 1 #3
          #3<=5
while task_no<=5:
         #3==3
  if task_no==3:
    print("Doing task",task_no)
    break
  print("Doing task",task_no)
  task_no += 1

print("remaining.....")

#continue statement
task_no = 1 #3
          #3<=5
while task_no<=5:
       #3==3
  if task_no==3:
    continue
    #....
  print("Doing task",task_no)
  task_no += 1 

#continue statement
task_no = 1

while task_no<=5:
  if task_no==3:
    task_no += 1
    continue
  print("Doing task",task_no)
  task_no += 1

Doing task 1
Doing task 2
Doing task 4
Doing task 5

Nested While Loop


A while loop within a while loop

house_no = 1
room_no = 1
        #1
while house_no <= 4:
  print("Entered House #",house_no)
          #1
  while room_no <= 3:
    print("Entered Room #",room_no, "of House #", house_no)
    room_no += 1
  print("Leaving House #", house_no)
  room_no = 1
  house_no +=1

Sequence Data Type: List


List can be collection of variables

These variables can be of different data types

We keep the element of the list between thrird braces and separated by comma

[element1, element2, element3, ........., elementN]

We can asign the list to a variable

list_val = [element1, element2, element3, ........., elementN]

#List can be of integer types
int_list = [1, 2, 3, 4, 5, 6]

#list can be of string type
str_list = ["Alice", "Bob", "Charlie", "Dave", "Ethan"]

#List can also be of another data types which we will see later

Indexing of List
Each element in a list have their specific index

Index starts from zero

So for N number of elements in a list there will be 0 to N-1 index

We can access specific index

For that we have to write the variable that is assigned to the list and put the
index number within the third braces
var_name_the_list_was_assigned_to[indexNo]

#Indexing of a list
str_list = ["Alice", "Bob", "Charlie", "Dave", "Ethan"]
          #   -5       -4       -3       -2        -1
print(str_list[0])
print(str_list[1])
print(str_list[-1]
print(str_list[-6])
#0 to N-1 -> 0 to 4
#Neg Indexing -1 to -N -> -1 to -5

For Loop
When to use:

1. If you want to iterate over the elements of a sequence

2. If you want to run any repetitive block of code for fixed number of times

How the for loop looks:


for iterating_var in sequence_var_name:

block_of_code
names = ["Alice", "Bob", "Charlie", "Dave", "Ethan"]

for elem in names:
  print(elem)
  #...... 3k

print("while loop")
count = 1 #6

       #6<=5
while count<=len(names):
         #names[1]
  print(names[count-1])
  count +=1

print("remaining.....")

For Loop with range function


As for loop needs a sequence to work with, manually setting up the sequence
as a list or other data types takes too much of effort

So to overcome this issue we can use the range function

range function returns a sequence of numbers which is usually helpful when we


want to a spcific task again and again for a certain number of time

range function takes 3 arguments

This is how the range function should look:


range(start, end, step_size)

start indicates the starting value of the range. If it is not defined, the inital value
is 0. This is inclusive, meaning it will start from the value the function is given

end indicates the stopping value of the range. Must be defined for the function
to work. This is exclusive, meaning the range will end before this value and will
not include this value

step_size indicates how the range will increase or decrease. The default value
is 1 which indicates the value in the range increases by 1

for num in range(-2, -14, -3):
  print(num)

Nested For Loop


A for loop within a for loop

for house_no in range(1,5):
  if house_no==3:
    break
  print("Entered House #",house_no)
  for room_no in range(1,4):
    print("Entered Room #",room_no, "of House #", house_no)
    if house_no==2 and room_no==2:
      break
print("Remaining lines of codes")

#Show Loop Control Statements

Few Problems

#3-10
#Adding all the odd numbers from 1 to 50

val = 1
sum_ = 0
while val <= 50:
  if val%2==1:
    sum_ += val
  val += 1

print(sum_)

625

sum_ = 0

for i in range(1,51):
  if(i%2==1):
    sum_ += i

print(sum_)

625

val = 1
sum_ = 0

while val <= 50:
  sum_ += val
  val += 2

print(sum_)

625

sum_ = 0

for i in range(1,51,2):
  sum_ += i
print(sum_)

625

#11-13
#Printing the digits in the numbner

num = int(input("Please enter a number: "))
#253 -> 2, 5, 3
#253//100 = 2
#2*10^2+5*10^1+3*10^0
#   200+    50+3
# = 253
#divide it by 10^2
#10^(no_of_digits-1)

#84657 -> 8, 4, 6, 5, 7
#84657//10000 = 8
#84657%10000 = 4657 -> 10^4/10 -> 10^3

#We need to figure out how many digits are there
num_copy = num
count_digit = 0
while num_copy > 0:
  #print(num_copy%10) #-> Prints the last digit
  count_digit += 1
  num_copy = num_copy//10
#print("Total Digits", count_digit)

#num_copy= 0 #count_digit = 3
#while 0 > 0:
  #print(0%10) -> 5, 3, 2
  #count_digit += 1
  #num_copy = 0//10 -> 0

#we found the digit count now need to follow the simple algorithm

#lets store that number which we need to divide by to a variable

#84657
#84657//10000 = 8
#84657%10000 = 4657

#4657
#4657//1000 = 4
#4657%1000 = 657
floor_div = 10**(count_digit-1)
#print(floor_div)

while num > 0:
  print(num//floor_div)
  num = num%floor_div
  floor_div = floor_div//10

#num = 0
#floor_div = 1
#while 0 > 0:
  #print(0//1) -> 2, 3, 5
  #num = 0%1 -> 0
  #floor_div = 1//10 -> 0
#14-16
#Finding if the number is prime
starting = 2
ending = int(input("Please enter a number: "))

#If a number is prime, it is only divisable by 1 and that number. so the prime number is divi

str_ = ""

for i in range(starting, ending+1):
  
  div_count = 0

  for j in range(1, i+1):
    if i%j==0:
      div_count += 1

  if div_count == 2:
    print(i)
    str_ += str(i)+","
   

print(str_[:-1])

num = int(input("Please enter a number: "))

isPrime = True

for i in range(2, num):
  if num%i==0:
    isPrime = False
    print("Number is not a prime number")
    break
    
if isPrime:
  print("Number is a prime number")

#17
#Check min max and avg from user input

#Ask the user how many number he wants to input
quan = int(input("Please enter the number of times you want to provide input "))

#5
#-5, 36, 21, -35, 72
#max=72
#min=-35
#sum=89
#avg= 89/5

min_ = 0
max_ = 0
sum_ = 0
avg_ = 0

for i in range(quan):
  num = int(input("Please enter the number "))
  
  if i==0:
    min_ = num
    max_ = num
  else:
    if num > max_:
      max_ = num
    if num < min_:
      min_ = num
  
  sum_ += num

avg_ = sum_/quan

print("Max num is ", max_)
print("Min num is ", min_)
print("Average is ", avg_)

Please enter the number of times you want to provide input 5


Please enter the number -5
Please enter the number 31
Please enter the number 21
Please enter the number -35
Please enter the number 78
Max num is 78
Min num is -35
Average is 18.0

Printing various pattens

For these kind of problems we need to consider the row and


column of the structure
We need to find a patter which indicates how the row and
columns are chaning
#

##

###

####

#####

think about this structure

#18-20
#Printing patterns

#initiate row and column

row_ = 5
column_ = 5
#        3            [1,2,3,4,5]
for current_row in range(1,row_+1):
       #   1                 [1,2,3] (1,4)
  for current_column in range(1,current_row+1):
    print("#", end="")
  print("")
#

You might also like