I am 11 years old and am keen programmer learning Python.
1) I am programming a guess the number game and when I ask the user if they want to play again, I get a semantic error (I think this is the correct way to describe it) where if I input "no", "n", "NO" or "N", the if statement is still executed, causing the loop() function to run again, after calculating scores. Take a look at the following image (sorry about the cluttered windows).
Play again error: https://i.stack.imgur.com/TsEyw.png
Here is a link to the rest of the program:
https://gist.github.com/anonymous/f9be138e07c569b8721b990293d92314 (I only have 8 reputation points) , but I am looking at just this snippet:
def play_again():
again = input("\nWould you like to play again? y/n " + prompt)
if again.upper() == "Y" or "YES":
global gu_num
percent = gu_num * 10
score = 100 - percent
highscores = [{round: (score)}]
current_score = {round: (score)}
highscores.append(current_score)
print("Lets see if you can beat your score of " + str(current_score[round]) + ".\nHere we go!")
gu_num = 0
loop()
elif again.upper() == "N" or "NO":
print("Ok then.\nThank you for playing Guess The Number and I hope to see you again soon!\nThis game was created and devoloped by Kiran Patel (me), age 12. If you liked this game or want to talk to me about -->anything<--, please do email me at kiran#inteleyes.com. It'll make me happy! Thank you for playing Guess the number with me.\n\n program was developed by Kiran Patel in 2017 ad.")
input("\n\nPress the enter key to exit")
quit()
else:
print("Sorry, I don't understand. Please try again:")
play_again()
2) I'm having a similar problem with the part of my code which starts to handle files. When I input a 'no' (same if expression) the program will execute the part of that if statement which creates the file (take a look at this image: file saving result and this image: file operations code). Note that the 'file operations code' image prints out the file-save error message because I hadn't given perms to write in prog'/files folder. I know it has tried to save the file because of the error message that was printed out (I intended the error message to be printed out).
3) Also, does anyone know what #!/usr/bin/python means? I know its hashtagged out, but I have seen it before like this and I was wondering what it means.
As always, ANY help will
be appreaciated, so please don't hesitate on adding something that is not directly relevant to the question, because I may well have missed it (unless it is completely irrelevant).
Once again, thanks in advance for your help.
From Kiran
The problem is here (and on every line that looks like it):
if again.upper() == "Y" or "YES":
Here's what you (reasonably) assume it's doing (This is how you would fix it, btw):
if (again.upper() == "Y") or (again.upper() == "YES"):
Here's what it's actually doing:
if (again.upper() == "Y") or "YES":
So let's say that you typed Q at the prompt. As Python reads along the line, it sees the first comparison operator, ==, and compares just the two things on either side of it: "Q" and "Y". "Those are not equal", thinks Python, and moves on to the next part: comparing False - the answer to the first part - with "YES".
In Python, if something exists and isn't False or 0 or something similar, it gets treated as True. "False is False, but "YES" is a perfectly valid string", thinks Python. "and the or operator means that if either of these two things is True, the whole thing is True, so this must all be true and I should run this block of code now." And so it does, every time, no matter what you type.
As a general rule, when you're doing these kinds of tests, it's only safe to do one comparison at a time. Any more than that and it's time to bring in the parentheses.
Also, regarding #!/usr/bin/python: the #! is called a Shebang, and it's not part of Python at all - it's part of your operating system (assuming your operating system isn't Windows). It says to your OS: "This may look like an ordinary text file, but it's actually a script, which you should run using the program located at /usr/bin/python".
Related
Soo, How can I have text display after an input()?
I'll explain with an example:
import os
docname = input(f"Where do you wanna save your document? {os.path.dirname(os.path.realpath(__file__))\\images\\")
As user is typing, the .pdf extension is after what they typed (am not native English)
Where do you wanna save your document? C:\Users\Public\Downloads\project\(here user can type).pdf
(I don't worry about the extention; docname = docname + ".pdf"
I saw this question, but that doesnt answer my question (This isn't a duplicate of that, because that doesnt appear as I type). Here's how far i've came:
text = f"File destination: {os.path.dirname(os.path.realpath(__file__))}\\images\\"
while True:
answer = input(text)
fileExtension = ".pdf"
while not answer:
pass
# print(f"\33[1A\33[{len(fileExtension)}C {fileExtension}")
# print("\033[A\033[A")
else:
break
The main problems are that:
This doesnt run lol
I can't (or don't know how to) identify the length of characters as user is typing. Also, I dunno if I would need it, but it's probably needed to determine if it has to print(f"\33[1A\33[{len(input)}]C)
The while loop doesn't appear as the input is running. If I would do more research, I maybe will figure out how to run 2 lines at the same time, but then there's gonna be a way more simple answer.
Even if I had all of these together, would it run at all? Or is the cursor jumping left and right without any possible input
I found this code in Python which is working fine.
But what is purpose of this "if True:", because the if is always True so this code inside will run every time. Do you know in which situations we can use this?
if True:
print (type(0x1F))
print (0b010101010)
print (0o7)
Hello I am currently working on a script that goes onto a website and automatically adds an Item to cart and purchases it for you I have a script that works except the only problem is that It is only able to checkout a single Item Item. Here is an example fo the script:
Item_code = input('Item code: ')
Size = input('Size: ')
def BOT():
driver = webdriver.Chrome(executable path=
URL = .....
driver.get(URL)
while True:
try:
driver.find_element_by_css_selector(Item_code).click()
break
except NoSuchElementException:
driver.refresh()
select = Select(driver.find_element_by_id('s'))
select.select_by_visible_text(Size)
The script finds the item with the item code that I use and then selects the size from the users choice
I want to be able to write the code and the size but If I want to bot to cart two Items in different sizes I want it to type in a , and insert the next Item code and Size For example:
12345, 6789
Large, Medium
I want to somehow write that if a comma is included to read and use the code after it after it uses the first one and repeat that for every comma so If I wanted to get 3 or even 4 all I would have to do is this:
1234, 5678, 7890, etc...
Large, medium, Small, etc...
If anyone could Help me out I would really appreciate it I was thinking of something like
for , in BOT():
(something like this but Im not sure )
I know how to tell the script that if Item_code == (',') then do this but that would not work because it needs to be just the comma and I do not know how to tell it to repeat the BOT() a second time and use the second code and size
If someone could help me out I would really appreciate it thanks.
(I want to be able to share this bot since I have already made a GUI for it and all that)
(not sure if the executable path will work when sharing)
I have fixed this problem I created several custom functions and called them on special if statements
ex.
if Item.count(',') == (1):
Cart1()
Checkout()
etc.....
The code I had wasn't executing whatsoever. So, I tried it with a basic code:
x=10, if x==10:, print ("Hello"),
This worked. But the moment I extended it to anything else, it wouldn't run eg.:
count=0, x=10, if x==10:, count=count+1, if count == 10:, print ("Hello"),
(That had correct indents and exc. the commas.) The loop wouldn't loop.
Anyone understand why? The other queries similar to this regard a different issue. It won't run through CMDLine either. I did uninstall and reinstall it but that changed nothing.
The reason your loop won't run is because there isn't a loop. I think what you're trying to do is this.
for i in range(11):
if i == 10:
print('Hello')
With the current string of commands that you're running, count is simply being increment from 0 to 1, and since count != 10 at that point, you never see Hello.
I'm currently working on a Bash script that simulates rolling a number of 6-sided dice. This is all taking place within a virtual machine running Debian that's acting as a server. Essentially, my webpage simulates rolling the dice by using the query string to determing the number of dice to be rolled.
For instance, if my URL is http://127.0.0.1/cgi-bin/rolldice.sh?6, I want the webpage to say "You rolled 6 dice" and then, on the next line, print six numbers between 1 and 6 inclusive (that are of course "randomly" generated).
Currently, printing out the "You rolled x dice" header is working fine. However, I'm having trouble with the next part. I'm very new to Bash, so possibly the syntax or something similar is wrong with my loop. Here it is:
for i in {1..$QUERY_STRING }; do
dieRoll = $(( $RANDOM % 6 + 1))
echo $dieRoll
done
Can anyone help me figure out where I'm going wrong? I'll be happy to post the rest of rolldice.sh if needed.
Since .. requires its arguments to be literals, you have to use eval to substitute the variable:
for i in $(eval "echo {1..$QUERY_STRING}"); do
Or if you have the seq command, you can do:
for i in $(seq 1 "$QUERY_STRING")
I recommend the latter -- using eval with input from the user is very dangerous.