Python indenting issue (Number Guess Game) [duplicate] - python

This question already has answers here:
"inconsistent use of tabs and spaces in indentation" [duplicate]
(29 answers)
Closed 4 years ago.
When I try to run my code it says:
if again == "y":
^
TabError: inconsistent use of tabs and spaces in indentation
My code is:
import random
def game():
wrong_guesses = [1,2,3,4,5]
num = random.randint(0,100)
guess = input("Guess a number bewtween 1 and 100, you have five tries ")
def wrong_guess():
wrong_guesses.remove()
print("That is not the number, You have {} guesses left".format(len(wrong_guesses)))
def right_guess():
if guess == num:
print("Congratulations! You guessed the number. You had {} guesses left".format(len(wrong_guesses)))
play_again()
def game_over():
if len(wrong_guesses) == 0:
break
play_again()
def play_again():
again = input("Would you like to play again? [y/n}")
if again == "y":
game()
elif again == "n":
break
game()

This question has already been answered numerous times, e.g.: "inconsistent use of tabs and spaces in indentation"
So first, please seek out the answer before posting a new question here on StackOverflow.
However, to provide my version of the answer:
The TabError tells you exactly why your code will not run. There is an inconsistency in your use of tabs vs spaces (e.g. you are using both tabs and spaces). The solution is to choose tabs or spaces and switch to it exclusively.
While Python does not require you to use one specifically, the PEP8 style guide advises spaces. You should be able to configure your editor to convert tabs to spaces. PEP8: https://www.python.org/dev/peps/pep-0008/
Also, while syntactically-correct, you should probably change your elif clause in the play_again function to an else (or at least add an else clause after the elif); the reason I say this is you are currently not handling any input other than "y" and "n". Not to mention your code is calling game() recursively as opposed to running in an infinite loop, which is going to cause the program to crash at a certain point; for that I would advise refactoring the game to a while True: loop and then the break would break out of the gameloop--this is traditionally how gameloops work at a high-level.

The error says it all.
TabError: inconsistent use of tabs and spaces in indentation
This means you must have intertwined spaces and tabs in your code. Try removing all the white space and using only spaces (4 to replace a tab).

Related

Why is my 'while' loop not working in Python? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I'm a beginner in Python. I've tried using the 'while' loop. I need the code to allow the user to reattempt the question after their previously incorrect guess. After the first correct try, it says what I want it to say but after the first wrong try, the correct answer is given as incorrect. How do I solve this and what am I doing wrong?
key = input("Choose a place and see if your guess is correct! ")
if key == ("bed"):
print("Congratulations! You are correct and will now progress to room 2.")
while key != ("bed"):
input("Unfortunately your guess is incorrect. Try again. ") ```
First of all you need to indent the 2nd line. Second of all the loop can't work because you say that the loop should stop when the key is "bed" but you do not change the key. The 4th line should be: key = input("Unfortunately your guess is incorrect. Try again. ")
Of course you need to put your if statement in the while loop.
while(True):
if key == ("bed"):
print("Congratulations! You are correct and will now progress to room 2.")
False
else:
key = input("Unfortunately your guess is incorrect. Try againg.")
maybe try it like "this"?

I want to know how to "Hide" a part of my code after it has been used and is no longer needed [duplicate]

This question already has answers here:
How to clear the interpreter console?
(31 answers)
Closed 2 years ago.
I have been making a 5 question "Quiz" on Python. It is pretty simple in code design since I do not have much experience. I want to hide the previous questions so that the code is easier on the eyes and user friendly. I work on IDLE by the way.
i="Incorrect, You lost points for this question."
i2="Incorrect, Try Again."
g="Good Job!"
x=100 #percentage
q1=input("What is 2+3? ")
while q1 != "5":
x-=20
print (i,"Your current score:",x,"%")
q1=input("What is 2+3? ")
while q1 != "5" and (x<100):
print (i2)
q1=input("What is 2+3? ")
else:
print(g)
print("Your current score:",x,"%")
Q2=input("What are the first 3 digits of Pi? ")...
This goes on 4 more times. I want all text that I displayed for q1 to disappear when the input value for Q2 appears.
Import the module os
import os
os.system('cls')
os.system('cls') will clear the screen on windows otherwise replace 'cls' with 'clear'
Just put tthat line whenever you want to clear everything on your code

Just started learning python in college for a password generator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
import random
import string
PassGen = ""
length = int(input("how many characters would you like your password to have 8-15? "))
while len(PassGen) != length:
Num1 = ['random.choice(string.ascii_uppercase)']
Num2 = ['random.choice(string.ascii_lowercase)']
Num3 = ['random.choice(string.digits)']
everything = [Num1, Num2, Num3]
PassGen += [random.choice(everything)]
if (PassGen) == length:
print (PassGen)
my problems are on the lines Num1, Num2, Num3 I have put single speech marks seemed to get it to work but I need to know if that's the correct way to fix it
furthermore for the line PassGen += [random.choice(everything)] I used on of the answers to change Everything to everything and still couldn't get it to work.
There are several things that must be fixed for your script to work, as it appears you are trying to use coding conventions from another language...
Indentation is important in python, and logic and loops need indentation to follow them
Capitalization is important and variables are case sensitive. Typically only classes you define would have a capital first letter, or things like constants in the global scope (usually you protect your main code under a if __name__ == "__main__": block).
You seem to be using brackets to define lists inappropriately when you really only want a string
You seem to think Num1 + Num2 + Num3 generates a list, since you then try to pick an item at random. However, lists are generated with [] (related to point 3).
You do not need to explicitly tell your loops to Continue and the keyword is continue (lowercase) in python anyways.
Here is a modified version of your script that should work (although I would personally code it with different conventions, I tried to change it as minimal as possible)
import random
import string
password_to_be_generated = ""
Length = int(input("how many characters would you like in you password"))
while len(password_to_be_generated) != Length:
Num1 = random.choice(string.ascii_uppercase)
Num2 = random.choice(string.ascii_lowercase)
Num3 = random.choice(string.digits)
Everything = [Num1, Num2, Num3]
password_to_be_generated += random.choice(Everything)
print(password_to_be_generated)
I would recommend you review the basic syntax of python, as it seems pretty significantly different than what you are used to.
You've defined the variable "Everything" with a capital E.
In your code, it has a lowercase "e".
Change this and it should work.

Python if statements keep skipping [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
To provide some context, I am looking to create a program that will encrypt and decrypt through the Caesar cipher, and I have created code for both of these functions that works quite well. However, when I try to conjoin these into one code I find that it always ignores the if statements I have in place and will always try to encrypt what the user enters. Any help would be much appreciated!
characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.`~#$£%^&*()_+-=[]{}|;:<>,/"
translated = ""
print("Welcome to Krypto! ")
decision = input("What would you like to do today? (encrypt, decrypt, info) ")
message = input("Please enter the text you would like to manipulate: ")
if decision == 'encrypt' or 'Encrypt':
print ("Encrypt selected")
#encryption begins
elif decision == 'decrypt' or 'Decrypt':
print("Decrypt selected")
#decryption begins
or 'Encrypt'
This is always True

Creating a quiz and summoning questions and answers from extrernal file

I have a login system in which students take quizzes at different difficulties. what i need to do is load the question and answers for the quiz from an external .txt file. can someone help me quickly please as i need to have this done very soon. can the coding be simple aswell and available to use on python 3.4 as i am not very good with python
This is my attempt at the code:
def easyMathsQuiz():
score=0
emquiz=open("easymathsquiz.txt","r")
questionNumber=0
for questionNumber,line in enumerate(emquiz):
print (line)
ans=input("Your answer is: ")
if ans == "1":
score=score+1
questionNumber=questionNumber+1
elif ans=="2":
questionNumber=questionNumber+1
elif ans !="1" or ans !="2":
print("You have entered an invalid character")
easyMathsQuiz()
break
for questionNumber,line in enumerate(emquiz):
print(line)
if ans == "2":
score=score+1
questionNumber=questionNumber+1
elif ans=="1":
questionNumber=questionNumber+1
elif ans !="1" or ans !="2":
print("You have entered an invalid character")
easyMathsQuiz()
easyMathsQuiz()
print (score)
This is whats inside the .txt file:
What is 2+2-1? 1)3 2)4
What is 10+10? 1)30 2)20
What is 3*9? 1)27 2)36
What is 100/5? 1)25 2)20
What is 30-17? 1)23 2)13
My problem is:
Each line number basically represnts the question number. the first line i got to print but im just not sure how to make the next line print and i need the system to allow the user to input and of course it needs to check if their answer is correct. And i also have just absolutely no idea how to write code for it to go to the start of the question when they enter an invalid character rather than make the whole thing restart
Btw i cant seem to get the code to indent properly on here everything is indented correctly on my program

Categories