Jump to content

Ok, so i just started to learn how to write in python and i wanted to make a program that would 

give me the sum off all the values in a range, what i mean is i wanna be able to put in 2 number and 

want to find the sum of all the number between those 2 numbers 

 

Thank you 

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/
Share on other sites

Link to post
Share on other sites

int valuefor x in range(a, b)    value+=xprint value

pretty close to that, some of the syntax will be different, but you can figure it out yourself

you wont learn anything by just asking people to do the work for you

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6100805
Share on other sites

Link to post
Share on other sites

Ok, so i just started to learn how to write in python and i wanted to make a program that would 

give me the sum off all the values in a range, what i mean is i wanna be able to put in 2 number and 

want to find the sum of all the number between those 2 numbers 

 

Thank you 

 

Enderman is right, but here's their code in proper Python (rather than a more general form).  For the sum of all (intger) values between the intgers a and b:

x = 0for i in range(a, b+1):    x += iprint(x)

A much more compact way:

x = sum(range(a, b+1))print(x)

The first one is a bit more transparent--you start at the value a, and add it to the variable x.  Then you move to a+1, and add that to the value in x.  Rinse and repeat.  You need to have b+1 as the upper bound, rather than b, since Python excludes the upper bound from the list--range(1,5) contains the values 1, 2, 3, and 4, but not 5.

 

The second one creates the iterable object range(a, b+1), then the sum() function moves through each value in the iterable and adds them together.  Then it returns the value, so you can assign it to a variable or use it to do math with or whatever.

 

Also, I'm going to second Enderman's comment about asking other people to write things for you.  It won't help you learn Python.  If you're just starting out, Codeacademy or Lear Python the Hard Way are great resources, and if you google your question, you'll almost invariably find that it's already been asked and answered on Stack Exchange (it seems that every possible thing that could ever be asked has been on that site).  And, the Python documentation is generally very good if something isn't making sense to you.

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6101889
Share on other sites

Link to post
Share on other sites

Thank you all for your responses and feedback, 

 

The program is actually meant to give the sum of all values that are between 2 values that have a base of 2 

 

example:

 

2^4 to  2^8 ----------> (2^4) + (2^5) + (2^6) + (2^7) + (2^8) 

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6102412
Share on other sites

Link to post
Share on other sites

Oh, so, summing powers of two, if I understand you correctly?  Then something like this would be quick (might not be the most efficient, especially for large exponents, but it's quick and easy to understand):

x = 0# a, b are the exponent values on 2 (i.e., 2**a and 2**b are your bounds)for i in range(a, b+1):    x += 2**iprint(x)

Python uses a double-asterisk to denote exponents (carats don't work--writing out 2^i will do something totally different).

 

If you want to input our values as the numbers themselves, rather than the exponents, you can stick this up at the top, assuming you already defined a and b somewhere.  Or just replace the a and b inside the math.log() function manually if this can be hard coded.

import matha = math.floor(math.log(a, 2))b = math.floor(math.log(b, 2))

This takes the base-2 logarithm to get the nearest power of two, then rounds down to the nearest integer, so starting with a value of 5 will spit out 2 (since 2**2 = 4, and 4 is the largest power of two that's smaller than 5).  Change math.floor() to math.ceiling() to get the next largest one (putting in 5 spits out 3, since 8 is the next largest power of 2).  But, if you're working in numbers that are already powers of 2, this isn't an issue.

 

If you're trying to work in binary by any chance (talking about powers of 2 --> possibly doing stuff in binary), Python can automatically convert for you.  Use bin(x) to convert to the binary representation of x, and prefix a number with "0b" to tell Python that it's a binary representation.  So, 0b100 = 4, written in binary, and bin(4) will return 0b100.

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6102622
Share on other sites

Link to post
Share on other sites

Yes i had already defined a and b earlier, so i just put that in, in place of a and b.

 

Im actually using python 3.5, and what if i wanted to sum all the values between 2 powers of 2 soo like: 

 

2^4 -------> 2^7 

 

2^4= 16 

2^7=128 

 

16+17+18+20+21............+125+126+127+128 

 

because this is what i was trying to do earlier

 

i can post the code i have so far if you would like to see it 

 

another question i had was what if i wanted the powers to be negative, would i have to change anything in the code. 

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6106760
Share on other sites

Link to post
Share on other sites

In that case, just don't use the math.log() function at all.  Just have a = 2**4, b = 2**7, and you can use the sum(range(a, b+1)) method.  Or use Fizzlesticks' equation if you're going to be adding up a lot of numbers--it'll make the calculation go a lot faster if you have a lot of things to sum up.

 

It would probably help if you posted the code you're working on.  Then we can give you more specific tips/pointers.

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6106886
Share on other sites

Link to post
Share on other sites

i tried the equation before but it wouldn't work for me so i tried using your method and it worked fine maybe i did something wrong before anyway, 

 

I've figured out a way to get the sum of something like this 2^4 to  2^8 ----------> (2^4) + (2^5) + (2^6) + (2^7) + (2^8) thanks to your help earlier

 

But ive tried to also do this

 

 2^4 -------> 2^7 

 

2^4= 16 

2^7=128 

 

16+17+18+20+21............+125+126+127+128

 

i have coded for this and it seems to work, if u could just have a look over the whole thing and just give some pointers and feedback would be greatly appreciated

Thank you

 

here is the code:    

 

print('Before you begin i would like to expalin what this program is meant to do')

print (' ')
print('The program will first ask you to enter a positve whole number, once you"ve done that the program will then rais 2 to that number, you will do this twice meaning in the end you wil have something like this: (2^x) and (2^y).')
print (' ')
print('then the program will take these numbers and sum them, so you will get the sum of (2^x) and (2^y).')
print (' ')
print('and lastly the program will give you the sum of all the values to the powers of 2 between your given values.')
print (' ')
print('example:')
print (' ')
print('2^4 and 2^8 ----------> (2^4) + (2^5) + (2^6) + (2^7) + (2^8).') 
print (' ')
 
 
 
 
 
 
print ('Please enter a whole interger that you would like to be "x" in ----> (2^x), also make sure that your "x" value is greater than 1.')
    
 
 
value1=int(input('value1: '))
 
print ('2^',int(value1))
print ('=')
 
print (2**int(value1))
 
  
 
print ('Thank you, now enter your second value = y -----> (2^y).')
 
value2=int(input('value2:'))
 
 
print ('2^',int(value2))
print ('=')
 
 
 
 
 
print (2**int(value2))
 
 
value3=(2**int(value1))
 
value4=(2**int(value2))
 
print (' ')
 
 
print('The Sum of 2^',int(value1))
 
print('and 2^',int(value2))
 
print('is')
 
 
print (value3 + value4)
 
print (' ')
 
print('and now the sum of all values from 2^',int(value1))
 
print('to 2^',int(value2))
 
print('is')
 
 
x = 0
 
for i in range((int(value1)), ((int(value2))+1)):
    x += 2**i
print(x)
 
print (sum(range(int(value1)), ((int(value2))+1)))
 
 
 
print (' ')
 
 
print('Press enter to continue')
 
print (' ') 
                                                                                                                                            
input(' ') 
Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6107045
Share on other sites

Link to post
Share on other sites


print('Before you begin i would like to expalin what this program is meant to do')

print (' ')

print('The program will first ask you to enter a positve whole number, once you"ve done that the program will then rais 2 to that number, you will do this twice meaning in the end you wil have something like this: (2^x) and (2^y).')

print (' ')

print('then the program will take these numbers and sum them, so you will get the sum of (2^x) and (2^y).')

print (' ')

print('and lastly the program will give you the sum of all the values to the powers of 2 between your given values.')

print (' ')

print('example:')

print (' ')

print('2^4 and 2^8 ----------> (2^4) + (2^5) + (2^6) + (2^7) + (2^8).')

print (' ')

print ('Please enter a whole interger that you would like to be "x" in ----> (2^x), also make sure that your "x" value is greater than 1.')

value1=int(input('value1: '))

print ('2^',int(value1))

print ('=')

print (2**int(value1))

print ('Thank you, now enter your second value = y -----> (2^y).')

value2=int(input('value2:'))

print ('2^',int(value2))

print ('=')

print (2**int(value2))

value3=(2**int(value1))

value4=(2**int(value2))

print (' ')

print('The Sum of 2^',int(value1))

print('and 2^',int(value2))

print('is')

print (value3 + value4)

print (' ')

print('and now the sum of all values from 2^',int(value1))

print('to 2^',int(value2))

print('is')

x = 0

# a, b are the exponent values on 2 (i.e., 2**a and 2**b are your bounds)

for i in range((int(value1)), ((int(value2))+1)):

x += 2**i

print(x)

print (sum(range(int(value1)), ((int(value2))+1)))

print (' ')

print('Press enter to continue')

print (' ')

input(' ')

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6107261
Share on other sites

Link to post
Share on other sites

Okay, a few things: you should look into using print string formatting, because it will make some of your print statements a LOT less messy.  You can use the percent symbol (%) followed by one of a few special character inside of your print statement, then after you close the quote marks, specify a formatting string.  I've used %i a lot, which specifies that the thing needs to be printed as an integer.  The syntax is print("Stuff %i, %i, %i" %(first_i, second_i, third_i_)).  Using this means you don't have to break everything up into different print statements.  Even if you don't want to use string formts, you can print multiple statements in a row in Python:

print('Foo has a value of ', foo, 'which is greater than bar, whose value is ',bar)

You should also go read up on escaping characters.  Putting a blackslash (\) before a character specifies that it's a literal character or a special character.  So if you want to have an apostrophe inside your single quotes, like in your second print statement with "you've", you can type a backslash before the apostrophe and Python won't read it as the end of the string, but treats it like a literal ' character..

print('...and once you\'ve done that...')

You can also avoid needing all the print(' ') lines by using a newline character (\n), which tells Python to move the text after it to a new line in the output.

 

You also ought to read up briefly on some good program formatting practices.  You have a lot of unnecessary blank lines; try to keep those to a minimum.  You can use them when you need to set some code off from some other code, but it should only be done when it will make reading the program easier for someone else.  You also have some of your print statements stretching out into very, very long lines, which is bad practice since it makes it very hard to read.  You can split your print statements up over multiple lines to keep the user from having to scroll over a lot, like so (both print statements will give you identical output):

print('You should try to keep the length of your lines to a minimum.  Long lines can make your program very hard to read.')print('You should try to keep the length of your lines to a mininum. '      'Lone lines can make your programs very hard to read.')

Just close the string at some arbitrary point, hit enter to start a new line, and then type the rest of the string in quotes again.

 

There's a long style guide called PEP8 that's what almost everyone uses to properly format their code.  Some programs, like PyCharm, will let you type your code in and then automatically format it to conform to PEP8.  PyCharm will automatically deal with lines that get too long, for instance, and it's a program I'd recommend for just generally writing Python code.  It has a terrifying number of options and can be a bit of a hassle to change all the settings to do what you want it to, but it can automatically deal with code formatting, you can run your code right there in the program, and I've generally been very happy with it once I got past the trouble of getting all the settings to be what I wanted them to be.

 

Okay, as for your actual code itself: aside from the formatting, I only see a few problems.  First: you already specified that value1 and value 2 are integers when you defined them with int(input()).  You don't need to keep calling them as "int(value1)" every time you use them--Python already has them stored as integers, so you can juse call "value1" and it will already be an integer.  So I took out all the unnecessary int() functions.  Second: when you're doing the sum of all values between 2^value1 and 2^value2, you were actually summing between value1 and value2.  I changed it so your output now does the following:

  1. Tells the user it's about to print the sum of all powers of two between 2^value1 and 2^value2.  So if the user puts in 3 and 8, it will add 2^3 + 2^4 + 2^5 + 2^6 + 2^7 + 2^8.
  2. Sums the powers of two and prints the result on a new line.
  3. Tells the user it's about to add all integer values between 2^value1 and 2^value 2.  So if the users puts in 3 and 8, it will sum up 8+9+10+...+254+255+256.
  4. Sums those values and prints the result on a new line.

I also cleaned up your formatting to make the code easier to read and more in line with some of the Python standard formatting practices, and added a note specifying that the second user-entered value needs to be larger than the first (or some weird things will happen with the range() function).  Here's the cleaned up and slightly tweaked version:

print('Before you begin i would like to expalin what this program is meant '      'to do.\n')print('The program will first ask you to enter a positve whole number, '      'once you\'ve done that the program will then raise 2 to that number, '      'you will do this twice meaning in the end you wil have something like '      'this: (2^x) and (2^y).\n')print('Then the program will take these numbers and sum them, so you will '      'get the sum of (2^x) and (2^y).\n')print('And lastly the program will give you the sum of all the values to the '      'powers of 2 between your given values.\n')print('example:\n2^4 and 2^8 ----------> (2^4) + (2^5) + (2^6) + (2^7) + ('      '2^8).\n')print('Please enter a whole interger that you would like to be "x" in ----> '      '(2^x). Make sure that your "x" value is greater than 1.')value1 = int(input('value1: '))print('2^%i = %i' % (value1, 2 ** value1))print('Thank you, now enter your second value = y -----> (2^y).\n'      'y must be larger than x.')value2 = int(input('value2:'))print('2^%i = %i' % (value2, 2 ** value2))value3 = 2 ** value1value4 = 2 ** value2print('\nThe Sum of 2^%i and 2^%i is %i.' % (value1, value2, value3 + value4))print('And now the sum of all powers of two between 2^%i and 2^%i (inclusive) '      'is:' % (value1, value2))x = 0for i in range(value1, value2 + 1):    x += 2 ** iprint(x)print('And the sum of all values from 2^%i to 2^%i (inclusive) is:' % (value1,                                                                       value2))print(sum(range(value3, value4 + 1)))print('Press enter to continue')

Also, one thing I didn't change, but that didn't make much sense to me: when you prompt the user for the first input value, you say it needs to be greater than 1.  As far as the program actually running, it doesn't--you can input 1 or 0 and it works just fine for me, so long as the second number is larger.  It definitely breaks if you put in a negative number, though.  I don't know if this was just an oversight or if you're using this script in connection with something else, where the first exponent has to be greater than 1 due to some other concern.  I didn't change that line, just in case, but it did grab my attention.

 

Let me know if that code works alright. 

 

I'll go ahead and refer you to the Lear Python the Hard Way website, which is a pretty good (and totally free!) introductory course to Python, and should help you a lot if you're just starting out.  Search through there and through the Python documentation if anything just doesn't make sense to you--it's better to learn to read the documentation to sort things out, since Python's is usually very good compared to most other things I've run across, and once you learn enough of the terminology, it becomes pretty easy to read and understand.

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6108189
Share on other sites

Link to post
Share on other sites

Thank you so much for your help, and to get such great help i am truly thankful

 

and i will make sure to use all of your formatting tips, especially the one on the long lines of code and the \ one 

 

the reason i said to have values above 1 is because if the number is negative then it just breaks everything, but now i realize it just has to be above 0 in order to stay positive.

 

I will also be sure to check out all of those python website.

 

and i just ran the code and it works fine

 

Once again thanks for all your help 

Link to comment
https://linustechtips.com/topic/454735-python-35-program-help/#findComment-6109086
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×