how to get out from loop with a single word - python

I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)

Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)

Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).

Related

How to use a for-loop/range to end a specific character input in Python?

If user entered anything other than an integer it should be ignored, whereas, if it were to be an integer it should be added to the lst (list)
the function should display the list of integers, ignoring anything that wasn't an integer and display the max and min number.
lst = []
n = int(input("Enter Integers: "))
for index in range(min(n), max(n)):
if index == ' ':
return
for i in range(min(n),max(n)):
elements = int(input())
lst.append(elements)
print(lst)
print(len(lst))
for num in lst:
if num % 2 == 0:
print(num, end= ' ')
I have a function here that prompts users to enter a list of integers, if SPACE is inputted: it should END the input.
I'm quite new at python and not sure how to go about this code.
The expression
input("Enter Integers: ")
evaluates to a string. Since you want to read strings until a space is inserted, you need a infinite loop:
numbers = []
while True:
value = input("Enter an integer: ")
If the user provides a space, stop reading numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
# Exit the loop
break
If you want to convert it to an integer, use the int function and append it to numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
numbers.append(int(value))
You can also add a validation, if the user provides a value that isn't a number:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
try:
number = int(value)
except ValueError:
print('The value is not a number!')
# Continue looping
continue
numbers.append(number)
Your code there is somewhat misleading and adds confusion to the question. My solution below is based off the question before the code.
lst = []
print("Enter Integers:")
while True:
n = input()
try:
# Try converting to an int, if can't ignore it
lst.append(int(n))
except ValueError:
pass
# If space input, break the loop
if n == ' ':
break
print("Integer list: ")
print(lst)
if len(lst) > 0:
print("Min: " + str(min(lst)))
print("Max: " + str(max(lst)))

Getting Attribute Error using is.integer() on user input for multiplication table

I am new to programming and I've been trying to run through a few practice exercises with Python. I am trying to create a multiplication table where the user can pick a number and how many different multiples they wish to see. I am running into an AttributeError when the user tries to input how many multiples they wish to see and I was wondering if there was any way to fix it. Any help would be much appreciated:
def multiple_generator(multiple, number):
if multiple.is_integer() or multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {multiple} = {number * multiple}")
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), a)
except ValueError:
print("Please input a positive integer ")
Try this instead:
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), int(a))
except ValueError:
print("Please input a positive integer ")
The reason your code didn't work because you forgot to cast a to an integer as well. Also is_integer is not needed since b is already casted to an integer type.
From the docs:
Returns True if the float instance is finite with integral value, and False otherwise.
When you are converting b to an integer and passing it, it is getting assigned to multiple. But, is_integer() method only works for floats. So you get an error.
You can simply do:
def multiple_generator(multiple, number):
if float(multiple).is_integer() or multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
But since b is already an integer, you can just check if multiple > 0
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
Also, you are printing multiples of a number. But input returns a string. When you multiply string with an integer, it creates n copies of itself.
While passing the argument a, convert it to an integer.
Also, you need to multiply with i instead of multiple:
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {number * i}") #=== Multiply by i
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), int(a)) #=== pass as An integer
Output:
What number you want to multiply? 2
How many multiples you want to see? 2
2 x 1 = 2
2 x 2 = 4

Why does it give an error when typing "done"?

this is my problem
Can you help me?
Thanks
Write a program that asks the user to repeatedly ask for a number until the word "done" is typed, then by entering "done" the three values ​​of "sum of numbers", "number of numeric inputs", "average of numbers". Print.
Your application should use try and except when the user enters a non-numeric input, show him the "Invalid input" error message and go to the number request again.
Like the following example:
Enter a number: 4
‌Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16
3
5.333333333333333
I type the code below
while True :
try:
number = input ('Enter number: ')
n = int (number)
except:
print('Invalid input')
if n == 'done' :
break
x = None
y = None
for Total in [n] :
x = x + n
print (x)
for num in [n] :
y = y + 1
print (y)
for Average in [n] :
x = x + n
y = y + 1
aver = x / y
print ( aver)
And when I type "done" it displays a "Invalid input" warning
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: done
Invalid input
Enter number:
When you type 'done', number becomes equal to the string 'done'
n = int (number) is then the same as n = int ('done'), which raises an exception, because 'done' can't be parsed as a base-10 integer
Note that since the call int ('done') raised an error, the value of n doesn't change
So you get to the except clause and print('Invalid input')
Since the value of n remained the same, n == 'done' is False
Thus, the loop continues
You can fix it by moving the check inside the except clause:
while True:
try:
number = input ('Enter number: ')
n = int (number)
except:
if number == 'done':
break
print('Invalid input')
Also note that this code:
for Total in [n] :
...
...will create a list with one element [n] and iterate over this list once, because there's only one element. So, it won't really compute any sum.
Furthermore, this code will attempt to add a number to None:
x = None
y = None
for Total in [n] :
x = x + n
print (x)
On the first iteration, x = x + n will evaluate to x = None + <integer>, which is invalid since None can't be added to anything.
Moreover, judging by your input, you want to input multiple numbers, however the first while loop will overwrite the variable n with a new number on each iteration, so all previous numbers will be lost.
You should accumulate these numbers somewhere:
numbers = []
while True:
try:
number = input ('Enter number: ')
n = int (number)
except:
if number == 'done':
break
print('Invalid input')
else:
# There was no exception
numbers.append(n)

Python one line for loop input

I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)
Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")
The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.
You can use this without needing x:
num = [int(x) for x in input().split()]
If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']
Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs

Calculator in python problems

I made a calculator in python but when I run it and do for example 123 and 321 I get 123321 instead of 444, What am I doing wrong?
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
input() returns string not number . That's why instead of addition , String concatenation is performed.
you need to use int(x) and int(y) for conversion.
use this statement answear = int(x) + int(y)
input returns a string, and when you combine two strings the result is what you are seeing.
>>> x = '123'
>>> y = '321'
>>> x+y
'123321'
So you need to convert them to an integer, like this:
answear = int(x) + int(y)
you can use this :
y=int(input())
This is because you are declaring it as a string. Use a = int(input()). This will cast it into an integer. If you want to insert a decimal number use the float data type.
input() accepts and returns a string object and you need to typecast this into an integer (or float) if you want to perform arithmetic operations on it. Performing a + operation on two strings merely concatenates them.
Instead of input(), use int(input()). This will tell Python that the user is about to enter an integer.
def main():
def add(x,y):
return x + y
def sub(x,y):
return x - y
def mult(x,y):
return x * y
def div(x,y):
return x / y
def remainder(x,y):
return x % y
repeat=True
while repeat:
select=int(input("please select any operation:-\n 1.ADD\n2.SUBTRACT\n3.MULTIPLY\n4.DIVIDE\n5.REMAINDER\nselect here:-"))
num1=int(input("Enter the first number"))
num2=int(input("Enter the second number"))
if select==1:
print(num1,"+",num2,"=",add(num1,num2))
elif select==2:
print(num1,"-",num2,"=",sub(num1,num2))
elif select==3:
print(num1,"*",num2,"=",mult(num1,num2))
elif select==4:
print(num1,"/",num2,"=",div(num1,num2))
elif select==5:
print(num1,"%",num2,"=",remainder(num1,num2))
else:
print("invalid input")
print("Do you want to calculate further?\n press y for continue.\n press any other key to terminate.")
repeat="y" in str(input())
if repeat=="y":
print("Ooo yeh! you want to continue")
else:
print("Tnakyou")
main()
This is a simple problem to fix. When adding to integers or doing any other operation including an input and an int you need to do this:
y = int(input())
x = int(input())
a = y+x
so this put into your code looks like this:
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = int(input())
print("Number 2")
y = int(input())
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)

Categories