I looked on stackoverflow to solve my problem but from all explanations about loops and checks I don't understand why my code isn't working.
So I want to build a dictionary (totally new to Python btw) and I read that I can also check if the input is in the dicitonary module but that is actually not what I want to do here. I just want to see if the raw_input contains at least one number in the string (not if the string only contains numbers) and if the length of the input string is at least 2.
If the input passes those checks it should move on (the rest of this dictionary will come later. For now I only want to understand what I did wrong with my check)
Here's my code, help would be very much appreciated!
def check():
if any(char.isdigit() for char in original):
print ("Please avoid entering numbers. Try a word!")
enter_word()
elif len(original)<1:
print ("Oops, you didn't enter anything. Try again!")
enter_word()
else:
print ("Alright, trying to translate:")
print ("%s") %(original)
def enter_word():
original = raw_input("Enter a word:").lower()
check()
enter_word()
Edit: Works now perfectly with the following code:
def check(original):
if any(char.isdigit() for char in original):
print "Please avoid entering numbers. Try a word!"
enter_word()
elif len(original) < 1:
print "Oops, you didn't enter anything. Try again!"
enter_word()
else:
print "Alright, trying to translate:"
print "{}".format(original)
def enter_word():
original = raw_input("Enter a word:").lower()
check(original)
enter_word()
You need to pass the input original to your check() function:
def check(original):
if any(char.isdigit() for char in original):
print("Please avoid entering numbers. Try a word!")
enter_word()
elif len(original) < 1:
print("Oops, you didn't enter anything. Try again!")
enter_word()
else:
print("Alright, trying to translate:")
print("{}".format(original))
def enter_word():
original = input("Enter a word:").lower()
check(original)
enter_word()
In addition to this, you had some syntax errors in your code. Since you used print() instead of print I assume you are using Python3. However, to read user input you used raw_input() which was the way to do in Python2 and became input() in Python3. I fixed this. Another thing I fixed was the string formatting of the print() statement in the else branch. You might take a look at the string format mini-language.
Related
I'm currently working on a guessing game assignment. The assignment uses a dictionary to store the course name which is the key and the course number which is the value. The user guesses the course number of the course name given. If the value matches the key then it should print "correct!" and vice versa.
I have gotten the program to display the keys one at a time with an input statement separating them. I've gotten the correct/incorrect counters working. I'm not able to get an if statement working which is supposed to check if the value matches the key. It prints incorrect every time regardless of if the answer is correct. I realize there's probably something wrong with the condition of the if statement because i'm not really sure how to extract one value at a time.
Here's what I have so far:
# Mainline
def main():
programming_courses={"Computer Concepts":"IT 1025",\
"Programming Logic":"IT 1050",\
"Java Programming":"IT 2670",\
"C++ Programming":"IT 2650",\
"Python Programming":"IT 2800"}
print ("Learn your programming courses!\n")
correct=0
incorrect=0
v=0
# Game Loop
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses.values():
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
# Display correct and incorrect answers
print ("You missed ",incorrect," courses.")
print ("You got ",correct," courses.\n")
# Entry Point
response=""
while (response!="n"):
main()
response=input("\n\nPlay again?(y/n)\n# ")
Your problem is here:
if answer != programming_courses.values():
programming_courses.values() is a list of all the values in the dictionary. If you don't understand what's happening in your program, it's really helpful to just print stuff out and see if it looks like what you expect.
What you want is the specific value for the key you're on right now, which you need to look up from the dictionary like so:
if answer != programming_courses[key]:
Also, iterating over a dict gives you the keys by default, so you can just say:
for key in programming_courses:
You don't need to use .keys() there.
Your problem is when you are checking your dict. Currently your code is comparing the answer to a list of all the values in the dict:
out[]:
dict_values(['IT 1025', 'IT 1050', 'IT 2670', 'IT 2650', 'IT 2800'])
If you change to the following it works, by taking the specific value from the dict with the given key:
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses[key]:
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
you could try this
if answer != programming_courses[key]:
Im in my first couple of weeks of programming. I am trying to make a function that asks for a users input, checks whether or not that input is alphabetic, if it is alphabetic then i want to break the while loop.
If I run the script and enter the correct types in the input it breaks and works fine. If I intentionally put a number in the input field it doesn't break out of the loop when I reenter the correct type.
any ideas on what im doing wrong?
def wallType():
wall_type = input("What type of wall was the route on? ")
while wall_type:
#if there is text in the input,instead of an alphanumeric, then tell them they must put in a number.
if str.isalpha(wall_type):
return wall_type
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()
Put your code in a while True loop. When input received is alphabetic, use break to break out of while loop. Else loop again to ask for input.
def wallType():
while True:
wall_type = input("What type of wall was the route on? ")
# string is alphabetic, break out of loop
if str.isalpha(wall_type):
break
else:
print("Please reenter an alphabetic word. Try again. ")
I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.
I want to write a python program, first it asks you to enter two numbers, and then output all daffodil numbers between the two numbers, and it will continue run, until I enter a "q". I write a program, but it is wrong:
#coding=utf-8
while 1:
try:
x1=int(raw_input("please enter a number x1="))
x2=int(raw_input("please enter a number x2="))
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
Can somebody help? I think it should be simple, but I am not able to write it correctly.
I believe you've misunderstood the problem statement. Try this instead:
if i*100+j*10+k==i**3+j**3+k**3:
ref: http://en.wikipedia.org/wiki/Narcissistic_number
for n in xrange(x1,x2):
digits = map(int,str(n))
num_digits = len(digits)
if sum(map(lambda x:x**num_digits,digits)) == n:
print "%d is a magic number"%n
you will still have the issue of not being able to enter "q" since you force the input to be integers
I would like to address the quit event.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
# The mathematical part... (for completeness) (not my code)
if x1>x2:
x1,x2=x2,x1
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print "%-5d"%n
The pass statement is used only when you don't have anything to be executed in certain block of code. It does nothing more, so don't use it if not needed. It is there for the sake of the code looking clean & with correct indentation.
if some_thing: # don't do anything
else:
some_thing = some_thing_else
Note how the above if statement is syntactically incorrect. This is where pass comes handy. Say, you decide to write the if part later, till then you must provide pass.
if some_thing: # don't do anything
pass
else:
some_thing = some_thing_else
It's a bit tricky to know what's going on without more hints, but some issues I see right off:
You need to be consistent with indentation in Python. Your last if statement is less indented than statements above it (like the previous if and the for loop). This will cause an error. You're also using different amounts of indentation in other places, but since it's not inconsistent that's allowed (if a bad idea). Its usually best to pick one indentation standard (like four spaces) and stick with it. Often you can set your text editor to help you with this (turn on "Expand tabs to spaces" or something in the settings).
You've got two pass statements where they're unneeded or harmful. The first, after the line that has if x1>x2: x1,x2=x2,x1 is going to cause an error. You can't have an indented "suite" of code if you've put a series of simple statements on the end of your compound statement like an if. Either put the assignment on its own line, indented, or get rid of the pass. The last pass at the end of the code is not an error, just unnecessary.
You're missing a colon at the end of your try statement. Every statement in Python that introduces an indented suite ends with a colon, so it should be easy to learn where they're needed.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
i have it! thx to Ashish! it is exactly what i want! and i will quit wenn i enter q! thx a lot!
I start my python script asking the user what they want to do?
def askUser():
choice = input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?");
print ("You entered: %s " % choice);
I would then like to:
Confirm the user has entered something valid - single digit from 1 - 4.
Jump to corresponding function based on import. Something like a switch case statement.
Any tips on how to do this in a pythonic way?
Firstly, semi-colons are not needed in python :) (yay).
Use a dictionary. Also, to get an input that will almost certainly be between 1-4, use a while loop to keep on asking for input until 1-4 is given:
def askUser():
while True:
try:
choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
except ValueError:
print("Please input a number")
continue
if 0 < choice < 5:
break
else:
print("That is not between 1 and 4! Try again:")
print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
mydict[choice]()
We use the try/except statements here to show if the input was not a number. If it wasn't, we use continue to start the while-loop from the beginning.
.get() gets the value from mydict with the input you give. As it returns a function, we put () afterwards to call the function.