I've been trying to make this code worked but is giving me a confusing error (been trying to figure out during the weekend)
numberone = ("Failed")
user = int(input("Enter any number: ")
if user > 15:
print(numberone)
else:
print("well guessed")
File "<string>", line 3
if user > 15:
^
SyntaxError: invalid syntax
What seems to be the issue?
Because you didn't close the bracket in the previous line.
You have:
user = int(input("Enter any number: ")
And should be:
user = int(input("Enter any number: "))
Also, there is a problem with the else statement. It should be right under the if (in python it is important)
In general, this should work:
numberone = ("Failed")
user = int(input("Enter any number: "))
if user > 15:
print(numberone)
else:
print("well guessed")
Related
Ask the user to enter a number and check if the input is 'POSITIVE', 'ZERO', 'NEGATIVE'
def is_positive():
# input() returns str
user_input() = input("Please enter a number: ")
# cast input into int -> int()
n = int(user_input)
# check conditions
if n > 0:
print("POSITIVE")
elif n == 0:
print("ZERO")
else:
print("NEGATIVE")
Close just change the user input variable name to have no parentheses like so. The parentheses are meant for when you are calling a function which is why an error was raised.
user_input = input("Please enter a number: ")
count=0
while count < 3:
Username = input('Username: ')
Password = input('Password: ')
numAttempts = 3
if Password=='123' and Username=='admin':
print('Successfully logged in')
elif:
print('Invalid username and password!')
count += 1
else numAttempts > 3:
print("Account has been blocked")
File "", line 8
if Password=='123' and Username=='admin':
^
IndentationError: unexpected indent
In python, indents matter. You would need to tab everything after the
while count < 3:
Any conditional or loop statement needs to be indented after. It's also important for the tabs to be consistent (IE, using the tab key or same number of spaces).
You also look like you have your logic flipped with your else and elif statement.
Also, you numAttempts should probably start at 0, and you need to update this in the else clause.
This should get you started.
count=0
while count < 3:
Username = input('Username: ')
Password = input('Password: ')
numAttempts = 3
if Password=='123' and Username=='admin':
print('Successfully logged in')
elif numAttempts > 3:
print("Account has been blocked")
else:
print('Invalid username and password!')
count += 1
So I have an assignment:
Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it. Here’s an example:
cat
cot
cog
log
Write a program to help your friend.
It should do the following:
Ask your friend for an initial word
Repeatedly ask them for an index and a letter
You should replace the letter at the index they provided with the letter they enter You should then print the new word
Stop asking for input when the user enters -1 for the index
Here’s what should be happening behind the scenes:
You should have a function, get_index, that repeatedly asks the user for an index until they enter a valid integer that is within the acceptable range of indices for the initial string.
(If they enter a number out of range, you should reply invalid index.)
You should have another function, get_letter, that repeatedly asks the user for a letter until they enter exactly one lowercase letter. (If they enter more than one character, you should reply Must be exactly one character!. If they enter a capital letter, you should reply Character must be a lowercase letter!.)
You should store a list version of the current word in a variable. This is what you should update each time the user swaps out a new letter.
Each time you have to print the current word, print the string version of the list you are keeping in your variable.
I have tried rewriting, researching, and even debug mode.
def get_index():
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + ": "))
if index_in > len(string) or index_in < -1:
print "Invalid Index"
elif index_in == -1:
return False
else:
get_letter(index_in)
def get_letter(index):
global string
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print "Character must be lower case!"
else:
char_list[index] = letter
string = ('').join(char_list)
break
print string
string = input("Enter a word: ")
get_index()
An example of the program should look like this:
Enter a word: cat
Enter an index (-1 to quit): 1
Enter a letter: o
cot
Enter an index (-1 to quit): 2
Enter a letter: g
cog
Enter an index (-1 to quit): 5
Invalid index
Enter an index (-1 to quit): -3
Invalid index
Enter an index (-1 to quit): 0
Enter a letter: L
Character must be a lowercase letter!
Enter a letter: l
log
Enter an index (-1 to quit): -1
Your code looks perfect!
Just need some changes according to (python 3)
def get_index():
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + " (-1 to quit): "))
if index_in > len(string) -1 or index_in < -1:
print("Invalid Index")
elif index_in == -1:
return False
else:
get_letter(index_in)
def get_letter(index):
global string
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print("Character must be lower case!")
else:
char_list[index] = letter
string = ('').join(char_list)
break
print(string)
return
string = input("Enter a word: ")
get_index()
You should use print(msg) instead of print msg in python 3
You missed one condition, consider this scenario,
Run the program
Enter a word: c
Enter a number between 0 and 0 (-1 to quit): 1
Error
there was a wrong in get_index() check on line:
if index_in > len(string) or index_in < -1:
it should be :
if index_in > len(string) -1 or index_in < -1:
============================================================ *
UPDATE
updating the annwer according to discussion in comments:
def get_index(string):
try:
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + " (-1 to quit): "))
if index_in > len(string) -1 or index_in < -1:
print("Invalid Index")
elif index_in == -1:
return False
else:
get_letter(index_in, string)
except ValueError:
print("Please Enter a number!")
get_index(string)
def get_letter(index, string):
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print("Character must be lower case!")
else:
char_list[index] = letter
string = ('').join(char_list)
break
print(string)
return
if __name__ == "__main__":
string = input("Enter a word: ")
get_index(string)
CHANGES are:
You must avoid global variables.
Instead, pass particular variable to functions as argumens.
Notice, how string was used in first answer and how it was used in the updated answer.
Use try-catch blocks to catch unexpected behavior
I am doing some CodeHS for my computer science class at my school and for some reason my program doesnt meet the criteria of the grader, and maybe someone can assist me.
The autograder is looking for this:
The things it tests with are here:
and every result returns a runtime error in the autograder but not in the console.
Heres my code:
def get_letter():
while True:
letter = str(input("Enter a letter:\n> "))
if letter.isupper() == True:
print("Character must be a lowercase letter!")
continue
if len(letter) > 1 or len(letter) < 1:
print("Must be 1 character!")
elif letter.islower() == True:
return letter
break
def get_index():
while True:
try:
index = int(input("Enter an index (-1 to quit):\n> "))
if index == -1:
break
if index > len(word) or index < 0:
print "Invalid index"
continue
if index <= len(word):
global letter
letter = get_letter()
return index
break
except ValueError:
print "Please enter a number"
continue
word = input("Enter a word\n> ")
words = list(word)
while True:
try:
indexes = get_index()
splitword = words[:indexes] + [letter] + words[indexes +1:]
joinedword = ''.join(splitword)
print joinedword
except NameError:
break
and here are the instructions:
The CodeHS lesson is 8.3.8 Word Latter
This might be a little too late. I just came up to this question on CodeHS and had trouble myself. But I found it somewhere else, not to CodeHS's requirements so I had to fix it up myself. Here it is all fixed
def get_index(Inital_Word1):
User_Input = int(input("Enter an index (-1 to quit): "))
DexNav = len(Inital_Word1)
while User_Input > DexNav or User_Input<-1:
print "Invalid index"
User_Input = input("Enter an index (-1 to quit):")
DexNav = len(Inital_Word1)
return User_Input
def get_letter():
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while DexNav > 1:
print "Must be exactly one character!"
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while User_Input.isupper():
print "Character must be a lowercase letter!"
User_Input = input("Enter a letter: ")
return User_Input
def replace_at_index(User_Input, num, replacement):
return User_Input[0:num] + replacement + User_Input[num + 1:]
for i in range(1):
Inital_Word = input("Enter you inital word here: ")
Index = get_index(Inital_Word)
while Index != -1:
Letter = get_letter()
Inital_Word = replace_at_index(Inital_Word, Index, Letter)
print (Inital_Word)
Index = get_index(Inital_Word)
I was wondering if anyone could help me figure out how to allow a user to first register and then sign in to take a quiz. I’m finding it difficult as the users details such as name, age and year group as well as username and password need to be saved to a text file. I have some of the code for registration already completed but I'm still confused.
with open("user account .txt","w") as userFile:
usernamePart1 = raw_input("Enter your name:")
while not usernamePart1.isalpha():
print("Invalid name, try again")
usernamePart1 = raw_input("Enter your name:")
usernamePart2 = raw_input("Enter your age:")
while not usernamePart2.isdigit():
print("try again")
usernamePart2 = raw_input("Enter your age:")
fullUsername = usernamePart1[:3] + usernamePart2
userFile.write("Username:" + fullUsername)
with open("reports.txt","a") as reports:
reports.write("\n" + "Username:" + fullUsername)
print "Your username is" + " " + (fullUsername)
UserYearGroup = int(raw_input("Enter your year group:"))
while UserYearGroup < 7 or UserYearGroup > 15:
print("Invalid year group, enter again")
UserYearGroup = int(raw_input("Enter your year group:"))
if UserYearGroup >= 7 and UserYearGroup <= 14:
userFile.write("\nYear Group:" + str(UserYearGroup))
print(UserYearGroup)
password = raw_input("Enter a password which you will remember:")
userFile.write("\nPassword:" + password)
It keeps saying this when i run it:
Traceback (most recent call last):
line 22, in <module>
userFile.write("\nYear Group:" + str(UserYearGroup))
ValueError: I/O operation on closed file
This line of code
userFile.write(“\nYear Group:” + str(UserYearGroup)) is not in the with block that defines userFile (the first with block).
As soon as you go out of the with block, the file is closed, and you cannot write to it.
You can :
Make sure that all the code until this line is still in the with block defining userFile
for instance :
with open("user account .txt","w") as userFile:
usernamePart1 = raw_input("Enter your name:")
while not usernamePart1.isalpha():
print("Invalid name, try again")
usernamePart1 = raw_input("Enter your name:")
usernamePart2 = raw_input("Enter your age:")
while not usernamePart2.isdigit():
print("try again")
usernamePart2 = raw_input("Enter your age:")
fullUsername = usernamePart1[:3] + usernamePart2
userFile.write("Username:" + fullUsername)
with open("reports.txt","a") as reports:
reports.write("\n" + "Username:" + fullUsername)
print "Your username is" + " " + (fullUsername)
UserYearGroup = int(raw_input("Enter your year group:"))
while UserYearGroup < 7 or UserYearGroup > 15:
print("Invalid year group, enter again")
UserYearGroup = int(raw_input("Enter your year group:"))
if UserYearGroup >= 7 and UserYearGroup <= 14:
userFile.write("\nYear Group:" + str(UserYearGroup))
print(UserYearGroup)
password = raw_input("Enter a password which you will remember:")
userFile.write("\nPassword:" + password)
Or
Add another with open("user account .txt","w") as userFile: to wrap your other writes.