Completely new to programmming and I'm having quite a few difficulties understanding loops.
I've entered the below code in Python, which tests a users knowledge of the 7 times table:
print('Let\'s test your knowledge of the 7 times table')
table = 7
for i in range(1, 13):
print('What\'s', i, 'x', table, '?')
guess = input()
if guess == 'stop':
break
if guess == 'skip':
print('Skipping. Next question:')
continue
ans = i * table
if int(guess) == ans:
print('You has teh Corrects!')
else:
print('Wrong, it\'s', ans)
print('Finished').')
I wanted to add an 'if' condition to prevent a user from inputting anything other than 'stop', 'skip' or integer input, in order to avoid the 'invalid literal for int() with base 10:' error message. I expressed this as follows:
if guess != int or 'stop' or 'skip':
print('Invalid input. Please enter either a valid command or numeric response.')
continue
I added this code below where the function of the 'skip' input string is defined but when I run the program now it won't recognise numeric input. I've tried inserting this after the point that it's defined that 'guess' can be an integer but at this point the loop doesn't appear to execute this part of the code as I get the 'invalid literal' error I was trying to prevent.
Apologies in advance, I know this is probably a very basic query but I've tried a number of different solutions and I'm struggling to identify whether it's my understanding of loops that's the problem or the way in which I've expressed the '!=' statement.
Thanks
The code you have written in the first part seems like it should work to me, if the break under if guess == "stop" be moved one tab to the right so break is "inside" of the if.
The code in the second part is wrong. You would to it like this:
if guess != "stop" and guess != "skip" and not guess.isdigit():
# Do something.
Use .isdigit():
if not (guess.isdigit() or guess == 'stop' or guess == 'skip'):
print('Invalid input. Please enter either a valid command or numeric response.')
continue
You have to repeat the guess variable, that's why you probably had a syntax error. If not, it was because of the break's indentation.
The error message is caused by the int(guess) itself, and not by the lack of another specific if statement. The int(guess) makes Python try to convert guess to an int and fails (returns a ValueError) if it isn't actually an integer. A way to avoid int(guess) returning an error would be to catch that exception (although I don't know if you've dealt with exceptions yet).
The way this is done is 'trying' to execute int(guess), and if it returns a ValueError, 'catching' that error:
try:
if int(guess) == ans:
print('You has teh Corrects!')
else:
print('Wrong, it\'s', ans)
except ValueError:
print('Invalid input. Please enter either a valid command or numeric response.')
Related
I stole this code from an answer given 2 years ago by someone else with regard to error handling, where the program is looking for an int but getting a non-int value.
My IDE (PyCharm 2021.3.3) on 64 Bit Windows 7 is telling me that the "break" statement is outside of the loop. Is the answer incorrect, or am I missing something?
The original code in the answer was:
while True: #loop forever
try:
u = int(input("Please, enter a number: ")) #this tries to accept your input and convert it to integer
except ValueError: #executes if there is an error in try
print("That isn't a valid integer, please try again")
else:
print("u =",u)
break #break the loop if there was no mistakes in try clause
The error I am getting is:
break #break the loop if there was no mistakes in try clause
^
SyntaxError: 'break' outside loop
With this formatting it works for me.
Python 3.10.4 - Windows 10, Windows Terminal(PowerShell), IDE: Notepad++
I'm very new to python and coding in general. currently trying to make a program that asks the user for a code, and if the code matches up with one of the bits in the list then it prints saying the code was accepted and quits the program. otherwise it says the code is invalid and loops back to the user input.
The issue I have is that it asks the user for the code and regardless of what is inputted it says it is invalid
codes = ['1234', '5678', '2684', '1243', '3565', '3458', '4589']
truecode = False
while not truecode:
user_input = input('Please input your code')
if user_input is codes:
print('Code accepted, enjoy your voucher')
else:
print('Code is invalid, please try again')
Try in instead of is:
if user_input in codes:
print('Code accepted, enjoy your voucher')
else:
print('Code is invalid, please try again')
I was using the if not equal to code but I needed the equal to code specifically for lengths from some previous posts I have tried this code of len(pin(4)) however this somehow still doesn't work
thank you in advance
pay =input("card or cash")
if pay ==("card"):
pin = str(input("enter your pin number"))
while True:
if len(pin)!=4:
str(input("not four digit try again"))
if len(pin(4)):
print("payment cleared")
else:
print("payment cleared")
break
There are several problems with your code, starting with the formatting. You may use essentially any form of tabbing or spacing in python, but the convention and general best practice is to use 4 spaces.
Next, the line. if pay ==("card"): is unnecessarily confusing.
if pay == "card": is much clearer and functions identically.
The first big error you make is to ask for the pin outside of the loop. Since your pin = str(input("enter your pin number")) occurs outside of your while True: loop, your program will only accept input once, then will enter an infinite loop unless the else clause of len(pin)!=4 occurs.
The line str(input("not four digit try again")) makes absolutely no sense. Here, you are accepting input in a line which you surely instead meant to use the print statement instead, and on top of that you are unneccessarily converting the value entered via input into a string. A simple print("not four digits! try again.") will suffice here.
The line if len(pin(4)): should throw an error if run, as there is no builtin called pin which you should be able to call with pin(4). The correct syntax would be if len(pin) == 4:.
I made a couple changes in the code below besides those described above to help with usability. I first convert the value of pin to integer to check if the value is a number. I assume that it is not inappropriate to represent a value which must clearly be a number as an integer in your example, but if you really want it to be a string you could use regex to check if it is a number or not with the re module. Something like if re.match('[0-9]{4}', pin): would work in this case.
pay = input("card or cash")
if pay == "card":
while True:
try:
pin = int(input("enter your pin number: "))
if len(str(pin))!=4:
print("not four digits! try again.")
else:
print("payment cleared")
break
except ValueError:
print('not a valid number! try again.')
All the logic of the program is okay, the program takes the user input and prints an error if the user inputted anything other than a integer, but im not sure how to get the program to loop if the user enters an invalid input.
Passlimit = 10
while Passlimit:
try:
Passinput = int(raw_input("how many characters and numbers would you like for your password to contain? NO LONGER THAN 10 CHARACTERS: "))
if not (Passinput <= Passlimit):
raise ValueError()
except ValueError:
print("Invald input, Please only input numbers")
else:
print("NUMBER SELECTED")
break
The break is immediately following the try...except...else clause. I think you meant to indent the break, so that it is only executed in the else branch.
You would still need to add code though to keep track of the number of tries, otherwise it will loop indefinitely as long as the user provides invalid input.
So I am trying to make a Reddit bot for personal use, as a learning project, and I am having trouble adding error exceptions for inputs.
Here is the entire source code: http://pastebin.com/DYiun1ux
The parts that are solely in question here are
while True:
if type(thing_limit) == int:
print("That is a number, thanks.")
break
elif type(thing_limit) == float:
print("You need a whole number.")
sys.exit()
elif type(thing_limit) == str:
print("You need a whole number.")
sys.exit()
else:
print("That is a number, thanks.")
break
I'm not sure how I would go about making sure that the username that I put in is valid or not. Thanks!
input always returns a string. Your best choice is trying to convert the result to an integer.
try:
thing_limit = int(thing_limit)
except ValueError:
print("You need a whole number.")
sys.exit()
else:
print("That is a number, thanks.")
Every input in python will be read as a string, so checking the type will always return a string. If you want to check the validity of the input, declare a string with such as
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
then iterate over your string to see if that letter is in the charset. If it's not, then the input is invalid. Also make sure that the input does not exceed 20 characters.
The reddit source code defines a valid username as one that's at least 3 characters, no more than 20 characters, and matches the regular expression \A[\w-]+\Z.