Integer, Input, print - python

The main problem I have is with the printing, It doesn't work as it gives me the error:
NameError; the name 'ask2' is not defined
I am an absolute beginer in Python, therefore I have literally NO idea how to make it global, or something in those lines.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
if int(ask) == 1:
print("========================================================================")
ask2 = ""
while ask2 != 'exit':
ask2 = input("Please enter it in such form (XX00XXX): ")).lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
# This 'elif' is optional, it just provides a bit better feedback to the user so he knows he manually stopped
elif ask2 == 'exit':
#There are other parts of the code, but it's not necessary
else:
plate = ""
# This randomly adds two capital letters (your own code)
for i in range(2):
plate += chr(random.randint(65, 90))
print()
print(plate)
print("The program, will determine whether or not the car "+str(plate),ask2+" is travelling more than the speed limit")

Your code is currently structured like this:
if some_condition:
ask2 = ''
else:
...
print(ask2)
The problem is that when some_condition is False and the else block executes, after the if/else when you try to print ask2, you're getting the NameError since the if block never ran and ask2 is undefined.
You need to do:
ask2 = ''
if some_condition:
...
else:
...
print(ask2)
Also, unrelated, but there's absolutely nothing wrong with using break.

The error does say it fairly well. ask2 doesn't seem to be defined.
Did you define int somewhere before? You won't be able to use it, if you haven't declared it somewhere before.
if int(ask) == 1:
print("========================================================================")
ask2 = ""
while ask2 != 'exit':
it seems like you are calling on ´ask2 being != 'exit' ´ but you did not did not assign any value to it. It just says ask2 ="". Try to assign it some value before, either by defining it or by having one automatically assigned.

Related

Playing with loops

I'm trying to figure out how to work with loops in Python and I need a little help. The code I wrote is just something I'm playing with. It's not an assignment or anything like that.
What I'm trying to figure out is how to loop the program so that it asks the user to input something to start the questions over. This is what I have so far:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
monkeys()
I'm trying to get main() to do most of the work since that's what my teacher wants on our assignments. Everything under main() is something I copied to see if that would work but it only returns this:
Type in Gorilla, Chimp or Macaque and make sure they're capitalized: Gorilla
This is not a monkey!
This is not a monkey!
This is not a monkey!
This is not a monkey!
It was a lot longer than just the 4 lines but this is not what I'm looking for.
I see a couple of problems here...
First of all, you're concatenating two strings...
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
When you go into your for-loop, the interpreter is looking at each character of that concatenated string. This is why you output 38 lines of "This is not a monkey!" For what you're trying to do, you don't need a for-loop. Try this instead:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
else:
print(monkey_yes)
The next issue I see is that you don't call the main function at all. Instead of calling moneys() at the bottom of your code, call main().
Next issue is using "while True:". If you're going to use a boolean as a while condition, make sure you put logic in your code to change that condition. Changing it to "False" should be what exits your main, not a return statement. Your main() would be better off starting like this:
def main():
keep_going = True
while keep_going:
monkeys()
Notice you should call your monkeys() function first, otherwise nobody will know what to input when the program starts. You also need code asking if they want to continue running the program. Right after your monkey() call, do something like this:
monkeys()
again = input("Would you like to try again? (y/n) ")
The next issue is your use of return statements. Instead of doing this:
elif again == "n":
return "Good bye!"
do this...
elif again == "n":
print("Good bye!")
keep_going = False
Lastly, you have "if again not in {"y","n"}:". You have to assign a value to "again" or you'll get more errors. If you use the example above, it should meet your needs.
Keep plugging at it and don't lose hope. You're getting close to understanding it.
First of all, you call monkeys() but you should call main() instead since that's where the loop is. Second, return causes a function to halt execution and to continue where you called it. In order to continue looping, remove the returns in main().
To get a better understanding of how your code works read this article about debugging. It shows some tips that allow you to see step-by-step what your code is doing.
You should use this code instead, which (as many have pointed out including #Code-Apprentice above) calls the function main() as you intend. #Code-Apprentice 's answer also includes a good explanation of why this works. This code is almost exactly the same as yours above; only the last line is different:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
main()
The reason I am submitting this answer is to point out that, despite calling main(), you are going to encounter another problem right away. You refer to a variable again in main(), but you never assign a value to again in the first place (if you run this code, you can expect to see an error of the form, "NameError: global name 'again' is not defined."). Addressing this next error is beyond the scope of your question; there are lots of ways that you can re-write this code to accommodate again, if you choose.

Input/If statement - correct way of writing

I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.
As I am just starting out, I was wondering which way is more preferable to write the program,
The solution is:
# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")
# If they want to proceed
if should_proceed.lower() == "y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= num_tickets
# Otherwise...
else:
# Thank them by name
print("Thank you anyways, {}!".format(name))
Whereas, I have put:
# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()
# If they want to proceed
if proceed == "Y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining = tickets_remaining - ticket_request
print(tickets_remaining)
# Otherwise...
elif proceed == "N":
# Thank them by name
print("Thank you for your time, {}".format(customer_name))
Was it incorrect to call upper() on the input?
Is there any other errors I have done?
Many thanks,
Was it incorrect to call upper() on the input?
No, this is a perfectly fine way to allow case-insensitive input. Their solution shows an alternative that works just as well.
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:
proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
doSomething()
elif proceed.upper() == "N":
doSomethingElse()
On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:
proceed = ""
while proceed != "Y" and proceed != "N":
proceed = input("Would you like to proceed (Y/N)? ").upper()

Why does function keep repeating text after I end while loop and exit?

Problem
To reproduce the problem, run this in repl.it and input "cNOT" (without the quotation marks) when prompted. After this it should ask about the gates you want for the second qubit, instead, it asks again the same question you gave "cNOT" as an answer to.
Code
import numpy as np
def target(qstat):
typegat2 = input("Which gate is this target qubit for? See list of two qubit gates at the top.")
if typegat2 == "cNOT":
carray = np.array([[0,1],[1,0]])
if np.array_equal(mem1, [0,1]) == True:
return qstat
elif np.array_equal(mem1, [1,0]) == True:
return np.dot(qstat,carray)
else:
print("superposition...not implemented")
return qstat
else:
print("other gates not yet implemented")
return qstat
qubits = 2
qstat = {1:[0,1],2:[0,1]}
done = "n"
singates = {"target":target}
x=1
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
while True:
try:
qstat[x]=singates[fstgat](qstat[x])
break
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
done = input("Done with your qubit? y or n: ")
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"
print("result for qubit",1,qstat[0])
print("result for qubit",2,qstat[1])
Explanation of code
The code is way reduced down, but it's meant to be a simulation of an ideal quantum computer. "qstat" is a dictionary of the states of each qubit. It probably doesn't need to be a dictionary, but the way it is in the actual program is nice so I'm keeping it. Anyway, "qubits" is the number of qubits in the system and it normally can be any integer the user inputs. The function "target" is the target qubit in a cNOT gate. The reason there's the "try...except" section is in the code is because sometimes the user will input "target" before "control" and since the control qubit needs to be checked to determine what to do with the target qubit, outputs a NameError, so I set it up to record that qubit in a list that I'm currently coding to "recalculate" each of the qubits in that list.
"done" is a way of checking that the user's done with each qubit, and since it's in a while loop, I thought setting it to "y" after the "except" statement would end the while loop and move on to the next qubit, but for some reason it's staying inside the function - the same line is repeated over and over. If you wish to exit the function, you have to type some gibberish, because that corresponds to the last else statement, where if typegat2 doesn't equal "cNOT" it returns qstat (which hasn't changed) and moves on. So clearly the function isn't returning anything because of the error, or something. But then the problem becomes, how can I get it to exit the function?
Any help would be appreciated. I would be glad to answer any questions you have on the code; I tried to reduce it as much as possible.
Get rid of the while True: loop, that's causing the code to repeat whenever the NameError exception occurs.
Also, move the input for done into the try block. Otherwise, that input will override the done = "y" statement in the except block.
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
try:
qstat[x]=singates[fstgat](qstat[x])
done = input("Done with your qubit? y or n: ")
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"

Python 3.x - Input only returns first item

I have been having problems with a block of code in a little project and I can't seem to fix it.
In the below code, I define inputrace() so that a process is carried out where the player types in a number that is above 0 and below 13 (there are 12 choices, each dictated by a number); it also checks for blank lines and strings and has the program state that there is an error and ask for user input again if they are detected. If it passes the check, RaceInp is returned and set to RaceChoice which allows the code below it to assign a Race to the player based on their selection.
#race check
def inputrace():
print ("Input number")
RaceInp = input()
Check = RaceInp
try:
int(RaceInp)
except ValueError:
print("Numbers only!")
inputrace()
if not int(Check)>12 or int(Check)<1:
return RaceInp
print (RaceInp) #this is here so I can check the value returned
Race = "NA"
RaceChoice = inputrace()
print (RaceChoice)
#assign race
if RaceChoice == "1":
Race = "Human"
#continues down to twelve
Everything works when valid strings are put in (any number 1-12), but things break when I purposefully put in an invalid string. It seems like RaceInp only retains the first user input and does not change, even after the function is recalled from an error. That means if I were to put in "a," the program will tell me it is wrong and ask again. However, when I put in "1" in an attempt to correct it, it accepts it but still keeps RaceInp as "a."
Is there any fix to this? I have no clue what's going on.
I appreciate the help and sorry if I got anything wrong in the question!
It seems that the problem is that you put the inputrace in a recursion instead of a loop. Something like this would probably be better:
def input_race():
while True:
print("Input a number between 1 and 12.")
race_input = input()
try:
race_input = int(race_input)
if race_input >= 1 and race_input <= 12:
return race_input
except ValueError:
pass
print ("'{input}' is not a number.".format(input=race_input))
race = "NA"
race_choice = input_race()
if race_choice == 1:
race = "Human"
print(race)

In this very basic code i can't figure out what's the sytax error here in line 6 is (python)

myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")

Categories

Resources