TIME NOW
World current time now,
CALENDAR
Calendar monthly, yearly
login CONVERT LENGTH
login CONVERT TEMPERATURE
login DICTIONARIES, LISTS
login SCIENCE EDUCATION RELIGION
login WORK CALCULATOR
login CALCULATE LIFE

Python 3 programming language, learn python, tutorial

Previous articlePage bottomNext article  ALL TOPICS

Python 3. for loop

 1. Fibonacci series:
a, b = 0, 1
while b < 10:
  a, b = b, a+b
  print("a = ",a , "b = ",b ,end = '\n')

Result:
a =  1 b =  1
a =  1 b =  2
a =  2 b =  3
a =  3 b =  5
a =  5 b =  8
a =  8 b =  13

2. Loop for the list:
words = ['day', 'year', 'month']

for w in words:
  print(w, len(w))

Result:
day 3
year 4
month 5

2a. Calculate list of squares. Get sequences.Try this:
squares = []

for x in range(10):
    squares.append(x**2)

print (squares)

The same example:
squares = [x**2 for x in range(10)]
print (squares)

2b. Create dictionary using loop:
dict = {x: x**2 for x in (2, 4, 6)}
print (dict)


2c. Matrix
w, h = 8, 5;

Matrix = [[0 for x in range(w)] for y in range(h)]

print ( Matrix )

2d. Matrix, min, max values
#
matrix = [[0]*5 for i in range(5)]
print (matrix)

#
matrix = [[0]*5]*5
print (matrix)

#
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
    for i in k:
        dup.append(i)

print (max(dup), min(dup))

Generating lists: http://www.secnetix.de/olli/Python/list_comprehensions.hawk

3. How to change the list:
words = ['day', 'year', 'month']
for w in words[:]:  # Loop over a slice copy of the entire list.
  if len(w) > 3:
    words.insert(0, w)

print (words)

Result:
['month', 'year', 'day', 'year', 'month']

3a. range(). Try this:
for i in range(5):
  print(i)

print()

for i in range(5, 10):
  print(i)

print ()

for i in range(0, 10, 3):
  print(i)

print ()

for i in range(-10, -100, -30):
  print(i)
 

4. range(), using list. len() is a length of the list :
a = ['milimeter', 'centimeter', 'meter', 'km', 'decimeter']
for i in range(len(a)):
  print(i, a[i])
 
Result:
0 milimeter
1 centimeter
2 meter
3 km
4 decimeter

5. range(). Try this:
# not list
print (range(5))

#list
print ( list(range(5)))

6. break. for can have else. This else is not for if.  It is executed when the loop terminates through exhaustion of the list
for n in range(2, 100):
  for x in range(2, n):
    if n % x == 0:
      print(n, 'equals', x, '*', n//x)
      break
  else:
    #loop fell through without finding a factor
    print (n, 'is a prime number')

7. for loop and continue:
for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found a number", num)

7a. Replace characters:
my_string = "ABsolutE Zero"
mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
    my_string = my_string.replace(k, v)
print (my_string)

7b. Replace characters:
my_string = "ABsolutE Zero"
replaceDict = {'A':'1','B':'2','C':'3','D':'4','E':'5'}
      
for key, replacement in replaceDict.items():  
  my_string = my_string.replace( key, replacement )
 
print (my_string )

8. pass:
while True:
     pass

9. Print names:
a="jonas - 10, simas - 20, petras - 30"

names = a.split(',')
print (names)
for x in range(names.__len__()):
    print(names[x].split('-')[0].strip())
 
9a. Print names:
a="jonas - 10, simas - 20, petras - 30"

list = a.split(", ")

for i in range (0,3):
   print (list[i][:-4])

Task 1:
Get two lists: names and money. Amount of ements and values are various.
["jonas","simas", "petras","ona"]
[10,20,50,1]

11a. Errors:
string="jonas - 30USD, simas - 50USD, petras - 30USD"

b = dict(e.split('  -  ') for e in string.split(', '))

print(b)

11b. No errors:
sring="jonas - 30USD, simas - 50USD, petras - 30USD"

b = dict(s.split(' - ') for s in sring.split(', '))

print(b)

11c. Generate dictionary:
string="jonas - 30USD, simas - 50USD, petras - 30USD"

dictionary = dict(list(s.split(' - ')) for s in string.split(', '))

for i, j in dictionary.items():       # use iteritems in py2k
    dictionary[i] = dictionary[i].replace("USD", "")

print(dictionary)

12. Dictionary of names and values:
x ={}
e="jonas - 30USD, simas - 50USD, petras - 30USD"
a = [d for d in e.split(', ')]

for dd in range(len(a)):
    ss= list(a[dd].split(' - '))
    x.update({ss[0]:ss[1].replace("USD","")})

print (x)

12. Multiprocess:
from multiprocessing import Process

def loop_a():
    while 1:
        print("a")

def loop_b():
    while 1:
        print("b")

if __name__ == '__main__':
    Process(target=loop_a).start()
    Process(target=loop_b).start()

Task 2:
String:
a="jonas - 3USD, simas - 50USD, petras - 30USD"

Values can differ. 
Amount of names-money pairs can differ.

Get names and money. 
If money >= 30 additionaly prints "Too much".
And
If money <= 5  additionaly prints "Not much":

Result:
ona has 15 USD.
simas has 50 USD. Too much.
jonas has 3 USD. Not much.
....

Previous articlePage topNext article  ALL TOPICS


Andrius:
1.   
x = int(input("Iveskite norima x reiksme: "))
y = int(input("Iveskite norima y reiksme: "))
s = 0
while s < 100:
y = y + 1
x = x + 1
s = x + y
print("y = ",y , "x = ", x , "Suma = ", s) 

2.
x = int(input("Iveskite norima x reiksme: "))
y = int(input("Iveskite norima y reiksme: "))
s = 0
for n in range(x):
for x in range(y):
s = n + x
print(n, "sudejus", x ,"gausime" ,s)


2015-11-02 06:10:49
Vitalij:
a,b=0,7
print("Atspekite skaiciu")
while a!=b:
a=int(input())
if a==b:
print("Skaicius atspetas")
else:
print("Bandikite dar karta")

print("Daugybos lentele")
for a in range(1,10):
for b in range(1,10):
print(a,"*",b,"=",a*b)
print("\n")


2015-11-02 07:46:47
Mindaugas:
print("=============pirmas pavyzdys====================")

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print (i, " is prime")
   i = i + 1

print ("Good bye!")

print("==============antras pavyzdys==================")
for num in range(1,11):  #to iterate between 1 to 11
   for i in range(2,num): #to iterate on the factors of the number
      if num%i == 0:      #to determine the first factor
         j=num/i          #to calculate the second factor
         print ('%d equals %d * %d' % (num,i,j))
         break #to move to the next number, the #first FOR
   else:                  # else part of the loop
      print (num, 'is a prime number')
print("==============trecias pavyzdys================")
import random
n = 20
to_be_guessed = int(n * random.random()) + 1
guess = 0
while guess != to_be_guessed:
    guess = int(input("New number: "))
    if guess > 0:
        if guess > to_be_guessed:
            print("Number too large")
        elif guess < to_be_guessed:
            print("Number too small")
    else:
        print("Sorry that you're giving up!")
        break
else:
    print("Congratulation. You made it!")


2016-04-19 12:09:45

 Use username: Guest, Anonymous, Programmer






QUOTES:
Ceremony leads her bigots forth, prepared to fight for shadows of no worth. While truths, on which eternal things depend, can hardly find a single friend.
William Cowper
Once you have traveled, the voyage never ends, but is played out over and over again in the quietest chambers, that the mind can never break off from the journey.
Pat Conroy, The Prince of Tides
The only source of knowledge is experience.
Albert Einstein