I am new to Python.Trying to learn it.
This is my Code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
The code is executing but the loop is always repeating and is not allowing me to enter 2nd integer.
Output:
How many integers?3
Please enter integer1:1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:
Can i know what is wrong with my code?
Thank you
The problem of your code is that isint is never changed and is always False, thus count is never changed. I guess your intention is that when the input is a valid integer, increase the count;otherwise, do nothing to count.
Here is the code, isint flag is not need:
import sys
while True:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
break
except ValueError:
print("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
try:
new_int=int(new_int)
ints.append(new_int)
count += 1
except:
print("You must enter an integer")
isint needs to be updated after asserting that the input was int
UPDATE:
There is another problem on the first try-except. If the input wasn't integer, the program should be able to exit or take you back to the begining. The following will keep on looping until you enter an integer first
ints=list()
proceed = False
while not proceed:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
proceed=True
except:
print ("You must enter an integer")
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint=True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
A better code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints = []
for count in range(0, my_int):
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint = True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
Related
The ValueError part of my code works well alone but with my if and elif statements it does not work? could someone please explain what I did wrong thank you. The table is linked and my coding is written for you.
!table](https://i.stack.imgur.com/mayZQ.png)
pass_credit=int(input("please enter your credits at pass:"))
defer_credit=int(input("please enter your credits at defer:"))
fail_credit=int(input("please enter your credits at pass:"))
if pass_credit==120:
print("progress")
elif pass_credit==100:
print("do not progress-module retriever")
elif fail_credit>80:
print("exclude")
elif pass_credit==80:
print("do not progress-module retriever")
elif pass_credit<80:
print("do not progress-module retriever")
#Start
while True:
try:
pass_credit=int(input("please enter your credits at pass:"))
break
except ValueError as e:
print ("Bad integer value entered, try again.")
while True:
try:
defer_credit=int(input("please enter your credits at defer:"))
break
except ValueError as e:
print ("Bad integer value entered, try again.")
while True:
try:
fail_credit=int(input("please enter your credits at fail:"))
break
except ValueError as e:
print ("Bad integer value entered, try again.")
print(f"You entered: {pass_credit=}, {defer_credit=}, {fail_credit=}")
while True:
try:
entry=input("please enter your credits at pass:")
pass_credit = int(entry)
break
except ValueError as e:
print (f"You entered: {entry}, which is not an integer, try again.")
#End
How to exit the program after max 3 attempts using Python, for exception program , if you dont get the desired output?
while True:
try:
x = int(input("Please enter a number: "))
break
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
exit (1)
nothing = 0
while nothing < 3:
nothing += 1
try:
x = int(input("Please enter a number: "))
break
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
Try:
c = 0
while c < 3:
c += 1
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
You want exit after 3 attemps. Try this and count that input is wrong:
num_err = 0
while num_err < 3:
try:
x = int(input("Please enter a number: "))
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
num_err += 1
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
Use sys.exit() for stopping the whole script
import sys
while True:
try:
x = int(input("Please enter a number: "))
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
sys.exit()
I read all the code that is submitted above but one thing is missing, that if a user
enter two incorrect value then enter a correct value after that he has only one chance. That is if user enter any wrong input after entering two correct input the loop will break.
So I have tried to solve this problem. Look at my code...
count = 0
while True:
try:
x = int(input("Please enter a number: "))
count = 0
break
except ValueError:
count += 1
print("You have entered the non-numeric value.Only three invalid inputs are allowed. Enter the numerical value.")
except KeyboardInterrupt:
print("\nYou have press Ctr+C.")
exit(1)
if count == 3:
break
I am trying to explain what I have written in this code.
As you have mentioned that a user can enter only three invalid input so I have increased the variable count each time when user will enter an invalid input. But if a user will enter a valid input then the count will be 0. It means again the user can enter maximum three invalid input. After entering three invalid input continuously the count will be 3 and the loop break
I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".
Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?
while number != "done":
try:
number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
except ValueError:
print("not a number!")
continue
Separate the two parts : ask the user and verify if it is done, then parse it in a try/except
number = None
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
number = float(number)
except ValueError:
print("not a number!")
continue
print("Nice number", number)
Instead of trying to make exceptions to the rules, you can instead do something like,
while True:
try:
number=input("Enter a number: ")
number=float(number)
except:
if number=="done":
break
else:
print("Not a number")
Check if the error message contains 'done':
while True:
try:
number = float(input("Enter a number: "))
except ValueError as e:
if "'done'" in str(e):
break
print("not a number!")
continue
also in this case continue is not necessary here (for this example at least) so it can be removed
Maybe convert the number to float afterwards. You can check if number is not equal to done,then convert the number to float
number = 0
while number != "done":
try:
number = input("Enter a number: ") #The user should be able to write "done" here as well
if number=="done":
continue
else:
number = float(number )
except ValueError:
print("not a number!")
continue
There are various ways to approach this situation.
First one that came across my mind is by doing:
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
else:
try:
number = float(user_input)
except ValueError:
print("not a number!")
continue
while True:
try:
user_input = input("Enter a number: ")
if user_input == "done":
break
number = float(user_input)
except ValueError:
print("not a number!")
continue
You can cast the input to float after checking if the input is 'done'
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
I decided to learn python and I chose the book "The python book" to do so but I encountered a problem while coding one of the exercise programs, I'm doing a program that shows how control structures work but it gets stuck in a while loop, I think it is because a boolean variable (isint) is not setting to true so it just gets stuck there, but I'm not sure because I'm new to programming.
#!/usr/bin/env python2
import sys
target_int=raw_input("How many integers? ")
try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an integer")
ints=list()
count=0
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
print("Using a for loop")
for value in ints:
print(str(value))
print("Using a while loop")
total=len(ints)
count=0
while count<total:
print(str(ints[count]))
count+=1
I would get this result everytime I ran the program:
jonathan#Jonathan:~/Python$ ./construct.py
How many integers? 1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:4
Please enter integer1:4
Please enter integer1:23
Please enter integer1:13
As you can see no matter what I put there the while loop just keeps going.
Indentation is important in python:
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
This is two separate blocks of code: the if isint==True: part is not inside the while count<target_int: block.
You need to change it to this:
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
Additionally, isint is never set to anything but False, anywhere. So the body of your if statement is never going to execute.
You probably want to set isint to True when you know the input is a valid integer.
You aren't setting isint flag to true when checking for an integer.
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint=True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
First your indentation looks wrong for:
if isint==True:
ints.append(new_int)
count+=1
Then you should add isint = True in (at the end of) the block
try:
new_int=int(new_int)