Python Calculator with lists and loops [duplicate] - python

This question already has answers here:
for loop in python with decimal number as step [duplicate]
(2 answers)
Closed 1 year ago.
I am trying to create a calculator program that takes user input and stores it in a list and perform the calculation based on their selection. However, I keep running across an error for line 31 saying
TypeError: 'float' object cannot be interpreted as an integer.
Here is the code:
import math
def printIntro():
print("This is a simple calculator.")
print("Select an operation:\n1) Add\n2) Subtract\n3) Divide\n4) Multiply")
while True:
operator = input("Enter your choice of + - / *: \n")
if operator in('+', '-', '/', '*'):
#continue asking for numbers until user ends
#store numbers in an array
list = []
num = float(input("What are your numbers?: "))
for n in range(num):
numbers = float(input("What are your numbers?: "))
list.append(numbers)
if n == '':
break
if operator == '+':
print(add(list))
if operator == '-':
print(subtract(list))
if operator == '/':
print(divide(list))
if operator == '*':
print(multiply(list))
else:
break

Python's range method accepts an integer.
The error is due to the fact that you convert the input to float in num = float(..) before giving it to range(num).
I think in the line where you try to get the number from input causes it:
num = float(input("What are your numbers?: "))
It should work with (I also fixed the prompt message):
num = int(input("How many numbers you have?: "))

for n in range(int(num)): cast num as int inside the for loop such as this. There is a similar comment to this above but here is the fixed code.

Related

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,

I used while loop, until the random number that python throws matched the input, why it doesn't work? [duplicate]

This question already has answers here:
Why does assigning to my global variables not work in Python?
(6 answers)
Closed 2 years ago.
I let the user input a 3-digit number, and let python throw a random 3-digit number, try to see when the random number can match the input. However, everytime I run it on cmd, it prints 'Python is too tired', which is a statement I set to prevent it from looping infinitely (I really did so, until I added this limitation of attempt times).
import random
my_num = int(input('Type your 3-digit int number: '))
if my_num >= 100 and my_num < 1000:
attempt = 0
my_lottery = []
my_lottery.append(int(num) for num in str(my_num))
def lottery_throw():
lottery = []
i=0
while i<3:
lottery.append(random.randint(1,9))
i+=1
return(lottery)
def check():
global boo
lottery_throw()
if lottery == my_lottery:
boo = 'true'
else:
boo = 'false'
while attempt < 100000:
check()
attempt += 1
if boo == 'true':
print('you win')
print(attempt)
break
elif attempt >= 100000:
print('python is too tired')
break
else:
print('You must enter a 3-digit number.')
Run it on cmd, everytime I run it, it returns 'Python is too tired'
But the number of possible combinations (9C3) is only 84. It's very unlikely that python really didn't throw a correct number. How can I fix this problem?
Errors
Do not use global variables unless you really need them. As you can see, writting to a global variable doesn't work our of the box
012 is a valid 3 digit number
If you append a list to another list you will get a nested list (list inside another list): [[1, 2, 3]]
Why create a list of each digit when you can create the number itself?
for loops should be used for a fixed number of iterations, while loops when a more complex condition is needed to return from the loop.
return should be used without parenthesis as they are redundant (it is not a function)
True and False are booleans, do not use "true" and "false" (strings) to represent them.
if condition return true else return false (in pseudocode) is the same as return condition
for loops also can have an else clause, which only is executed if no break was found.
Solution
import random
my_num = int(input("Type your 3-digit int number: "))
if 0 <= my_num < 1000:
for attempt in range(1, 100001):
if my_num == random.randint(0, 999):
print(f"You win in {attempt} attempts.")
break
else:
print("Python is too tired.")
else:
print("You must enter a 3-digit number.")
I have no idea what you did, but I wasn't able to fix it.
Here is my version incited:
num = input('Type your 3-digit int number: ')
for i in range(100000):
if (("00"+str(random.randint(0,999)))[-3:]) == num:
print("You win on attempt %i"%i)
did_win = True
break
else:print('python is too tired')

Problem in a number guessing program's while loop [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I'm new to Yython programming. I create a simple program with random module, that ask for number, and person need to guess an number. I got problem with getting the answer. Even if I give the correct answer, program isn't stopping, here's the code:
import random
run = True
answer = random.randint(1,9)
guess = input("Give me an number in 1 to 9: ")
print(answer)
while run:
if guess == answer:
print("Congratulations, you won!\n" * 5)
run = False
else:
guess = input("Try again: ")
print(answer)
The print(answer) line is for me to know what is the answer, and even if I write it down, program isn't stopping.
answer is always an integer:
answer = random.randint(1,9)
and guess is always a string:
guess = input("Give me an number in 1 to 9: ")
thus they can never be equal.
You need to conver the inputted string to an integer:
guess = int(input("Give me an number in 1 to 9: "))
Or better yet, convert the generated random number to a string, to avoid the issue of the program crashing when the user inputs a non digit:
answer = str(random.randint(1,9))
The random function will return an integer and the input function will return a string in python, "1" is not equal to 1. To be able to check if the input is the same, convert the random number to a string by doing guess == str(answer) instead

Why does this loop have only one iteration instead of the number of iterations entered by the user? [duplicate]

This question already has answers here:
Python: raw_input and unsupported operand type(s)
(3 answers)
Closed 7 years ago.
I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.
However, when I enter any number, it asks to enter name only one time and shows the output in list:
def main():
# a = 4
a = input("Enter number of players: ")
tmplist = []
i = 1
for i in a:
pl = input("Enter name: " )
tmplist.append(pl)
print(tmplist)
if __name__== "__main__":
main()
output:
Enter number of players: 5
Enter name: Tess
['Tess']
The for loop should run 5 times and user entered 5 values get stored in a list.
You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -
def main():
num=int(input("Enter number of players: "))
tmplist=[]
for _ in range(num):
pl=input("Enter name: " )
tmplist.append(pl)
print(tmplist)
Since you are using Python3
a=input("Enter number of players: ")
means a is a string "5". Since this is only one character long - the loop will run just once
You need to use
a = int(input("Enter number of players: "))
You'll also need to change the loop
for i in range(a):
I recommend using more meaningful variable names - especially if this is homework
def main():
number_of_players = int(input("Enter number of players: "))
player_list = []
for i in range(number_of_players):
player = input("Enter name: " )
player_list.append(player)
print(player_listlist)
if __name__== "__main__":
main()
You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it's '5', resulted in one iteration, because there's only one character in '5'.
First you have to change it into a number, with a = int(a).
With a as a number, you still can't loop through that, because a number isn't an iterable.
So then you should create a range object to loop over, with for i in range(a):.
Then you will be able to carry out your operations as expected.
Since the input a is a string
you need to convert it to a number and then use a different for.
it should be
def main():
#a=4
a=int(input("Enter number of players: "))
tmplist=[]
i=0
while i < a:
pl=input("Enter name: ")
tmplist.append(pl)
i+=1
print(tmplist)
main()

Python Basic Input Confusion

So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.
Example Inputs:
23 45
or
23
45
Each number should go to its own variable.
Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.
Here is what Im working with, but obviously this version takes the numbers one on each line.
def main():
num1 = int(input())
num2 = int(input())
numSum = num1 + num2
numProduct = num1 * num2
print("sum = ",numSum)
print("product = ",numProduct)
main()
the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:
inputs = input("Enter something").split() # read input and split it
print inputs
applying to your code, it would look like this:
# helper function to keep the code DRY
def get_numbers(message):
try:
# this is called list comprehension
return [int(x) for x in input(message).split()]
except:
# input can produce errors such as casting non-ints
print("Error while reading numbers")
return []
def main():
# 1: create the list - wait for at least two numbers
nums = []
while len(nums) < 2:
nums.extend(get_numbers("Enter numbers please: "))
# only keep two first numbers, this is called slicing
nums = nums[:2]
# summarize using the built-in standard 'sum' function
numSum = sum(nums)
numProduct = nums[0] * nums[1]
print("sum = ",numSum)
print("product = ",numProduct)
main()
Notes on what's used here:
You can use list comprehension to construct lists from iterable objects.
You can use sum from the standard library functions to summarize lists.
You can slice lists if you only want a part of the list.
Here I have modified your code.
def main():
num1 = int(input("Enter first number : "))
num2 = int(input("\nEnter second number : "))
if(num1<=0 or num2<=0):
print("Enter valid number")
else:
numSum = num1 + num2
numProduct = num1 * num2
print("sum of the given numbers is = ",numSum)
print("product of the given numbers is = ",numProduct)
main()
If you enter invalid number it prints message Enter valid number.

Categories

Resources