My code does not run and i can't seem to get the score to print - xenocode

def tf_quiz():
user_name
user_year
print("Welcome to my true or false divison quiz") #welcome message
user_name=str(input("please enter in your name")) #asks/stores user input
user_year=str(input("please enter in your year")) #asks/stores user input
print("all you have to do is type T/F for each question") #explaning the task
print ("12/3 = 4") #asks the question
if correct_ans == "T" : #correct answer
print ("Correct!") #prints correct if the answer is correct
score = score +1
if correct_ans == "F" : #incorrect answer
print ("incorrect!") #prints incorrect if the answer is incorrect
print ("42/6 = 7")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print ("18/3 = 4")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("40/5 = 9")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("90/10 = 9")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print (" 16/2= 4")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("9/3 = 3")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print ("45/9 =5 ")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("81/9 = 7")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print("49/7 = 7")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :`enter code here`
print ("incorrect!")
#Main program
tf_quiz()
I can't print the name and score for the user using this code,
and it also does not run. I have tried multiple different things but i still cannot get it to work no matter what i do to try and fix it. the code also will not run and it will not give me any problems or ways to make it run.

Related

I can't figure out what is wrong and I am brand new to this

I'm just messing around and I can't figure out what is wrong
name = raw_input('What is your name?\n')
hi = raw_input('Are you having a good day, %s. \n' % name
if hi == "yes"
i == raw_input("great. \n")
if i = "thanks":
q = raw_input("you're welcome \n")
if q == "bye":
print("=)")
else:
print("Have a great day, Good Bye \n")
elif hi == "no":
n = raw_input("that is sad. hope your day gets better, %s \n" % name)
if n == "bye":
print("Good Bye, %s \n" % name)
else:
print("Hope your day gets better, Good Bye.")
else:
print(" ")
print(" ")
print(" Please enter yes or no.")
print(" *You need to restart the program")
it is saying invalid syntax for ( i == raw_input("great. \n") )
In python when you see invalid syntax for "whatever" check for the line above the "whatever"
so your problem is a missing : at the first if statement
if hi == "yes"
should be
if hi == "yes":
As stated in the comment, you're just missing a : after if hi == "yes".
This is a common error and the message points you to the line after the actual problem.

Really weird issue with CodeHS

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)

Want to terminate the program after giving the answer

I am Working on this BMI calculator code but when I run the program and enter all the values it gives the answer but keeps on repeating. I want that the program terminates after giving the answer.
I also want the answer to be in decimals.
here is the code:-
import math
print "*After Entering Every value Hit Enter"
time.sleep(2)
#intro Starts
name = raw_input("Please Enter Your Name : ") #enter your name
print""
print "Hello", name
time.sleep(0.5)
print""
print "It Feels Like Your Are Really Concerned About Your Health"
time.sleep(3)
print "So Lets Start Calculating Your BMI"
print "" #intro ends
#option for gender
gender = raw_input('Are you Male Or female ? ')
print "OK, Thats great"
print ""
#the bmi Calculation
kg = float(input('Enter Your Weight(in Kg.) : '))
cm = float(input('Enter Your height(in cm) : '))
print ""
meter = cm * math.pow(10, -2)
bmi = float(kg//(meter**2))
#the Conditions start
while gender == "male":
if bmi < 18.5: #if overweight
print "It seems like your are Underweight"
print "Your BMI is", bmi
print ("")
print "I prefer you To Increase Your diet."
#if normal
elif bmi >= 18.5 and bmi <= 25:
print "Your are Absolutely fine"
print "Your BMI is", bmi
print "Be on the same track"
#if overweight
elif bmi > 25 and bmi <=30:
print "Your are overweight "
print "Your BMI is", bmi
print "I prefer you to go for daily morning Jog."
#if obese
elif bmi > 30:
print "Your are under obese category"
print "Your BMI is", bmi
print "I prefer you to Change your diet"
while gender == "female" or "Female" :
print "sorry this program is under development"
print ("")
I will be thankful if somebody helps me.
I am A begineer
So you should try considering if instead of while if you don't want to repeat the process
import math
import time
print "*After Entering Every value Hit Enter"
time.sleep(2)
#intro Starts
name = raw_input("Please Enter Your Name : ") #enter your name
print""
print "Hello", name
time.sleep(0.5)
print""
print "It Feels Like Your Are Really Concerned About Your Health"
time.sleep(3)
print "So Lets Start Calculating Your BMI"
print "" #intro ends
#option for gender
gender = raw_input('Are you Male Or female ? ')
print "OK, Thats great"
print ""
#the bmi Calculation
kg = float(input('Enter Your Weight(in Kg.) : '))
cm = float(input('Enter Your height(in cm) : '))
print ""
meter = cm * math.pow(10, -2)
bmi = float(kg//(meter**2))
#the Conditions start
if gender == "male":
if bmi < 18.5: #if overweight
print "It seems like your are Underweight"
print "Your BMI is", bmi
print ("")
print "I prefer you To Increase Your diet."
elif bmi >= 18.5 and bmi <= 25:
print "Your are Absolutely fine"
print "Your BMI is", bmi
print "Be on the same track"
#if overweight
elif bmi > 25 and bmi <=30:
print "Your are overweight "
print "Your BMI is", bmi
print "I prefer you to go for daily morning Jog."
#if obese
elif bmi > 30:
print "Your are under obese category"
print "Your BMI is", bmi
print "I prefer you to Change your diet"
if gender in ("female" ,"Female" ): #gender == "female" or "Female" is always true
print "sorry this program is under development"
print ("")
Use break command to break your loop:
while gender == "male":
if bmi < 18.5: #if overweight
print "It seems like your are Underweight"
print "Your BMI is", bmi
print ("")
print "I prefer you To Increase Your diet."
#if normal
elif bmi >= 18.5 and bmi <= 25:
print "Your are Absolutely fine"
print "Your BMI is", bmi
break
Also , don't forget to add wait at the end of your loop so your program don't exit immediately after finishing:
import time
time.sleep(100)
Edit:
You edited the code so I also edited and improved your code:
while gender == "male":
if bmi < 18.5: #if overweight
print "It seems like your are Underweight"
print "Your BMI is", bmi
print ("")
print "I prefer you To Increase Your diet."
#if normal
elif bmi <= 25:
print "Your are Absolutely fine"
print "Your BMI is", bmi
print "Be on the same track"
#if overweight
elif bmi <=30:
print "Your are overweight "
print "Your BMI is", bmi
print "I prefer you to go for daily morning Jog."
#if obese
elif bmi > 30:
print "Your are under obese category"
print "Your BMI is", bmi
print "I prefer you to Change your diet"
break
while gender.lower() == "female":
print "sorry this program is under development"
print ("")
Edit2:
I just tried running your program. Your code has a lot of mistakes and bugs. You are not importing time whereas you are using it to wait. \n means newline. Rather than writing print "" you can simply write \n where you want a new line in your old print statement. If we write Male in the gender , then the conditions will not run. Try the following:
import math,time
print "*After Entering Every value Hit Enter"
time.sleep(2)
#intro Starts
name = raw_input("Please Enter Your Name : ") #enter your name
print "\nHello\n", name
time.sleep(0.5)
print "It Feels Like Your Are Really Concerned About Your Health"
time.sleep(3)
print "So Lets Start Calculating Your BMI\n"
#option for gender
gender = raw_input('Are you Male Or female ? ')
gender = gender.lower()
if gender != "male" and gender != "female":
print "Invalid Gender"
time.sleep(10)
quit()
print "OK, Thats great\n"
#the bmi Calculation
kg = float(input('Enter Your Weight(in Kg) : '))
cm = float(input('Enter Your height(in cm) : '))
print ""
meter = cm * math.pow(10, -2)
bmi = float(kg//(meter**2))
#the Conditions start
while gender == "male":
if bmi < 18.5: #if overweight
print "It seems like your are Underweight\nYour BMI is\n", bmi,"\nI prefer you To Increase Your diet."
elif bmi < 25:
print "Your are Absolutely fine\nYour BMI is", bmi,"\nBe on the same track\n"
elif bmi <=30 :
print "Your are overweight \nYour BMI is", bmi,"\nI prefer you to go for daily morning Jog."
elif bmi > 30:
print "Your are under obese category\nYour BMI is", bmi,"\nI prefer you to Change your diet"
break
while gender == "female":
print "Sorry! this program is under development"
break
print ("")

Error in Tic tac toe Program (Python)

The code shown below is that of a Tic tac toe game in which there are two players (Player1 and Player2 are humans). I have an issue in the if else statements in the "# Player 1 Plays now" and "# Player 2 Plays now" sections of the code. To be precise, the computer always thinks that every box is already filled with some value other than 1,2,3,4,5,6,7,8,9 and it keeps displaying the message "That cell is already marked. Please try another cell" defined in the nested else statement.
Can somebody enlighten me how to fix this problem ?
board = [0,1,2,3,4,5,6,7,8,9]
print type(board[1])
def board_invoke():
print "| ",board[1], " | ", board[2], " | ", board[3], " | ", "\n", "-------------------", "\n", "| ", board[4], " | ",board[5], " | ", board[6], " | ", "\n", "-------------------", "\n", "| ", board[7], " | ",board[8], " | ", board[9], " | "
def game_start():
Player1= raw_input("Select Player 1 between X or O : ")
if Player1 not in ('X','x','O','o'):
print "That is not an expected player"
game_start()
else:
print "\nSince you have selected Player 1 as %s" %Player1
print "\nThe Player 2 is assigned :",
if Player1 in ('X','x'):
Player2 = ("O")
else:
Player2 = ("X")
print Player2
print "\nThe game Starts now....\n"
board_invoke()
while (1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9) in board:
# Winning Condition
if board[1]==board[2]==board[3]==Player1:
print Player1," wins"
break
elif board[4]==board[5]==board[6]==Player1:
print Player1, " wins"
break
elif board[7]==board[8]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[2]==board[3]==Player2:
print Player2, " wins"
break
elif board[4]==board[5]==board[6]==Player2:
print Player2, " wins"
break
elif board[7]==board[8]==board[9]==Player2:
print Player2, " wins"
break
elif board[1]==board[5]==board[9]==Player1:
print Player1, " wins"
break
elif board[3]==board[5]==board[7]==Player1:
print Player1, " wins"
break
elif board[1]==board[5]==board[9]==Player2:
print Player2, " wins"
break
elif board[3]==board[5]==board[7]==Player2:
print Player2, " wins"
break
elif board[1]==board[4]==board[7]==Player1:
print Player1, " wins"
break
elif board[2]==board[5]==board[8]==Player1:
print Player1, " wins"
break
elif board[3]==board[6]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[4]==board[7]==Player2:
print Player2, " wins"
break
elif board[2]==board[5]==board[8]==Player2:
print Player2, " wins"
break
elif board[3]==board[6]==board[9]==Player2:
print Player2, " wins"
break
# Player 1 Plays now
Cell_no = raw_input("Player 1 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player1
board_invoke()
# Player 2 Plays now
Cell_no = raw_input("Player 2 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player2
board_invoke()
print "Do you want to play again ?"
user_decision = raw_input("Please type Yes or No : ")
if user_decision == ('YES' or 'Yes' or 'yes'):
game_start()
else:
print "Ok. I take it that we will wrap up !"
print "See you again !"
game_start()
Your if statement is not completely correct.
You are evaluating:
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
which is always true. The or keywords combines each comparison logically. The first compare statement would then simply be 'X', which is not null or 0 and therefor always true. As the first statement is true, the whole if-statement is true.
I see this quite often on people starting to learn programming. If-statements can't be written exactly like human sentences. You have to compare every single character to your variable.
Here is a simple (not python specific and quite ugly) solution to your problem:
else:
if 'X' == board[Cell_no] or 'x' == board[Cell_no] or 'O' == board[Cell_no] or 'o' == board[Cell_no]:
print "That cell is already marked. Please try another cell"
An even better approach though would be to turn that check around and compare it with a list:
else:
if board[Cell_no] in ['X','x', 'O', 'o']:
print "That cell is already marked. Please try another cell"

Trying to edit a txt file from a range of user inputs in python

me: I am very new to coding.
What i'm trying to do: Allow the user to change a txt files data. E.g. The name of a person, the email of a person, etc.
Problem: Code accepts my inputs however, it does not change the txt file.
Code i've made already.
click here for code
L = open("players.txt","r+")
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
for line in L:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
L.close() #Closes the file to free us usage space.
Text file i'm wanting to edit.
click here for text file
Im guessing I need to basically save over the existing text file with the new data that has been entered. The question is how?
Any help would be appreciated.
p.s. First time posting so i cannot post pictures as i don't have 10 reputation. My apologies.
You are never actully writing to the file:
https://docs.python.org/2/tutorial/inputoutput.html
Change "L.open" to write mode "w", use "L.write()" to write new data, this means you need to rewrite the data you don't want to change and construct and write new data where you wanted it to be modified.
Pseudo-code:
Open file
for line in file
if(line.name == selectedname):
write_row_edited(something)
else:
write_line_unedited()
close file
I took the time to insert the missing peudo-code
#we need to load file into memory, so we can edit it (rewrite it modified)
file = open("players.txt","r")
data = file.read()
file.close()
datalines = data.split("\n")
#now we have the file "line-by-line" in memory so we can edit it
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
file = open("players.txt","w")
for line in datalines:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
#merge string so we can write it back
newline = ",".join(strings)
file.write(newline+"\n")
else:
file.write(line+"\n")
file.close()