Accepting only letters as input [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My code is supposed to only accept letters (for example Jack would be accepted, and jack1 would not be accepted).
It prompts the user for their first and last name then stores them. Once I had written the code for the first name, I tested it to see if I had written the code correctly for the first name, but it kept giving me this error .
In the answers can you please show how to make this work with only numbers being allowed?
Code
import random
operators = ["+", "-", "*"]
def greeting(first_name, last_name):
print ("Hello", first_name + " " + last_name)
Play = input('Are you ready to begin?')
if Play == 'yes':
print("Great", first_name + ", lets begin")
else:
greeting(first_name, last_name)
def Players_input():
print ("Welcome to the Arithmetic Quiz")
first_name = input("Please enter your first name: ")
if all(x.isalpha() or x.isspace() for x in first_name):
last_name = input("Please enter your last name: ")
greeting(first_name, last_name)
else:
print("Only alphabetical letters and spaces: no")
Players_input()
score = 0
for i in range(10):
first_number = random.randint(1,12)
second_number = random.randint(1,12)
op = random.choice(operators)
print (first_number, op, second_number, " = ?")
users_answer = int(input())
if op == "+":
right_answer = first_number + second_number
elif op == "-":
right_answer = first_number - second_number
elif op == "*":
right_answer = first_number * second_number
if users_answer == right_answer:
print("Well Done!")
score += 1
else:
print ("Sorry but thats the wrong answer, the right answer is: " + str(right_answer) + ". Better luck next time")
print (first_name, "Your final score in the Arithmetic Quiz is", str(score), "out of 10")

The answer for the first problem:
You never defined first_name outside of Players_input. This value is just stored inside the function, and get's deleted afterwards. (more about this in the link added by gjttt1)
There are two ways to solve this:
You could make first_name global. But this is a bad style, so I wouldn't use this option. You would add global first_name at some point in Players_input, before it is written to (so either before or directly after the first print call)
You could return first_name, this is the preferred way. Add a return first_name at the end of Players_input, and replace Players_input() with first_name = Players_input().
The answer to the second problem:
Just use this function instead of int(input()) (replace this line with int_input()):
def int_input(prompt="", error_message="You didn't enter an integer!"):
while True: # repeat this until the function returns
inp = input(prompt) # get the input after autputting the prompt.
try: # Try to...
return int(inp) # turn it into an integer. If it works, return it.
except ValueError: # If it didn't work, it raised a ValueError. In this case...
if error_message: # print the error_message if it is not "", false or None.
print(error_message)
Then you have a third problem: You should just use lowercase letters in function names, to distinguish them from classes. This is just about your style, but it'll certainly help to develop a good, clear coding style.
I hope I could help,
CodenameLambda

The first_name variable is out of scope when you are trying to use it. It belongs to the Players_input() function.
Read this article on scoping to get more of an idea of what is happening

Look at the error. It's telling you that the first_name variable is not defined. This is because it is a local variable in the Players_input function and cannot be used elsewhere. Variables that are defined inside a function are put on the stack in memory and are destroyed when that stack frame is pushed off the stack. You call this 'going out of scope'.
I recommend that you look up information about the scope of variables.

you can declare first_name=('hi') earlier in the code and then when you call it in as an input function you can write it like:
first_name=str(input('Please enter your first name: '))

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

Importing Variables from other functions

I've tried searching and trying suggestions people made for others but its not working for me, here is my code:
def CreateAccount():
FirstName = input('What is your first name?: ')
SecondName = input('What is your second name?: ')
Age = input('How old are you?: ')
AreaLive = input("What area do you live in?: ")
return FirstName, SecondName, Age, AreaLive
def DisplayAccountInfo(FirstName,SecondName,Age,AreaLive):
print("Your Firstname is",FirstName)
print("Your Secondname is",SecondName)
print("You are",Age," years old")
print("You live in the",AreaLive," area")
return
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo()
while True:
ConfirmAccountF()
So its just supposed to run indefinitely for now, but what I want it to do is pass the variables from 'CreateAccount' into 'DisplayAccountInfo'.
When I press anything other than n for 'ConfirmAccount' I get that the variables are undefined.
If I set it manually in 'DisplayAccountInfo()' then it doesn't throw any errors.
This is just me messing about and trying to understand python, if anyone can help that would be great.
Use the unpacking operator, *:
DisplayAccountInfo(*CreateAccount())
What this does is takes the tuple of four strings returned by CreateAccount and converts them into four arguments to be passed as separate parameters to DisplayAccountInfo. Whereas if you omitted the * operator and just called DisplayAccountInfo(CreateAccount()), that would pass a single tuple argument to DisplayAccountInfo, resulting in a TypeError exception (because DisplayAccountInfo expects four arguments, not one).
Of course if you also need to save the strings returned from CreateAccount for later use, you'll need to do that in between calling CreateAccount and DisplayAccountInfo.
The variable you declared on CreateAccount() can't be accesed by its name from the outside. To pass the information to another function you need to store its values first:
first_name, second_name, age, area = "", "", "", ""
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
first_name, second_name, age, area = CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo(first_name, second_name, age, area)

An arithmetic Quiz and writing to a csv [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am creating an arithmetic quiz, but my code isn't writing the scores to a csv file in excel. Can you help me? What do I need to fix?
I have 3 blank csv files, but there is not data in them.
Here's my code...
import random#this imports random numbers
import csv#this imports a csv
score=0#this sets the score to be 0 at the start
answer=0#this sets the answer to be 0, before it is formatted with the different questions
operators=("+","-","*")#this gives three options to select from for a random operation in each question
valid=('gold','platinum','diamond')
#_______________________________________________________________________________________________________________________________
def main():
global student_name
global class_name
print("ARITHMETIC QUIZ")#this prints the title "ARITHMETIC QUIZ"
student_name=input("\nWhat is your name? ")#this asks the user to input their name
#it stores the student's name in the variable 'student_name'
class_name=input("What class are you in? ")#this asks the user to input their class name
#it also stores the class name in the variable 'class_name'
if class_name=="gold":
quitting()
elif class_name=="platinum":
quitting()
elif class_name=="diamond":
quitting()
else:
print("That is not a valid class name")
print("Please choose from 'gold', 'platinum' or 'diamond'")
class_name=input("Please enter your correct class name below: \n")
#_______________________________________________________________________________________________________________________________
def quitting():
quitting=input("\nDo you want to exit the quiz? (enter 'yes' or 'no') ")
#this asks the users if they want to exit the program.
quitting = quitting.lower().replace(' ', '')
#this converts all the characters to lower case, and it also removes and spaces
if quitting=='yes':#this checks if they wrote 'yes'
print("The program will end.")
#if they did write yes, the above line of text will be printed
exit()#and then the program will end.
else:
quiz()
#_______________________________________________________________________________________________________________________________
def quiz():
global score
for i in range(10):
#this creates a forLoop that will repeat X times, depending on the number inside the brackets
#in this case, it will repeat the following function 10 times
num1=random.randint(1,20)#this chooses a random number for the variable num1
num2=random.randint(1,20)#this chooses a random number for the variable num2
operator=random.choice(operators)#this chooses a random operation from the options of '+','-' and '*'.
if operator=="+":
answer=num1+num2#if the operator was '+', the answer would be the sum of num1 and num2
elif operator=="-":
num1,num2 = max(num1,num2), min(num1,num2)#this makes num1 larger than num2 to make subtraction easier
answer=num1-num2#else if the operator was '-', the answer would be num1 takeaway num2
elif operator=="*":
answer=num1*num2#else if the operator was a '*', the answer would be the product of num1 and num2
try:
temp=int(input("\nWhat is " + str(num1) + operator + str(num2) + "? "))#the variable temp changes for each inputted answer
#this converts the integers 'num1' and 'num2' into strings
#because integers and strings can't be in the same line of code
#this asks the user the question
if temp==answer:#this cheks if the answer is correct
print("Well Done " + student_name + "! The answer is correct.")
score=score+1
#if it is correct, it will print "Well Done! The answer is correct".
#it will also add 1 to the score
else:
print("Incorrect. The answer was " + str(answer))#this converts the variable 'answer' into a string
score=score#this makes sure that the score remains the same as last time
#if the answer is not correct, it will print "Incorrect" and output the correct answer
except ValueError:
print("Invalid answer. Please use integers only!")
#this will be printed if the user inputted anything other than an integer, like a string
print("\nThank you " + student_name + "! You scored " + str(score) + " out of 10 in this quiz.")
#this converts the variable 'score' into a string
#and this prints thank you and the student's score out of ten
#_______________________________________________________________________________________________________________________________
def find_user_in_class():
if class_name == 'gold': #if what the user's input for the class name was 'gold'...
appendFile = open('goldclassscores.csv', 'a') #it opens the csv file, named 'goldclassscores'
elif class_name == 'platinum':#if what the user's input for the class name was 'platinum'...
appendFile = open('platinumclassscores.csv', 'a')#it opens the csv file, named 'platinumclassscores'
elif class_name == 'diamond':#if what the user's input for the class name was 'diamond'...
appendFile = open('diamondclassscores.csv', 'a')#it opens the csv file, named 'diamondclassscores'
for line in appendFile: #looks through each column of the csv
user = {}
(user['student_name']) = line.split
if student_name == user['student_name']:
appendFile.close()
return (user)
appendFile.close()
return({})
#_______________________________________________________________________________________________________________________________
def write_to_csv():
if class_name == 'gold':
goldcsv = open('goldclassscores.csv', 'a')
goldcsv.write('\n')
goldcsv.write(student_name)
goldcsv.write(str(score))
goldcsv.close()
print('Your score has been saved.')
elif class_name == 'platinum':
platinumcsv = open('platinumclassscores.csv', 'a')
platinumcsv.write('\n')
platinumcsv.write(student_name)
platinumcsv.write(str(score))
platinumcsv.close()
print('Your score has been saved.')
elif class_name == 'diamond':
diamondcsv = open('diamondclassscores.csv', 'a')
diamondcsv.write('\n')
diamondcsv.write(student_name)
diamondcsv.write(str(score))
diamondcsv.close()
print('Your score has been saved.')
#_______________________________________________________________________________________________________________________________
if __name__=="__main__": main()
Please help me!!
You are not calling your write_to_csv() function anywhere. Try calling it when the quiz is done.

Appending variable to text file not working in Python

I am trying to get my program to output two variables to a text file after it finishes running something but all I get is the folder and no text files inside of it. Here is the code in question:
I have edited to include the entire program.
import random #needed for the random question creation
import os #needed for when the scores will be appended to a text file
#import csv #work in progress
answer = 0 #just to ensure a strage error isn't created by the input validation (since converting to a global variable isn't really needed)
global questionnumber #sets the question number to be a global variable so that
questionnumber = 0
global score
score = 0
global name
name = "a"
def check_input(user_input): #used to verify that input by user is a valid number
try: #the condition that does the checking
answer = int (user_input)
except ValueError: #what to do if the number isn't actually a number
return fail() #calls the failure message
return answer #sends the answer back to the rest of the program
def fail(): #the failure message procedure defined
print("That isn't a whole number! Try again with a different question") #tells the user what's going on
global questionnumber #calls the global variable for this procedure
questionnumber = questionnumber - 1 #allows the user, who made a mistake, a second chance to get it right
def questions(): #the question procedure defined
global name
name=input("Enter your name: ") #gets the user's name for logging and also outputting messages to them
print("Hello there",name,"! Please answer 10 random maths questions for this test!") #outputs welcome message to the user
ClassOfStudent=input("Which class are you in?") #gets the user's class for logging
finish = False
while finish == False: #only occurs if "finish" isn't set to true so that the questions asked don't exceed ten
global questionnumber #calls the global variable
global score
choice = random.choice("+-x") #uses the random function to choose the operator
if questionnumber < 10 | questionnumber >= 0: #validation to ensure the question number is within ten
number1 = random.randrange(1,12) #uses random numbers from the random function, above 1 and below 12
number2 = random.randrange(1,12) #same as the abovem for the second number
print((number1),(choice),(number2)) #outputs the sum for the student to answer
answer=check_input((input("What is the answer?"))) #asks for the student's answer
questionnumber = questionnumber + 1 #adds one to the numebvr of questions asked
if choice==("+"): #if the ramdomly generated operator was plus
correctanswer = number1+number2 #operator is used with the numbers to work out the right answer
if answer==correctanswer: #checks the studen't answer is right
print("That's the correct answer") #if it is, it tells the student
score = score + 1 #adds one to the score that the user has
else:
print("Wrong answer, the answer was",correctanswer,"!") #if the answer is wrong, it tells the student and doesn't add one to the score
if choice==("x"): #essentially the same as the addition, but with a multiplicatin operator instead
correctanswer = number1*number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
elif choice==("-"): #essentially the same as the addition, but with a subtraction operator instead
correctanswer = number1-number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
else: #if the number of questions asked is ten, it goes on to end the program
finish = True
else:
print("Good job",name,"! You have finished the quiz") #outputs a message to the user to tell them that they've finished the quiz
print("You scored " + str(score) + "/10 questions.") #ouputs the user's score to let them know how well they've done
#all below here is a work in progress
#Create a new directory for the scores to go in, if it is not there already.
if os.path.exists("Scores") == False:
os.mkdir("Scores")
os.chdir("Scores")
if ClassOfStudent==1: #write scores to class 1 text
file_var = open("Class 1.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==2: #write score to class 2 text
file_var = open("Class 2.txt",'w+')
file_var.write(name, score)
file_var.close()
if ClassOfStudent==3: #write score to class 3 text
file_var = open("Class 3.txt",'w+')
file_var.write(name, score)
file_var.close()
questions()
ClassOfStudent is a string rather than a number, so none of the code that writes to the file will get executed. You can easily verify that by adding a print statement under each if so you can see if that code is being executed.
The solution is to compare to strings, or convert ClassOfStudent to an i teger.
Use print(repr(ClassOfStudent)) to show the value and type:
>>> ClassOfStudent = input("Which class are you in?")
Which class are you in?2
>>> print(repr(ClassOfStudent))
'2'
Using input() in Python 3 will read the value in as a string. You need to either convert it to an int or do the comparison against a string.
ClassOfStudent = int(input("Which class are you in?")
should fix your problem.
first you have a problem with the "". you have to correct the following:
if ClassOfStudent==2: #write scores to class 1 text
file_var = open("Class 2.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==3: #write scores to class 1 text
file_var = open("Class 3.txt",'w+')
file_var.write("name, score")
file_var.close()
notice that I added the "" inside the write.
In any case, I think what you want is something like:
file_var.write("name %s, score %s"%(name,score)). This should be more appropriate.

How to save the users name and last 3 scores to a text file?

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score)
else:
print("Your answer is not correct")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score >= 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open("class%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()

Categories