Python Forum
Simple Code - What's going on inside it?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Code - What's going on inside it?
#1
Below is code from my class. When I run the code with several integers, it somehow stores them and returns them all when "else" is run. I suspect it is because of the empty "" values for the variables below. Is this correct? Also, I don't completely understand how this works below: num_final = num_temp + num_1; and num_temp=num_final; Is this telling the code-gremlin to store the values in memory until "else" is called?





num_1="" 
num_temp="" 
num_final="" 

while True:
    num_1 = input ("Enter and integer: ")
    if num_1.isdigit():
        num_final = num_temp + num_1
        num_temp=num_final
    else:
        print(num_final)
        break
 
Reply
#2
You get a long string of concatenated integers because of the line:
num_final = num_temp + num_1
Here you operate with strings, and + operator with strings means concatenation. You can play with that in Python console to see how it works. If code should be summing the integers instead, conversion from string to integer is required with int().

Quote:num_final = num_temp + num_1; and num_temp=num_final;
Without num_temp=num_final each loop would start with empty num_final string and all you would get in the end is the last number you enter. You can check the working easily by commenting out lines and printing values you want to observe.
Reply
#3
thank you. Will play with it also.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 288 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 470 Nov-07-2023, 04:32 PM
Last Post: snippsat
  help me simple code result min and max number abrahimusmaximus 2 900 Nov-12-2022, 07:52 AM
Last Post: buran
  Simple encoding code ebolisa 3 1,435 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,783 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Simple code question about lambda and tuples JasPyt 7 3,284 Oct-04-2021, 05:18 PM
Last Post: snippsat
  My simple code don't works !! Nabi666 1 1,596 Sep-06-2021, 12:10 PM
Last Post: jefsummers
Sad SyntaxError: from simple python example file from mind-monitor code (muse 2) warmcupoftea 4 2,800 Jul-16-2021, 02:51 PM
Last Post: warmcupoftea
  Plotting sum of data files using simple code Laplace12 3 3,031 Jun-16-2021, 02:06 PM
Last Post: BashBedlam
  Help with isinstance command (very simple code) Laplace12 2 1,994 Jul-30-2020, 05:26 AM
Last Post: Laplace12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020