def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
command = input("Enter a command: ")
while command == 'squares' :
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
print('Sum = ', sq_sum)
I want to know how to print out a summation line (Ex: Sum = 2**2 + 3**2 + 4**2 + 5**2 = 54). My code only prints out Sum = 54.
You can use for loop to generate strings "number**2" and keep on list, and later you can use ' + '.join(list) to concatename this strings
def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
terms = []
for number in range(a, a+b):
terms.append("{}**2".format(number))
terms = ' + '.join(terms)
print(terms, '=', sq_sum)
EDIT: or shorter:
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = sum(i**2 for i in range(a, a+b))
terms = ' + '.join("{}**2".format(i) for i in range(a, a+b))
print(terms, '=', sq_sum)
You can change your squares() to return a string as well.
def squares(start, num):
s_sum = 0
output = ""
for i in range(num):
s_sum += start**2
output += '{}**2+'.format(start)
start += 1
return s_sum, output[:-1]
Related
I need my program to generate as many playing fields as the entered number of players playing the game. Currently it only generates 1 field. Cant wrap my head around this one.
s = int(input("Sisesta mängijate arv: "))
b = int(input("Sisesta väjaku suurus: "))
b = b + 1
bb = b
c = int(input("Sisesta korrutustabeli suurus: "))
for s in range (1 , s+1):
numberolemas = ['0']
t.write(str(s) + ". väljak \n\n")
print(str(s) + ". väljak \n")
for bb in range (1 , bb):
for b in range (1 , b):
import random
number = random.randint(1, c) * random.randint(1, c)
olemas = True
while olemas:
number = random.randint(1, c) * random.randint(1, c)
if number not in numberolemas:
olemas = False
t.write(str(number))
print(str(number), end = ' ')
if number <= 9:
t.write(" ")
print(" ", end = '')
elif number >= 100:
t.write(" ")
print(" ", end = '')
else: t.write(" ") and print(" ", end = '')
numberolemas.append(number)
b = b + 1
t.write("\n\n")
print(" ")
bb = bb + 1
print(" ")
t.close() ```
Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")
I want a program so I can enter a big integer and it will do a calculation like this:
62439 = (6 - 2 + 4 - 3 + 9)
Basically it splits them up and the first and third should be added and the second and the fourth should be subtracted. Please follow the loop sort of method. I can't have the elif and if working in the same run of the loop.
num = input("Input any number: ")
total = 0
p = 0
x= 0
q = 0
number = len(num)
if len(num) ==5 :
total = 0
for i in range(0,(number)):
p = p+2
q = q +1
if x == 2 and q == p:
total = total+(int(num[q]))
x=1
p=p-1
elif x == 1 and q == p :
total = total-(int(num[q]))
x=2
p=p-1
print("your number is: ",total)
I expect it to repeat the loop as many times as there are numbers in the integer that is entered e.g (333) executes 3 times
num = input("Enter a number: ")
sum = 0
do_add = True
try:
for digit in num:
if do_add:
sum += int(digit)
else:
sum -= int(digit)
do_add = not do_add
except Exception:
print("Invalid input")
else:
print("The result is", sum)
Why not just perform the calculation:
num = input("Input any number: ")
if len(num) == 5:
total = int(num[0])-int(num[1])+int(num[2])-int(num[3])+int(num[4])
print("your number is: ",total)
Maybe like this:
def main():
digits = input("Enter a number: ")
assert digits.isdigit()
result = sum(int(digit) * [1, -1][index%2] for index, digit in enumerate(digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or like this if you wanna be more deliberate - also easier to extend:
def main():
from operator import add, sub
digits = input("Enter a number: ")
assert digits.isdigit()
operations = [add, sub]
result = 0
for index, digit in enumerate(digits):
result = operations[index%len(operations)](result, int(digit))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or just go overkill (also known as "taking advantage of the standard library"):
def main():
from itertools import cycle
from operator import add, sub
from functools import reduce
while True:
digits = input("Enter a number: ")
if digits.isdigit():
break
operation_iter = cycle([sub, add])
def operation(a, b):
return next(operation_iter)(a, b)
result = reduce(operation, map(int, digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()
def makeArray(a):
a = []
for i in range(n):
a.append(i)
return a
print makeArray(a)
import random
def shuffleArray(a):
size = len(a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
print shuffleArray(makeArray(a))
if __name__ == '__main__':
a = raw_input("please enter size of array: ")
print ("you entered " + a)
makeArray(a)
shuffleArray(a)
how do I make this piece of code ask for input via terminal and take that input through both of the functions then returning a result? I'm asking the user for input storing that input in a variable printing the result and then shuffling by randominzing.
def makeArray(n):
a = [] #you were using 'a' for the size and the array itself at the same time
for i in range(n):
a.append(i)
return a
import random
def shuffleArray(a):
size = len (a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
if __name__ == '__main__':
n = int(raw_input("please enter size of array: ")) #'n' needs to be an integer because it's the size of the array
print ("you entered " + str(n))
anArray = makeArray(n)
print shuffleArray(anArray)
you can also replace:
def makeArray(n):
a = []
for i in range(n):
a.append(i)
return a
with:
def makeArray(n):
a = list(range(n))
return a