Suppose that I get the values for valid, d ,sn from a function that I introduced in my program. Then I pass it through the following if statement in python to output the result.
I want the program to print the following statements:
print on if the sn >= 0 and 1<d <90.
print off-right if the sn<0.
print off-left if the d>=90
other than that, for anything that is not valid outputs unknown.
Here is what I wrote, how do I include d when checking the statement?
if valid:
if sn >= 0 and 1<d <90:
print(" on ")
else:
print("off")
else:
print("unknown")
if valid:
if sn >= 0 and d > 1 and d < 90:
print(" on ")
elif sn < 0:
print("off-right")
elif d >= 90:
print("off-left")
else:
print("unknown")
Not sure what you want. But most probably you want to do this i guess?
if valid:
if sn >= 0 and (d>1 and d<90):
print(" on ")
else:
if sn<0:
print("off-right")
elif d>=90:
print('off-left')
else:
print("unknown")
This is a self explanatory answer..
If you get confused by 1<d<90 then you can use what i did above
Related
I'm solving this problem.
My code works when I test it but it is failing the provided check with the error:
:( Little Professor accepts valid level // timed out while waiting for program to exit
It passes the three previous checks for invalid levels. Any insight to why this might be happening would help.
Here is my code:
def main():
level = get_level()
q=1
s=0
while q<=10:
try:
x = generate_integer(level)
y = generate_integer(level)
ans = x + y
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
pass
elif ans != eq:
c = 1
while c <= 2:
print('EEE')
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
break
else:
c += 1
if c == 3:
print('EEE')
print(f'{x} + {y} = {ans}')
q += 1
except EOFError:
pass
print(f'Score: {s}')
def get_level():
valid_inputs = (1,2,3)
while True:
try:
level = int(input('Level: '))
if level in valid_inputs:
return level
else:
pass
except ValueError:
pass
def generate_integer(level):
max = 10**level-1
min = 10**(level-1)
if level == 1:
min == 0
num = random.randint(min,max)
return num
main()
I ran your program (as-is) and found at least 1 problem. I'm not sure if it's why check50 flags that error, but you will need to fix it before it will pass. I entered Level: 1, then got a duplicate equation (4 + 5 = ). This violates a requirement buried under How to Test: "Your program should output 10 distinct problems" (emphasis mine). It's easy to miss - I didn't see it until someone mentioned it on the CS50P ED Forum.
Also, the last 2 lines of your program are supposed to be:
if __name__ == "__main__":
main()
Instead, only you have:
main()
Finally, this is an observation on your code structure. You have a lot of if statements for the 3 attempts to answer the question. It's overly complicated and kind of hard to follow. Hint: It can be simplified with another loop to prompt and check answers.
I am trying to make a encrypter, in a similar fashion to the enigma machine but no what I try, the variable "final_message" won't print anything but blank space
message = input("Please input a message. ").upper()
final_message = ""
shift = 0
rotor1 = ['D','M','T','W','S','I','L','R','U','Y','O',
'N','K','F','E','J','C','A','Z','B','P','G','X','O','H','V']
for i in range(len(message)):
if ord(message[i]) == 32:
final_message += "n"
else:
num = ord(message[i]) - 65 + shift
if num > 25:
num -= 26
final_message += rotor1[num]
shift+=1
print(final_message)
I pretty new to coding so I am wondering whether anyone can spot my mistake. I don't get any errors, my code just finishes without printing any letters
It seems the indentation of final_message += rotor1[num] should be at the same level as that of if num > 25. Like this -
if num > 25:
num -= 26
final_message += rotor1[num]
A friend of mine told me that she needs help with some homework, I owe her a favor so I said fine, why not. she needed help with a program that checks a sequence, if the sequence is made of the same 2 chars one after the other it will print "yes" (for example "ABABABAB" or "3$3$3$3:)
The program works fine with even length strings (for example "abab") but not with odd length one ("ububu")
I made the code messy and "bad" in purpose, computers is her worst subject so I don't want it to look obvious that someone else wrote the code
the code -
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i <= len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
if i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
I hope someone will spot the problem, thanks you if you read everything :)
How about (assuming s is your string):
len(set(s[::2]))==1 & len(set(s[1::2]))==1
It checks that there is 1 char in the even locations, and 1 char in the odd locations.
a) Showing your friend bad and messy code makes her hardly a better programmer. I suggest that you explain to her in a way that she can improve her programming skills.
b) If you check for the character at the even position and find that it is good, you increment i. After that, you check if i is odd (which it is, since you found a valid character at the even position), you check if the character is valid. Instead of checking for odd position, an else should do the trick.
You can do this using two methods->
O(n)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 2
while i < len(StringInput):
l=StringInput[i]
if(l==StringInput[i-2]):
GoodOrBad=True
else:
GoodOrBad=False
i+=1
if GoodOrBad == True:
print("yes")
elif GoodOrBad == False:
print("no")
main()
Another method->
O(1)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = set(StringInput[0::2])
L2 = set(StringInput[1::2])
if len(L1)==len(L2):
print("yes")
else:
print("no")
main()
There is a lot in this that I would change, but I am just showing the minimal changes to get it to work. There are 2 issues.
You have an off by one error in the code:
i = 0
while i <= len(StringInput):
# in the loop you index into StringInput
StringInput[i]
Say you have 5 characters in StringInput. Because your while loop is going from i = 0 to i < = len(StringInput), it is going to go through the values [0, 1, 2, 3, 4, 5]. That last index is a problem since it is off the end off StringInput.
It will throw a 'string index out of range' exception.
You need to use:
while i < len(StringInput)
You also need to change the second if to an elif (actually it could just be an else, but...) so you do not try to test both in the same pass of the loop. If you go into the second if after the last char has been tested in the first if it will go out of range again.
elif i % 2 != 0:
So the corrected code would be:
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i < len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
elif i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
def main():
StringInput = input('your string here - ')
MaxLength = len(StringInput) // 2 + (len(StringInput) % 2 > 0)
start = StringInput[:2]
chained = start * MaxLength
GoodOrBad = chained[:len(StringInput)] == StringInput
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
I believe this does what you want. You can make it messier if this isn't bad enough.
I am trying to increase the correct answer count by 1 every time the users answer is correct. However, when parsed into the display_result() function, the correct function displays "0 correct"
I haven't been able to get this working no matter how I try to wiggle around it, so any help is really appreciated.
code removed for academic integrity
If the user has answered 1 of 3 questions correctly, I expect the answer to be "You have answer 1 questions out of 3 correctly."
Currently, it would display you have answered 0 questions out of 3 correctly"
In menu_option() you never modify count, so it stays at 0. Two simple fixes. Change to:
count = check_solution(user_solution, real_solution, count)
return count
Or just
return check_solution(user_solution, real_solution, count)
One other thing I noticed: in get_user_input() you need to return the result of the recursive calls:
else:
print("Invalid input, please try again")
return get_user_input()
There are a number of problems:
you are doing correct = menu_option(option, correct) when instead you should be accumulating the correct scores like correct +=
in the menu_option you are never assigning to count, I presume it should be count = check_solution(...)
you shouldn't do return option for index == 5 because that will add to the correct.
Finally the code run as I expected(python3.6+ is required):
#!/usr/bin/env python3
import random
def get_user_input():
while True:
try:
index = int(input("Enter your choice: "))
if 0 < index < 6:
return index
except ValueError:
print("Invalid input, should be Integer.\n")
else:
print("Invalid input, please try again")
def get_user_solution(problem):
while True:
print("Enter your answer")
user_solution = input(f"{problem} = ")
try:
return float(user_solution)
except ValueError:
print("Invalid input, should be float\n")
def check_solution(user_solution, solution, count):
if user_solution == solution:
print("Correct.")
return count + 1
else:
print("Incorrect.")
return count
def menu_option(index, count):
first_num = random.randrange(1, 21)
second_num = random.randrange(1, 21)
if index == 1:
problem = f"{first_num} + {second_num}"
real_solution = first_num + second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 2:
problem = f"{first_num} - {second_num}"
real_solution = first_num - second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 3:
# blah blah blah, repeated code but removed for neatness
pass
if index == 5:
option = 5
return option
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct")
print("Your score is 0.0%")
else:
percentage = round(correct / total * 100, 2)
print(
f'You answered {total} questions with {correct} correct.\n'
f'Your score is {percentage}%'
)
def display_intro():
pass
def display_menu():
pass
def display_separator():
print('-'*20)
def main():
display_intro()
display_menu()
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
if __name__ == "__main__":
main()
I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()
You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.
n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?
Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).