0

So I tried same method in 2 scripts, but for some reason the last one doesn't work while the first code works just fine.

def convert(str):
    str = int(str)

values0 = 123
values1 = 1

try:
    convert(values0) and convert(values1)
    pass
except ValueError:
    sg.PopupError('Only numbers accepted.')
#Now if I try to multiply those values
print(values0 * values1)
#Works!

But here for some unknown for me reason it doesn't.

#But for some reason this doesn't work in my homework: Maybe because of PySimpleGUI?
import PySimpleGUI as sg
import math


layout = [
    [sg.Text('Enter how many hours you want to work: ')], [sg.InputText('')],
           [sg.Text('Enter how many pay you want per hour: ')], [sg.InputText('')],
        [sg.Button('Calculate Pay')], [sg.Cancel()] ]

window = sg.Window('Pay', layout)

def convert(str):
    str = int(str)



while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel':  
        break
    if event == 'Calculate Pay':
        try:
            convert(values[0]) and convert(values[1])  # I convert here
            break
        except ValueError:
            sg.PopupError('Only numbers accepted.')


sg.Popup('Your pay is: ', values[0] * values[1])     # But this doesn't work
window.close()

Sorry, if it was a stupid question, I am a total beginner and have no expereince in coding whatsoever.

dumbcoder
  • 13
  • 1
  • 1
    Hi, so what is the error? – drops Aug 25 '20 at 08:33
  • @drops TypeError: can't multiply sequence by non-int of type 'str' – dumbcoder Aug 25 '20 at 08:35
  • Your `convert` function doesn't do what you think. It's assigning something to a **local variable**, which has no effect outside the function (unless `int(str)` raises an exception). – khelwood Aug 25 '20 at 08:35
  • Get rid of `convert` and just write `values[0] = int(values[0])` etc. – khelwood Aug 25 '20 at 08:36
  • The previous comments have shown how to solve the issue. I want to explain what's the difference: in the first code, `print(values0 * values1)` multiplies two _integers_. If you'd use strings `values0 = '123'` and `values1 = '1'`, it wouldn't work either. In the second code, `values[0]` and `values[1]` are strings. If (in a more complicated case) you'd like to use a function like `convert`, you'd need to return a value, e.g., `return(int(s))`. Last but not least, it's better not to use `str` as a variable name because it's a [built-in name](https://docs.python.org/3/library/stdtypes.html#str). – Lenka Čížková Mar 21 '21 at 22:02

1 Answers1

0
def convert(str):
    str = int(str)

Your convert function doesn't do what you think. It's assigning something to a local variable, which has no effect outside the function (unless int(str) raises an exception).

Get rid of convert and just write out

values[0] = int(values[0])

etc.

khelwood
  • 55,782
  • 14
  • 81
  • 108