For loop with If and elif or else in python - python

Question 1:
Just tried to execute the program but i am getting syntax error
i=input('Enter the value of i')
for j in range(10):
if i==j:
print'The value of i is %d'%(i)
elif i!=j:
print'Please enter a valid value'
else:
print 'This is not a number'

The difference between the below two codes is that code one will ask for input once and then loop trying to compare, while code two will ask for input each loop (10x)...

If your code is really indented as you put it here, the reason you are getting a syntax error is that your elif and else blocks are indented too far. Another problem with your code is that i can be either equal or not equal to j. There is no third option. Another problem is that the first time it comes across a number that is not equal to the number typed, it will say that it is not a valid value. Also, just saying "Please enter a valid value" will not make it so. Here is a better version of your code:
i = None
while True:
i = input("Enter the value of i")
if i.isdigit():
if int(i) in range(10):
print "The value of i is %d" % i
else:
print "Please enter a valid value"
else:
print "This is not a number"
As for question 2, the difference between the two is that in the first, i=input('Enter the value of i') will be executed before the loop, and in the second it will be executed for each iteration of the loop. (That is, one time for each time the loop is executed. Because range(10) returns ten items, it runs ten times.) More about for loops here, here, and here

You appear to be having a syntax error because of inconsistent levels of indentation in your code. Please try the following instead and adjust the program to suit whatever your needs might be.
#! /usr/bin/env python3
import sys
def main():
loop = True
while loop:
try:
i = int(input('Enter of the value of i: '))
except EOFError:
sys.exit()
except ValueError:
print('This is not a number')
else:
if 0 <= i <= 9:
print('The value of i is', i)
loop = False
else:
print('Please enter a valid value')
if __name__ == '__main__':
main()

Related

Python How to break loop with 0

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

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'

Does While loop ends when the program return value?

I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

Having issues with a program to input multiple numbers from the user, till the user types “Done". To compute their average and print the results

So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done
Output:
1.5
So far I was able to come up with the input question and got it to loop until you put Done.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!
Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))

problems with if in a function

I am doing a simple program just to the program say if a number is even or not and to when the raw_input isn't a number, the program will complain about it:
def f():
t = raw_input('Enter a number and we will send an inormation: ')
if t != type(int):
print 'is this a number?'
elif int(t) % 2 == 0:
print t
print 'it is an even number'
elif int(t) % 2 > 0:
print t
print 'it is an odd number'
else:
print '???'
but when the program run it returns ONLY the if condition (when i write 90 or a word it returns 'is this a number?'. it should only return this if I Write a string). And I can't figure out where is the problem.
Many errors here.
First, use isintance to test if a variable is an int. Do not use type(t) != int.
Then you do the int(t) operation multiple times.
In addition, it seems that t is a global var, which is not recommended to use, especially for beginners.
Last you have a else at the end but a number is odd or even. There is no other alternatives. To test is a number is odd use if t & 1:.
You can use if t.isdigit():
type(int) returns the type of the object which will never be a value. So it will always be false.
This is caused by the fact that raw_input always returns a string, even if there is only numbers used. You need to type cast it as int and then check if it is odd or even, and catch an exception if it is not able to be converted to int. This is how you should do it:
def f():
try:
t = int(raw_input("Enter a number"))
except ValueError:
print "is this an integer?"
else:
if t % 2 == 0:
print t
print " is even"
else:
print t
print " is odd"
The else after the except block only runs if the exception is not thrown. Also, as #Julien Goupy says, the number is either odd or even, so you don't need the third else statement
Edit: It seems that elif after the try...except block does not work, so I have changed it to else

Categories

Resources