Python multiplication function not working - python-3.x

I am a beginner to python wanted to make a simple calculator app which takes multiple inputs for the case of operators 'Add' and 'Multiply'. I was having a problem with the operator 'Multiply where wrong outputs are being diplayed. So can any one help me with the syntax. I would also be thankful if you help me improve the other parts of the code.
print("Type Add to add the numbers")
print("Type Subtract to subtract the numbers")
print("Type Multiply to multiply the numbers")
print("Type Divide to divide the numbers")
Operator = input()
if Operator == "Add":
print("Type the number of numbers you want to add" )
Num_Numbers = range(0,int(input()))
Total = 0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
Count = int(input())
Total = Total + Count
print(Total)
elif Operator == "Subtract":
print("Type the first number")
Num1 = float(input())
print("Type the second number")
Num2 = float(input())
print(Num1 - Num2)
elif Operator == "Multiply":
print("Type the number of numbers you want to multiply" )
Num_Numbers = range(0,int(input()))
Total = 0
Counter = 0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
count = int(input())
if Counter != 0:
Counter = Counter + 1
while Total == 0:
Total = Total + count
print("Code implemented")
else:
continue
Total = Total * count
print(Total)
elif Operator == "Divide":
try:
print("Type the first number")
Num1 = float(input())
print("Type the second number")
Num2 = float(input())
print(Num1 / Num2)
except ZeroDivisionError:
print("Division by zero not possible")
else:
print("Operator Unidentified!")

elif Operator == "Multiply":
print("Type the number of numbers you want to multiply" )
Num_Numbers = range(0,int(input()))
Total = 1.0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
count = float(input()) #chances are the number can be float
Total = Total * count
print(Total)
Just simplified your code!

You put the start Total as 0. 0 multiplied by anything is 0, so you should start at 1:
Total = 1
It's more math than programming.
You also need to remove the strange lines (what are they for?!) shown below:
Counter = 0
#some needed lines
if Counter != 0:
Counter = Counter + 1
while Total == 0:
Total = Total + count
print("Code implemented")
else:
continue
Note for the future that:
var=var+1
Is quicker written as:
var+=1
And the same for other operators, and:
else:
continue
Is obsolete, you don't need a else statement for every if.

Related

Python multiply game. My script needs to have a arbitrarily number of players that each have to take turn in answering a multiplication question

Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break

Find average of given numbers in input

I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")

Excluding 0's from calculations

Hi I have been asked to write a program that will keep asking the user for numbers. The average should be given to 2 decimal places and if a 0 is entered it shouldnt be included in the calculation of the average.
so far I have this:
data = input()
numbers = []
while True:
data = input()
if data == "":
break
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))
Dumb question but how do you ensure the 0's arent considered in the calculation?
Correction: you are not appending the first input to the list
Modification: added an if statement to check whether the input is '0'
data = input()
numbers = []
numbers.append(float(data))
while True:
data = input()
if data == "":
break
if data == '0':
continue
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))

Novice Coder with issue properly looping

So I'm a novice coder having never coded before and am teaching myself Python on the guidance of my CS instructor. I'm walking myself through "Automating the Boring Stuff with Python" and I'm having issues with the Collatz sequence portion at the end of Chapter 3. I've got the sequence down but I'm having issues properly looping the code in order to get the result I want which is looping the sequence until the answer is == to integer 1. This is what I have and I would love some feedback and assistance.
def collatz(number): #defines the collatz sequence
if number%2 == 0:
num1 = number//2
else:
num1 = 3 * (number + 1)
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
num2 = collatz(num3)
if num2 == 1:
break
else:
num3 = collatz(num2)
print("ta da!")
You need this code:
def collatz(number):
if number % 2 == 0:
num1 = number//2
else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
num = collatz(num)
print(num)
if num == 1: break
print("ta da!"); input()

My program is not recognizing its using a negative number

I just started programming for school and this assignment requires me to enter a number and then use it to count from 0 up to the number, then choose a math operation, and then use that math operation.
The problem occurs when I enter a negative number, it gives me the correct message "Too small - Try again: " . but once I enter a positive number it still assigns my original negative number to the program.
Here is my noobie code:
num1 = int(input("\nEnter a number 1 or greater:\t"))
counting = num1 + 1
def count():
print("Counting from 0 to", num1,":")
for i in range(0,counting):
print(i, end = ' ')
math_op()
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
count()
def math_op():
ops = input("\n\nChoose math operation (+, -, *)")
if ops in ('+'):
print("Table for",num1,"using +:")
for i in range(1,11):
print(num1 ,'+', i ,'=', num1 + i)
if ops in ('-'):
print("Table for",num1,"using -:")
for i in range(1,11):
print(num1 ,'-', i ,'=', num1 - i)
if ops in ('*'):
print("Table for",num1,"using *:")
for i in range(1,11):
print(num1 ,'*', i ,'=', num1 * i)
if num1 <= 0:
reset()
else:
count()
Yes, you're missing a while loop:
num1 = -1
while num1 < 1:
num1 = int(input("\nEnter a number 1 or greater:\t"))
# remaining code after here
you never set the number to count when the correction is positive:
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
counting = num1 + 1
count()

Resources