snippsat 661 Master Poster

You can simplifying your code as suggest på vegaseat.

Think about design,now you have one long main function.
This make code hard to read and if you want to add more code this will soon get difficult.

Split code upp in more function.
A shorter function is eaiser to test and read.
A function keep code local,so you can use in and other code if you need that later.

Just some code to show you what i mean.

import random

def read_in_file():
    shuffle_txt = open("kn.txt", "r").readlines()
    random.shuffle(shuffle_txt)
    return shuffle_txt

def do_domething(arg):
    '''This is a dok string you can explain what this function do'''
    my_list = arg  
    print my_list  #Just a test print to show how you can get data in from read_in_file()
    
def main():
    while True:
        print '(1)play Knock game'
        print '(2) Quit'
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            shuffle_txt = read_in_file()
            do_domething(shuffle_txt)           
        elif choice == '2':            
           return       
        else:
            print 'Not a correct choice:', choice        
        
if __name__ == "__main__":
    main()
snippsat 661 Master Poster

Example pygtk.
http://www.oluyede.org/blog/writing-a-widget-using-cairo-and-pygtk-28-part-2/

Strong gui-toolkit for python are wxpython,PyQT,PyGTK

Here is a picturer off a alrmarclock a made with wxpython for fun.
http://www.esnips.com/doc/e8f216fc-bf2c-4ddc-b0e2-a5b2ee97fd6b/alarm_win_7

snippsat 661 Master Poster

Kur3k that code will break because your exception handling is wrong.
The code dos not what what is ask for.
It check if an integer for odd/even and has no 'quit' check out.
The code example should like this to make sense.

def check(number):
    if number % 2 == 0:
        return True
    else:
        return False

while True:
      try:
        number = int(raw_input("> Number "))
        if check(number) == True:
            print 'Number did pass it is a even number'
            break
      except ValueError:
        print "Wrong input only numbers,try again"

More like this is what ask for.

my_numbers = []
print 'Enter numbers | calculate <c> quit <q>'
while True:
    try:        
        n = raw_input('Enter a number: ')
        if n.lower() == 'q':
            break        
        elif n.lower() == 'c':
            print sum(my_numbers)
            break
        my_numbers.append(float(n))    
    except ValueError:        
        print 'Please only numbers,try again'
snippsat 661 Master Poster

startswitch/endswith you can use tuple.

if not link.startswith(('javascript','mailto')) and not link.endswith(('pdf','ppt')):
#do something

Depends on how input text is,but a regex can bee used.
Just an untestet regex for this could look something like this. ^javascript|^mailto|pdf$|ppt$ .

Or make variables with tuple as jca0219 suggest.

snippsat 661 Master Poster

Try.
print "You played %s. The computer played %s and %s" % (player_card1, computer_card1, computer_card2)

You can not use a% b% c%
http://docs.python.org/library/stdtypes.html#string-formatting-operations

Most commen formatting expression.
%s == String (converts any Python object using str()).
%d == Signed integer decimal
%f == Floating point decimal format.

snippsat 661 Master Poster

Use lowercase for your string formatting expression.

>>> print 'Hi this is a %s' % 'test'
Hi this is a test
>>> print 'Hi this is a %S' % 'test'
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: unsupported format character 'S' (0x53) at index 14
>>>
snippsat 661 Master Poster

Sneekula code will work fine for CSV string.

Just make and other version,that do just the same.
Maybe better looking,not that it matter so much at all.

def question():
    my_question =\
    ['What is your name? ', 
     'What organization do you work for? ',
     'What is your title at this organization? ',
     'What is the address of your organization, all on one line? ',
     'What is your email address? ',    
     'What is your phone number? ',
     'We will be writing your information to a file. ']
    return my_question
    
def main():    
    my_list = []
    for i in range(7):
        s = raw_input(question()[i])
        my_list.append(s)
        make_string = ','.join(my_list)
    print make_string
    
if __name__ == "__main__":
    main()
snippsat 661 Master Poster

And in what situation is using the global statement not considered ugly?

For me it`s never ok to use,and i have never used it in my code.

Looks unpythonic for me. Like this its OK, for my opinion.

It`s was just an example with function how to avoid global that was postet by Lapix.
You can off course rewrite it to one function,but that was not the point of my post.

snippsat 661 Master Poster

Dont use global statement,it`s a ugly.
A function should keep code local and not send variabels out in global space.

Pass in argument and return in out when you need it.
Do this become to difficult move over to use a class.

def start(my_list=[]):  
    inventory = my_list
    return inventory

def inventory(arg): 
    print "You are carrying:"
    for item in arg:
        print '%s' % item 
    
def main():
    inv_item = start(['gold','food','hammer'])
    inventory(inv_item)    

if __name__ == "__main__":
    main()
snippsat 661 Master Poster

You can look at this and se if it help you out.
And see if this is on right track,should be fast and not use to much memory.
But have to try it out in larger scale.

#This is after ippattern.findall has find ip in log file
'''-->ip_list.txt
100.11.23.45
100.11.23.46
100.11.23.45
100.11.23.48
100.11.23.49
100.11.23.50
100.11.23.51
100.11.23.52
100.11.23.53
100.11.23.52
100.11.23.55
100.11.23.56
100.11.23.55
100.11.23.58
'''
#ip_list has 11 unique ip`s total 14

#open a file for write 
ip_file = open("unique_ips.txt",'w')

#First we count unique ip`s
count_unique_IP = sum(1 for line in set(open('ip_list.txt')))
print count_unique_IP

#Then we find and sort unique ip
with open('ip_list.txt') as f:
    lines = sorted(set(line.strip('\n') for line in f))  
for line in lines:
    print line  #Test print
    ip_file.write(line)
    ip_file.close

'''
11
-->unique_ips.txt
100.11.23.45
100.11.23.46
100.11.23.48
100.11.23.49
100.11.23.50
100.11.23.51
100.11.23.52
100.11.23.53
100.11.23.55
100.11.23.56
100.11.23.58   
'''
snippsat 661 Master Poster

Can you give us "unique_ips.txt".
You can make to new file only smaller,with somthing like 100 ip adresses.

Then it is easier to test out a solution.
And please use 4 space for indentations PEP-8

snippsat 661 Master Poster

If it is a new line character that make this,you can try this quick fix.

operatorless = [item.rstrip() for item in operatorless]
return operatorless

Use print statement for troubleshoothing i think many forget in wxpython.
It will show result in stdout window.

Then you can see if as example if problem come from "wordlist"

spaceles=wordlist.split(" ")
print spaceles  #Test print

Or as many test print you need to track down the problem.

snippsat 661 Master Poster

Dont mix indentations use always 4 space.
Look into function,when you write all in global space it get soon difficult if you want to jump back and fourth between part of the code.

def my_menu():
    menu = """
    Choose the operation to do (1-2):
    1) Add
    2) Substract
    3) Quit
    """
    return menu

def add():
    x = int(raw_input("Give me the first number: "))
    y = int(raw_input("Give me the second number: "))
    print "The result is", (x+y)

def Substract():
    x = int(raw_input ("Give me the first number: "))
    y = int(raw_input("Give me the second number: "))
    print "The result is", (x-y)

def main():
    '''this is called dok string info about function'''
    while True:
        operation = raw_input(my_menu())
        if operation == '1':
            add()
        elif operation == '2':
            Substract()
        elif operation == '3':
            return
        else:
            print 'Not correct input,try again'

if __name__ == '__main__':
    main()

Here you fall back into main when a function is finish.
Then you dont neeed ask this userinput = raw_input ("Want to continue adding?\nA) y\nB) n\n") .
Because user can just type 1 again.

snippsat 661 Master Poster

Thanks. I see what I was missing. When can I use Raw input ?

In python 2.x is best to always use raw_input.
input() is i mix off eval() and raw_input() in python 2.x that return an integer.

Python 3.x has only input() work the same way as raw_input in python 2.x(return a string)
So you may ask,what if a need a integer from user input?

IDLE 2.6.5      
>>> my_input = raw_input('Type something: ')
Type something: test
>>> type(my_input)
<type 'str'>
>>> my_input = raw_input('Type something: ')
Type something: 5
>>> my_input = int(my_input)
>>> my_input
5
>>> type(my_input)
<type 'int'>
>>> #you can make raw_input return an integer
>>> my_input = int(raw_input('Type something: '))
Type something: 8
>>> my_input
8
>>> type(my_input)
<type 'int'>
>>>
snippsat 661 Master Poster

Hint.

lst_1 = ['b','a','c','2','1','3']
lst_2 = ['a','b','3''1','2']

diff_list = sorted([item for item in lst_1 if not item in lst_2])
snippsat 661 Master Poster

And result from my program is not:

Yes it work fine as an alterntive to regex.
But it was ask about how to use that regex and write to a file.

how could I append this code (which seems to be what I need) into yours?

http://www.daniweb.com/forums/post11...ml#post1192186

Many Thanks

Dont now what you mean here.

snippsat 661 Master Poster

You can look at this,did some changes to the regex.
Shoud find valid proxy ok now.

import re

'''-->proxy.txt
202.9945.29.27:80
221.11.27.110:8080
11111.45454.4454.444
114.30.47.10:80
116.52.155.237:80
204.73.37.11255:80
220.227.90.154:8080455
'''
proxy_file = 'c:/test/proxy.txt'

proxy_pattern = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5}\D'
my_compile = re.compile(proxy_pattern)

file2_read = open(proxy_file, 'r')
new_proxy = open('c:/test/new_proxy.txt', 'w')

for currentline in file2_read:
    match_obj = my_compile.search(currentline)
    if match_obj:        
        print currentline.rstrip()  ##Test print      
        new_proxy.write(currentline)    

file2_read.close()
new_proxy.close()

'''-->new_proxy.txt
221.11.27.110:8080
114.30.47.10:80
116.52.155.237:80
'''
snippsat 661 Master Poster

byte of python chapter 10 can help you out.
The zip solution there works best on linux, if you what to compress backup look into zipfile or some 3 party module rar/7zip/lmza.

snippsat 661 Master Poster

the first item in the index is 0, so the last item should there fore be 2

You missing the point he is showing how an IndexOutOfRange exception happends. print(abc[2]) is off course correct,but that not the point here.

snippsat 661 Master Poster

Somthing like this?

def click(self, val):
        s = "Button %s was clicked" % val
        label = tk.Label(text = s, width = 15)
        label.grid(row = 0, column = 0)        
        s = "Button " + val + " clicked"        
        # show result in title
        self.title(s)
snippsat 661 Master Poster

If you want more advace look dont use tkinter.
Tkinter look ugly under windows(Non-native look-and-feel)

This make me not use tkinter at all,i find wxpyhon som much better an it look good under windows.
Button are rounded in wxpython,or there are easy to make the look you what.
And when you move mouse over button it highlight,this dos not ugly tkinter buttons.

PyQt and PyGTK are also good tool-kit(that dont have native look-and-feel under windows.)

snippsat 661 Master Poster

@ultimatebuster
That regex vil match "456729994744"

import re

test_input = '456729994744'

if re.match(r'(\d{3})\D*(\d{3})\D*(\d{4})', test_input):
    print ('That is a valid input')  #That is a valid input  
else:
    print ('This is not a valid input')

A fix vil be this.
^(\d{3})\D*(\d{3})\D*(\d{4})$

Now it seems as this list only has numbers that shall match on lenght.
So no need to match against nr as (573)8841878 or 322-3223-222.
Then d5e5 solution work fine.

snippsat 661 Master Poster

I can write a solution tomorrow(away now),with regex.
Not so difficult to filter out numbers you need.

snippsat 661 Master Poster

What contry do you what valid phone nummers for?

Or give an example of match and not match.
match-
(+44)(0)20-12341234
02012341234

Not match.
(44+)020-12341234
1-555-5555

snippsat 661 Master Poster

Your code it`s not nice and well formated.

Thing that is clear now,can be difficult to understand when you look at code the 6 months time in the future.
And a bad formatet code with no documenting make things a lot worse.
So a well formated code can help yourself to,and make life eaiser for pepole that try to understand the code.

Just some not working code,to give som idè off making better formatet code.

class myClass(object):    
    pass

def my_fuction():
    '''Write short fuction'''    
    pass
    
def my_function1():
    '''Document your code and use clear variable name'''
    pass

def my_function2():
    '''
    Smaller function make it eaiser to test the code
    It`s much better to read well formatet code
    long if if if if else in global space is bad
    try use "if elif else" and retun data out off fuction if it get to long
    '''
    return "some data that need more work"
    pass

def my_function3(data_from_func2):    
    '''
    Work more on data from function2
    Look into TDD
    doctest,nose,uinttest
    It`s good to think off way to test the code
    '''
    pass

def main():
    '''
    Make it clear that code end
    You can use other nane that main if you want
    '''
    
if __name__ == '__main__':
    main()
snippsat 661 Master Poster

Thanks for responding, how to i test this

def list_sort(input_list,):
'''Sort a list'''
return sorted(input_list)

What do you mean?,like this.

def list_sort(input_list,):
    '''Sort a list'''    
    return sorted(input_list)

my_list = [5,9,6,3,7,4,5]    
print list_sort(my_list)    #[3, 4, 5, 5, 6, 7, 9]

It shoul be clear from my code example.

snippsat 661 Master Poster

can someone please show me how the function of the code should look like.

Thanks in advance

>>> a=[4,2,6,0,7,3,9,21,15,12,17,1,0]
>>> a.sort()
>>> a
[0, 0, 1, 2, 3, 4, 6, 7, 9, 12, 15, 17, 21]
>>>

def list_sort(input_list,):
    '''Sort a list'''    
    return sorted(input_list)
    
def remove_dup(input_list):
    '''Remove duplicate from a list'''
    return set(input_list)

def main():
    '''This is called a doc string'''
    my_list = [5,4,2,8,4]
    
    #First we se what the functions dos
    print list_sort(my_list)
    print remove_dup(my_list)
    print '-'*20     
    
    #Then we can combine them,first remove duplicate then sort    
    remove_duplicate = remove_dup(my_list)
    print list_sort(remove_duplicate)   
    
if __name__ == '__main__':
    main()

'''-->Output
[2, 4, 4, 5, 8]
set([8, 2, 4, 5])
--------------------
[2, 4, 5, 8]
'''

You can look at this.
The code is pretty clear,but just a short explanation because you new to this.

Both function take one argument .
The argument in this case is my_list
When return is done function is finish.
You can change return with print,and call it like this list_sort(my_list) .
Then you just print out result in the function,nothing get returned out.

You see the avantage when using return,you can have many function return jobb you want to do.
And in the main() you can pick upp all data and print it out.

snippsat 661 Master Poster
IDLE 2.6.4      
>>> word = raw_input("Please enter a string:")
Please enter a string:racecar
>>> # raw_input is returing a string so dont use "str"
>>> input_word = "word"
>>> input_word
'word'
>>> #Do you see the error now.
>>> word_rev = word[::-1]
>>> word_rev
'racecar'
>>> if input_word == word_rev:
	print "The word you have enterd is a palindrome"
else:
	print"The word you have entered is not a palindrome"

	
The word you have entered is not a palindrome
#Off course because you are comparing against "input_word" that is "word" not "racecar"

>>> #make it easy
>>> word = raw_input("Please enter a string:")
Please enter a string:racecar
>>> if word == word[::-1]:
	print "The word you have enterd is a palindrome"
else:
	print"The word you have entered is not a palindrome"

	
The word you have enterd is a palindrome
>>>

A function for this could look like this.

def is_palindrome(my_string):    
    return my_string.lower() == my_string[::-1].lower()
snippsat 661 Master Poster

What if i wanted to use xcode with python? Can I?

Yes.
http://zovirl.com/2006/07/13/xcode-python/

snippsat 661 Master Poster

Dont use classes if you dont understand how it work yet.
Use 4 space for indentations,no it look ugly.

Just to test you code.

currnt_quest = "Chef's Helper"

def taver_n():
    if currnt_quest == "Chef's Helper":
        done = raw_input("Bar Broski: You finish the quest yet? [yes/no] ")
        if done == "yes":  #MUST CONFIRM FLOUR/EGGS IS IN INV
            print "Bar Broski: Great Job! Here's $500 for your troble..."
            print "Reward 100xp!"
        #You need a else if no if answer.    
            
    print "Trav MCcoy: Welcome to my tavern. Many of the locals here have odd jobs for people that you can do. Quests give you exp to level up so do as many as you can."
    finishquest = raw_input("Are Ya Looking for a ")
    quest_list = ("1)Chef's Helper")
    quest = raw_input("Bar Browski:Hey, You intrested in a quest? [yes/no] ")
    if quest == "yes":
        print 'meny'
        #link to menu
        #manu = menu()
        #manu.main_menu()
    else:        
        print "Bar Browski: Alright another time then."
        print 'Meny'
        #link to menu
        #manu = menu()
        #manu.main_menu()
        
taver_n()

You need a if/else now your code dos the same if you answer yes or no.

done = raw_input("Bar Broski: You finish the quest yet? [yes/no] ")
if done.lower() not in ['yes', 'no']:
   print "Do somethin"
else:
    print 'Do something else'

Take small step and dont make to lagre function,if you make a text game make some time planning.

snippsat 661 Master Poster

This issue just came up in GUI calculator thread, where I prepared a calculator in Tkinter for comparision

Just make it a float,i have done that many time with wxpython for calculator stuff.
When push buttun i getvalue from this.

elif self.c == 'Divide':
    p = float(self.s1) / float(self.s2)
snippsat 661 Master Poster

For python 2.x
eval() has a lot of power and can be safety issue in wrong hands.
a = "__import__('os').remove('important_file')"
print eval(a)

IDLE 2.6.4 
>>> from __future__ import division
>>> 1 / 3
0.33333333333333331
>>>
snippsat 661 Master Poster

Buy him this book can be smart.
http://www.amazon.com/Hello-World-Computer-Programming-Beginners/dp/1933988495
Has some pygame lesson.

Invent Your Own Computer Games with Python
http://inventwithpython.com/

For more basic i think byte og python i good start,and a smart 12 y/o shold cope with it pretty well.
http://www.swaroopch.com/notes/Python

Non-Programmer's Tutorial for Python 2.6
http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6

And kids like youtube.
http://www.youtube.com/watch?v=4Mf0h3HphEA&feature=channel
http://www.youtube.com/watch?v=RHvhfjVpSdE
http://www.youtube.com/watch?v=0xgn-HKzZes&feature=related

snippsat 661 Master Poster

http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
http://stackoverflow.com/questions/81584

Pyscripter as postet over is good,but work only for windows.
Spe is good editor,work linux,mac osx.

Pydev for Eclipse are the many that like.

I use komodo ide and pyscripter windows.
Komodo ide and spe linux.

I fast way to test out editor is portablepython comes with pyscripter and spe.
Just unpack to hdd and all work,has a lot 3 party module installed to,wxpyhon,pygame......
http://www.portablepython.com/

snippsat 661 Master Poster

Yes off course,i did the same in my code if look at my post.

If it`s a number python will output as 0.something

If you make it a integer/float then the "0. " is there.
That why i said if 0 shall be removed make it a string.

snippsat 661 Master Poster

How about this.

#Python 3
try:
    input_num = float(input('test: '))
except ValueError:
    print ('Not an integer')

print (input_num)
snippsat 661 Master Poster

It still still a string tonyjv.
Use this to check type(a)

Just a and enter.
'.345'

If he shall use it to calulate,he need it to make it a float.
a + a
'.345.345'

snippsat 661 Master Poster

If it`s a number python will output as 0.something
You can remove 0 by make it a string.

>>> n = 0.7893948
>>> print n
0.7893948
>>> n = str(n)
>>> n
'0.7893948'
>>> n = n.replace('0', '')
>>> n
'.7893948'
>>> #if we make it an integer(float) again,it will output the 0
... 
>>> n = float(n)
>>> n
0.78939479999999995
>>> import re
>>> re.sub('^0+', '', '0.7893948')
'.7893948'
>>>

Maybe you have to think diffrent i dont think that 0 will be a problem.
Post you code if you dont get it to work,so can we look at it.

snippsat 661 Master Poster

When it come to web pages([X]HTML)
Then regular expression may not be the right tool to use.
Read bobince famous answer at stackoverflow.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

For small steady web pages regular expression can work ok.
Python has some really good tool for this like BeautifulSoup,lxml.

For a small wiki pages the solution post here by d5e5 and tonyjv can work fine.
Just to show one in BeautifulSoup.

import BeautifulSoup as bs

html = '''\
==Heading1==
<test>
some text here
</test>

==Heading2==
<test>
even more text
</test>
'''

soup = bs.BeautifulSoup(html)
divs = soup.findAll('test')
children = divs[0].contents
my_data = divs[0].string + divs[1].string
print my_data  #some text here even more text

BeautifulSoup can handle almost any web page even it has a lot of bad html.

You didn't write that awful page. You're just trying to get some data out of it. Right now, you don't really care what HTML is supposed to look like.

Neither does BeautifulSoup paser .

snippsat 661 Master Poster

This will match,0.00 can be any decimal number.

'Failed \d.{3,3}/\d.{3,3}.\d.{0,0}'
import re
txt = "Failed 9.45/100.00"

if re.match(r'Failed \d.{3,3}/\d.{3,3}.\d.{0,0}', txt):
    print 'Match'
else:
    print 'Match attempt failed'
import re

text = '''\
A fast and friendly dog.
'14257\'//745545*+*-/`'
mytest@online.no
My car is "red."
"Failed 9.99/100.00"
"Hei, this is a \"string\" with data!"
"0.99 100.0 Failed"
"han445@net.com"
'''

comp = re.compile(r'Failed \d.{3,3}/\d.{3,3}.\d.{0,0}')
test_match = comp.findall(text)
print 'Match is %s' % (test_match)  # Match is ['Failed 9.99/100.00']
snippsat 661 Master Poster

I encourage a two-spaced indent.

No and no no.

Python programmers should read Pep 8 and try to follow advice that is given there.
Use 4 spaces per indentation level.

snippsat 661 Master Poster

Not needed to write long if/elif/else lopp,for something simple as this.

Question = raw_input("Do you wish to play the Guess a Number Game? [Y/n]: ")
if Question.lower() not in ['y', 'n']:
   print "Not a valid option"
else:
    print 'Do something'
snippsat 661 Master Poster

Is there a way to filter out lines based on the fact that there are 5 integers separated by ' '

Yes you can look into regular expression. ^'\d{5}' a regular expression like this will match.
'12345' and not 12345 | '1234' | '12345 | 'a2345'

snippsat 661 Master Poster

If it faster i dont know,have to measure.
For this i think both solution will work fine.

Postet more as an alternative to your soultion,an show that module fileinput can be used for this.

snippsat 661 Master Poster

You can use module fileinput for this.

import fileinput

for line in fileinput.input("node.txt", inplace=1):
    line = line.strip()
    if not '1 87'in line:
        print line

'''Out--> to node.txt
Node 0 sends packet to 1
Node 0 sends packet to 3
Node 0 sends packet to 5
'''
snippsat 661 Master Poster

You can use cgi module,work in way same as php.
The other way is as postet over use to use web framework.

To test cgi you have to run a webserver like xampp.
To set up xampp look here.
http://jerryoem.spaces.live.com/Blog/cns!4032172F84519E20!342.entry
Then you can run python script in browser.

This will print hello world in your browser.

#!C:/python26/python.exe 
print "Content-type: text/html\n\n"

print('''\
<html>
<head>
<title>Hello</title>
</head>
<body>
Hello world!
</body>
</html>
''')

Links for cgi.
http://www.tutorialspoint.com/python/python_cgi_programming.htm
http://webpython.codepoint.net/cgi_tutorial

snippsat 661 Master Poster
snippsat 661 Master Poster
#It is a good thing that pyton 3 only has input not raw_input and input as python 2
#Let look a little at it
#I do not use python 3,i wait for 3 party module to be portet to python 3

>>> choice = input('Choose your option: ')
Choose your option: 5
>>> choice
'5'
>>> type(choice)
<class 'str'>
>>> choice + choice
'55'
>>> int(choice) + int(choice)
10

>>> #We can make user input return a interger
>>> choice = int(input('Choose your option: '))
Choose your option: 5
>>> choice + choice
10
>>> type(choice)
<class 'int'>
>>>
snippsat 661 Master Poster

One more way.

while True:
    try:
        wd = int(input('How wide would you like your letter to be? (5-20)' + ': '))
        if wd <=20 and wd >= 5:
            print ('You have answered: %s' % wd)
            break
        else:
             print('please enter a value between(5-20)')
    except (ValueError,NameError,SyntaxError):
        print ("Oops! That was no valid number. Try again...")
snippsat 661 Master Poster

Input in python 3 return datatype string(same as raw_input in python 2.x)

Change to datatype you need when you calculate.

print(add1, "+", add2, "=", int(add1) + int(add2))
print(div1, "/", div2, "=", float(div1) / float(div2))