I have an issue with my python code to make beeping noises.
It just does an infinite loop of beeps even though it should stop.
import winsound
import time
z = 1
while z == 1:
b = input('Enter number of beeps required')
print(b)
a = input('Is this number correct?')
if a == "yes":
print('Python shall use this number')
z = 2
if a == "no":
b = input('Enter number of beeps required')
x = 1
y = -1
while x == 1:
freq = 1500
dur = 50
winsound.Beep(freq,dur)
y += 1
if y == b:
x = 2
Thanks for any help
If you are using Python 3.x, input() returns a string object.
Comparing string object with int always return False.
>>> '1' == 1
False
You should convert string object to int before compare them:
b = int(b)
BTW, it's better to use following instead of while loop:
for i in range(int(b)):
...
Your problem is that input() on Python 3 returns a string, so b will be a string, and therefore y == b will never be True.
Use
b = int(input('Enter number of beeps required'))
Change
b=input ('Enter number of beeps required')
to
b=int(input ('Enter number of beeps required'))
You are reading b as string and comparing it against an int in
if y == b:
which will never be True. Thats why your code is infinitely looping.
Related
my for loop is looping through a list and i want tomake it so that if a value a user enters a value it its is not found in the list iwant to get another value from the user to check for in the list
import datetime as date
x = date.datetime.now()
D = []
d = int((x.strftime("%d")))
M = (x.strftime("%B"))
for i in range(1,8):
d = d + 1D.append(d)
print (M+", "+str(d))
z = str(input("enter date for booking"))
for i in D :
if i == z:
break
while True:
x = int(input("Enter a Value : "))
if x not in list:
print("Try again")
continue
print("Whatever you want to print")
break
This could help you with your project. If the variables are integers, keep it as int but you could switch it to str or float according with your variable types.
So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))
Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!
My code seems to be stuck in this while loop forever:
array = []
b = 1
while b != 0:
b = int(input("please enter whole numbers "))
array += [b]
print (array)
The meaning of the code is to put user inputs into an array and stop when user enter 0. I don't know why the loop manages to continue the code even though the condition is false. I thought as long as condition is false, python will stop right there!
I keep getting 0 as an element in the array when I don't want it to be in.
I have modified magamongo's answer a little in order to not use break, but you could also use it as in quamrana's answer:
array = []
b = 1
while b != 0:
b = int(input("please enter whole numbers "))
array += [b]
array = array[:-1]
print(array)
I think you could use your own exit condition and not rely on the while statement itself stopping:
array = []
while True: # never exit here
b = int(input("please enter whole numbers "))
if b == 0:
break # exit the loop here
array += [b]
print (array)
"break" helps you to do that.
array=[1]
while array[-1] != 0:
b = int(input("please enter a whole number"))
array += [b]
if array[-1] == 0:
print(array[1:-1])
break
Hope this helps :)
I do not know why this is saying it is wrong when it isn't. I enter the correct answer and it says that is not correct the correct answer is what i inputted
import random
x = 1
score = 0
num = 1
while x == 1:
a = random.randint(10, 201)
b = random.randint(1, 201)
a = int(a)
b = int(b)
c = a / 100 * b
print ("What is")
print (b)
print ("% of")
print (a)
num = input()
if c is num :
print ("Well done!")
score = score + 1
elif c != num :
print ("That is not correct, the correct answer is ", c)
There is a difference between '==' and 'is' in python.
'==' checks if the value is the same, while
'is' checks if they are the exact same object
See also: Is there a difference between `==` and `is` in Python?
Also, input() returns a string, but you compare it to a number. You have to convert the user input to a number first by using int(num) or float(num)
use of is comparison in this case is incorrect, is comparison is based on the object.
you should be using == as you need to compare actual values of the variables
so this
if c is num :
shouls be this
if (c == num):
import random
x = 1
score = 0
num = 1
while x == 1:
a = random.randint(10, 201)
b = random.randint(1, 201)
c = a / 100 * (b *1.0) # adding ‘* 1.0’ makes sure c is a float.
print ("What is %s\% of %s?" %(b, a)) # combined the prints in one line
num = float(input()) # Change input to float
if c == num :
print ("Well done!")
score = score + 1
elif c != num :
print ("That is not correct, the correct answer is ", c)
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P