Python How to break loop with 0 - python

I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand

You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))

so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function

Related

Am I using boolean operations correctly?

For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic.
Here is what I've got so far.
def check(number):
if (number % 2) == 0:
return True
else:
return False
def main():
number = int(input("Enter an integer: "))
if check is True:
print("This is an even number.")
elif check is False:
print("This is an odd number.")
__name__ == "__main__"
main()
When I run the code, I get the input prompt, but nothing in return after.
check is a function, so it should be like
if check(number):
print("This is an even number.")
else:
print("This is an odd number.")
Python is very flexible, you don't even need a function.
I would take advantage of f-strings and a ternary:
number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')
Example:
Enter an integer: 2
This is an even number
Enter an integer: 3
This is an odd number
As you are basic this is not the best function for check using bool.
def check(num):
return num % 2 == 0 # return True if even otherwise odd
This code is simple and easily to read rapidly.

Python beginner taking Python for Everybody course on Coursera - struggling with numbers assignment 5.2

So the task is to:
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I'm still kind of new to Python but I can't seem to achieve this assignment on my own. I kind of want to avoid just copying someone else's code because the teacher of the module Charles Severence, says that's not a good idea. But I'm also getting tired of this assignment that probably does not reflect anything I would normally want to use python for as a programmer.
This is my code at the moment. It seems like no matter what I change there is always a new error:
Please help, suggest solutions and tell me the mistakes I'm making.
EDIT:
I have received comments about the indentation errors and I wanted to clarify that these were typos I caused when copying my code into this forum. Anyway, I have adjusted my code and it no longer has the problem of not accepting 'done' or not continuing the loop after an invalid input. Now, the difficulty I'm having is retrieving the maximum and minimum values with or without a list function. Also, at this point I'm so stuck I wouldn't mind receiving some direct answers with working code.
largest = None
smallest = None
number_list = []
while True:
num = input('Enter a number:')
if num == 'done' : break
try:
num = int(num)
number_list.append(num)
except:
print ('Invalid Input')
continue
def max(num):
for largest in number_list[num]:
if largest < num:
largest = num
return largest
def min(num):
for smallest in number_list[num]:
if smallest is None:
smallest = num
if smallest > num:
smallest = num
return smallest
print ('Maximum is',max(num))
print ('Minimum is',min(num))
While not giving away the complete code due to the reasons your teacher stated, there are quite a few things to look at there:
The values aren't currently being returned since input always returns a string, and you need integers to compare, so after you input, you should add a line that tries to convert the input to an integer variable, something like this:
num = input('Enter a number:')
if num != "done":
try:
num = int(num)
number_list.append(num)
except ValueError:
print("Must be a number or the word 'done'")
Note that I also checked for a number_list variable that should be defined as an empty list beforehand. Lists are great for the purpose of storing many numbers on a single variable and then checking it for the largest and smallest number with the max() and min() arguments.
I assume you haven't heard of lists yet.
The way I would solve it would be to use a list to store all the values and then applying the max(list) and min(list) built-in functions.
alln = list()
num=""
while num!='done':
num = input('Enter a number:')
try:
alln.append(float(num))
except:
print('invalid input')
print ('Maximum is',max(alln))
print ('Minimum is',min(alln))
Like this
Check this and this to understand the basics of lists and how to work with those two functions.
Now the problems with your code
1. You have several indentation errors.
for largest_num in [uval]:
if largest is not None or uval > largest:
^here, the 'if' should be inside the 'for' block and it wasn´t. You have this problem twice in your code
while True:
num = input('Enter a number:')
uval = float(num)
if num == str:
elif num == str('done'):
^here, all four need an extra space to be properly indented
2. Because of this
num = input('Enter a number:')
uval = float(num)
When you write "done", you get another error. Try doing this instead:
while True:
if num == 'done':
break
#check if it's not a number
else:
num = float(num)
#store the value as a float
That way you can avoid converting a string to a float, which is why you are getting the error
Other problems I found
Both prints have indentation errors. But assuming that's just a typo, the indentation itself will make the loop print every single time it runs because it's inside the 'for' block.
str('done') this doesn't work because str() will transform the argument to a string. Remember that 'done' is already considered a string by python, so you can just write num == 'done'

Loop as long as input is greater then previous input

sorry - just a simple task, of asking for higher input unless its equal or less than previous input.
does it require a place holder for the input value or am I missing a break?
num=input("Enter a number: ")
while True:
num <= num
print("Something is wrong")
num=input("Try again: ")
if num >= num:
print("Keep going higher!")
code output
Something is wrong
Try again
import sys
num_tmp = -sys.maxsize - 1 # this expression returns lowest possible number
while True:
num = input("Enter a number: ") # input returns string value
if not num.isdecimal(): # checking if input contains only digits
print("Not a number, try again.")
continue # skips futher instructions and go to next iteration
elif int(num) < num_tmp: # int(num) converts string to integer
print("Entered number is lower that previous. That's all. Bye.")
break # breaks loop execution ignoring condition
num_tmp = int(num) # updating num_tmp for comparsion in next iteration
print("Keep going higher!")

Boolean return value?

def main():
num = int(input('Please enter an odd number: '))
if False:
print('That was not a odd number, please try again.')
else:
print('Congrats, you know your numbers!')
def number():
if (num / 2) == 0:
return True,num
else:
return False,num
main()
I am trying to make it so that if the number entered is odd, it congratulates the user. If not then it should tell them to try again. I am trying to return the Boolean value to main and then when I try to use the code in the main function to prompt the user, it doesn't work.
Your functions are very odd and I'm not talking about numbers that aren't divisible by 2. Try this:
num = int(input('Please enter an odd number: '))
if num % 2 == 0:
print('Better luck next time??') # no really, you should go back to school (;
else:
print('Genius!!!')
Try this:
num_entry = int(input('Please enter an odd number: '))
def number():
return num_entry % 2 == 0
def main():
if number() == True:
print('Sorry, please try again.')
else:
print('Nice! You know your numbers!')
number()
main()
This should work!
Your code does look odd like Malik Brahimi mentioned. This may be because you are trying to write your python code like Java, which requires a main method. There is no such requirement in python.
If you would like to have your check for the "odd-ness" of the number wrapped in a defined function that you can call elsewhere, you should try writing it like this.
def odd_check(number):
if number % 2 == 0:
#This is the check the check formula, which calculates the remainder of dividing number by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
num = int(input('Please enter an odd number: ')) #where variable is stored.
odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.
If you would like a piece of code that will continue to ask your user to enter a number until they get it right, try something like this:
while True: #This ensures that the code runs until the user picks an odd number
number = int(input('Please enter an odd number: ')) #where variable is stored.
if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
break #This stops the "while" loop when the "else" condition is met.

inconsistent string to int error and response

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

Categories

Resources