Writing to file using data from variables - python-3.x

import random # imports the random module
user_class = "" # Global variable
question_counter = int(0) # sets counter
amount_correct = int(0) # sets score
possible_operators = ("+","-","x") # creates a list of operators
while user_class == "": # Indefinite iteration - Runs until a valid class is given
user_class = str(input("Please enter your class"))
if user_class == "Rainbow": # Testing variable class - Will not crash the program
class_file = open("RainbowClass.txt","a")
elif user_class == "Sun":
class_file = open("SunClass.text","a")
elif user_class == "Moon":
class_file = open("MoonClass.text","a")
else:
print("Not quite. Try again:")
user_class = ""
name = str(input("Please enter your name"))
while question_counter < 10: # Indeffinate iteration – number of questions
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators) # Chooses one of the operators from the list
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
print("What is the answer to ", num1," "+operator+"" ,num2,"?")
user_answer = int(input())
if user_answer == answer:
question_counter = question_counter + 1
amount_correct = amount_correct + 1
print("Correct!")
else:
print("Incorrect")
question_counter = question_counter + 1
final_score = amount_correct
print("Well Done! You scored",amount_correct,"out of",question_counter,".")
amount_correct = str(amount_correct)
class_file.write(user_class)
class_file.write(name)
class_file.write(amount_correct + "\n")
class_file.close
This is my code. It does not get any errors when I run it but I am trying to get the user's class and open a text file according to the input. The file is opening but when it comes to the bottom it is not writing the data from the quiz that is inside the variables that I want it to.
What is the solution to this?

Untested crack at this (sorry, Python is on another system). Ill break it up into chunks:
import random
# Got rid of your global 'user_class'
# Moved the counter(s) to local function variables
# Moved the operator options to local function variables
Now to tackle your first while, I would do:
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file
Keep this:
# Don't need to call str(); input() returns a 'str'
name = input("Please enter your name: ")
Now for the second while, a similar function:
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct
Lets put it all together, and see how we get the variables and then how to write them to your files:
import random
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file, user_class
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct, question_counter
class_file, user_class = get_class_file()
name = input("Please enter your name: ")
final_score, num_asked = get_score()
print("Well Done!\n"
"You scored " + str(final_score) + " out of " + str(num_asked) + ".")
# In all methods you called 'a' mode so set that here
# Using 'with open()' automatically closes the file after completion
with open(class_file, 'a') as f:
f.write(user_class + "\n")
f.write(name + "\n")
f.write(str(final_score) + "\n")
Let me know if anything comes up, errors and such. Again, wasn't able to test.

Related

Want to continue running the calculator after the answer

def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
Want to write a statement to continue running the calculator after the answer is shown as output. Example, 2.0 + 2.0 = 4.0
I want the code to ask 'Do you want to continue operations with 4? Type 'y' for yes and 'n' for no.'
And then let's say I enter the multiply operator again, and another number to do the calculation with, it should show, 4.0 * 2.0 = 8.0
Okay, as stated in the comments to your original question, you were super close. All you needed to do is wrap your logic in a loop so you can iterate over the items, which I do in my example below with a while True loop. Then outside of that loop, you needed to track a value that the user creates...for example:
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
# track this value out of loop so it isn't reset
tracked_value = None
# make a continuous loop...
while True:
# anything here will reiterate unless broken
# tracked_value will always be none unless the user opts to reuse it below...
if tracked_value is None:
num1 = float(input("Enter first number: "))
else:
# now we can turn num1 into the tracked value, the user wishes to reuse it
num1 = tracked_value
print(f'You opted to reuse the tracked value for number 1, which was: "{num1}"')
# always will be asked.
num2 = float(input("Enter second number: "))
# print options
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
# honestly I would alter your dict to remove the need for
# this huge conditional, but I didn't want to change too much
# ex: method = operations.get(operator, None)... if method not None: answer = method(num1, num2)
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator. Try again...")
# 'continue' so you don't hit the code below, this starts the loop again
continue
# now logic is done, ask if they wish to continue or break
should_continue = input(f"Do you want to continue your calculation with your current answer: '{answer}'? "
"Type 'y' for yes and anything else for no. ")
# logic to continue or not, remember continue starts the iteration over
if should_continue.lower() in ['y', 'yes']:
# assign the tracked value now the user wants it.
tracked_value = answer
continue
else:
print('Thanks for using my calulator. See you next time.')
# break out of the while loop, the user opts to exit.
break
except ValueError as ex:
print(f"Enter valid inputs: {ex}")
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
calculator()
should_continue = input("Do you want to continue your calculation with your current answer? Type 'y' for yes and 'n' for no. ")
if should_continue == 'y':
should_continue = True
else:
should_continue = False
print("Thank you for using the calculator.")
while should_continue:
calculator()
break

return statement | Python 3 beginner

num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
print(cal(num1, num2))
this code runs right but says "none" at the end why?
Your code actually works. The problem with your code is that when you call calc() inside the print function, it tries to look for value that might be provided within the calc function (via the return statement). Since you did not return any value within your function, the interpreter cannot find the correct "value" to print. Note that none is a data type in Python. To solve the problem you can just change the print statements inside the if...else statement to a return statement. This way, when the operator is provided by the user, it will compute the result and return the result to the calc()'s function caller.
Here is the complete version of what you are trying to achieve:
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "":
input("Nothing entered. Please enter an operator. ")
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404")
print(cal(num1, num2))
As you have not provided a value for your function to return the Python interpreter returns a value for you. So when your print() calls your function cal the function returns nothing or put another way returns a value of None and that's what your print() statement prints.
Compare your code with the following where a value is returned to the print() statement,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2, op):
if op == "*":
cal_val = num1 * num2
elif op == "/":
cal_val = num1 / num2
elif op == "-":
cal_val = num1-num2
elif op == "+":
cal_val = num1 + num2
else:
cal_val = "Error 404"
return cal_val
print(cal(num1, num2, op))
Alternatively you could leave your code as it is and just call your cal() function without the print() wrapped around it. As below,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
cal(num1, num2)
Change your print statements in function to return statements, otherwise the function will be implemented, and it will print the result in console, but at your print statement you will get none.
because - when you use "Print" - you simply print a value in the console.
When you use "Return" - you get a value from a function.
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return(num1*num2)
elif op == "/":
return(num1/num2)
elif op == "-":
return(num1-num2)
elif op == "+":
return(num1+num2)
else:
return("Error 404")
print(cal(num1, num2))
Try this instead
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return num1*num2
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404"
print(cal(num1, num2))

Can`t exit from program

Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here
#import sys
def body_cycle(*args):
if option == "/":
error_func_for_zero(first_number, second_number, option)
print(division_option(first_number, second_number))
print()
print(begin)
def error_func_for_zero(*args):
try:
first_number / 0 or second_number / 0
except ZeroDivisionError:
print("YOU CANNOT DIVIDE BY ZERO!")
print(begin)
def division_option(*args):
return first_number / second_number
begin = " "
while begin:
print("Hello, I am calculator. ")
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")
print(body_cycle(first_number, second_number, option))
ask = " "
while ask:
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")
if exit_or_continue == "Y" or "y":
print("OK")
elif exit_or_continue == "N" or "n":
#break
ask == False
else:
print("Break program. ")
break
You just want to replace ask == False by ask = False.
In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:
def operation(a, b, option):
if option == "+":
return a + b
elif option == "-":
return a - b
elif option == "*":
return a * b
elif option == "/":
try:
return a / b
except ZeroDivsionError
return "YOU CANNOT DIVIDE BY ZERO!"
The rest can be put in a single loop instead of two, like so:
print("Hello, I am calculator. ")
while True:
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\n
Choose your option (+, -, *, /): ")
# Result.
print(operation(first_number, second_number, option))
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
Choice: ").lower()
if exit_or_continue == "y":
print("OK")
elif exit_or_continue == "n":
break

Novice Coder with issue properly looping

So I'm a novice coder having never coded before and am teaching myself Python on the guidance of my CS instructor. I'm walking myself through "Automating the Boring Stuff with Python" and I'm having issues with the Collatz sequence portion at the end of Chapter 3. I've got the sequence down but I'm having issues properly looping the code in order to get the result I want which is looping the sequence until the answer is == to integer 1. This is what I have and I would love some feedback and assistance.
def collatz(number): #defines the collatz sequence
if number%2 == 0:
num1 = number//2
else:
num1 = 3 * (number + 1)
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
num2 = collatz(num3)
if num2 == 1:
break
else:
num3 = collatz(num2)
print("ta da!")
You need this code:
def collatz(number):
if number % 2 == 0:
num1 = number//2
else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
num = collatz(num)
print(num)
if num == 1: break
print("ta da!"); input()

When comparing 2 variables output always the same

this is my code for a quiz with ten question.the problem is that whenever I write the answer (the answer gets printed before asking the question) it always say incorrect. please take into consideration that I am very bad at the language and don't correct what doesn't need to be fixed. Thankyou.
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(answer)
print(num1 ,symbal ,num2)
sanswer = input("= ?")
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(num1 ,symbal ,num2)
sanswer = int(input("= ?"))
print(answer)
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
2 mistake you have:
first: you shouldn't put print(answer) before input
second: you should sanswer = int(input("= ?")) use int() because what you take with input is string
and a simple suggestion try not to use global when coding.

Resources