Going to feel dumb once I figure this out.
The program I'm writing prompts for an operation (e.g. 9+3) and then prints the result.
Example run:
>>>Enter an operation: 9+3
>>>Result: 12
I'll have four separate functions for the operators +,-,*,/ and another function to receive the user input and print the result after the appropriate function return.
This is my code so far (I'm including only one operator function):
def add(n, y):
result = ""
result = n + y
return result
def main():
op = input("Enter an operation: ")
for i in range(1,len(op)):
n = n[0]
y = y[2]
if (i == "+"):
result = add(n, y)
print("Result: ", result)
print("Bye")
My error in the shell states n and y are not assigned so I'm not parsing them from the input correctly.
Because they are not assigned in the body of the function and not available in the global scope:
def main():
op = input("Enter an operation: ")
for i in range(1,len(op)):
n = n[0] # no n here yet so n[0] won't work
y = y[2] # no y here yet so y[2] won't work
I think you aim to parse the input, and then use those values to perform addition, something like that:
def main():
op = input("Enter an operation: ")
i = op[1]
n = int(op[0])
y = int(op[2])
if i == "+":
result = add(n, y)
print("Result: ", result)
print("Bye")
But it will work only for one digit arguments, so you might think about some proper parsing using regex, but that's for another question.
There are problems with your code:
In main, at n = n[0], you don't have any n defined. So you will get an error. Same for y = y[2].
In add you are adding strings. So you will get '93' as the answer.
For the proper parsing use regex
Or if you want quick to work, less coding version (not recommended if you are learning)
Try this:
def main():
while True:
# just a variable used to check for errors.
not_ok = False
inp = input("Enter an operation: ")
inp = inp.replace('\t',' ')
for char in inp:
if char not in '\n1234567890/\\+-*().': # for eval, check if the
print 'invalid input'
not_ok = True # there is a problem
break
if not_ok: # the problem is caught
continue # Go back to start
# the eval
try:
print 'Result: {}'.format(eval(inp)) # prints output for correct input.
except Exception:
print 'invalid input'
else:
break # end loop
Some regex links: 1 2
Related
I have tried this several different ways, I am still fairly new to Python so go easy on me. I am trying to execute a script where the user can choose to import a list from a plaintext file, or input a list manually, and the script will return the median and mode of the data.
The problem I am having is that my median and mode functions are not recognizing the reference to the raw data, and the main function isn't recognizing the median and mode from their respective functions.
I guess it's safe to say I am not calling these functions correctly, but frankly I just dont know how. Any help here would be much appreciated.
def choice():
##Choose user input type
start = input("Please select your input method by typing 'file' or 'manual' in all lower-case letters: ")
# Import File Type
userData = []
if start == "file":
fileName = input("Please enter the file name with the file's extension, e.g. ' numbers.txt': ")
userData = open(fileName).read().splitlines()
return userData
userData.close()
# Manual Entry Type
elif start == "manual":
while True:
data = float(input("Please enter your manual data one item at a time, press enter twice to continue: "))
if data == "":
break
userData = data
return userData
# Error
else:
print("You have entered incorrectly, please restart program")
def median(medianData):
numbers = []
for line in (choice(userData)):
listData = line.split()
for word in listData:
numbers.append(float(word))
# Sort the list and print the number at its midpoint
numbers.sort()
midpoint = len(numbers) // 2
print("The median is", end=" ")
if len(numbers) % 2 == 1:
medianData = (numbers[midpoint])
return medianData
else:
medianData = ((numbers[midpoint] + numbers[midpoint - 1]) / 2)
return medianData
def mode(modeData):
words = []
for line in (choice(userData)):
wordsInLine = line.split()
for word in wordsInLine:
words.append(word.upper())
theDictionary = {}
for word in words:
number = theDictionary.get(word, None)
if number == None:
theDictionary[word] = 1
else:
theDictionary[word] = number + 1
theMaximum = max(theDictionary.values())
for key in theDictionary:
if theDictionary[key] == theMaximum:
theMaximum = modeData
break
return modeData
def main():
print("The median is", (median(medianData)))
print("The mode is", (mode(modeData)))
Welcome! I think you need to read up a bit more on how functions work. The argument when you define a function is a "dummy" local variable whose name matters only in the definition of a function. You need to supply it a variable or constant whose name makes sense where you use it. It is a very good analogy to functions in mathematics which you may have learned about in school. (Note that these points are not specific to python, although the detailed syntax is.)
So when you have def median(medianData) you need to use medianData in the definition of the function, not userData, and when you call median(somevar) you have to make sure that somevar has a value at that point in your program.
As a simpler example:
def doubleMyVariable(x):
return 2*x
How would you use this? You could just put this somewhere in your code:
print(doubleMyVariable(3))
which should print out 6.
Or this:
z = 12
y = doubleMyVariable(z)
print(y)
which will print 12.
You could even do
z = 36
x = doubleMyVariable(z)
which will assign 72 to the variable x. But do you see how I used x there? It has nothing to do with the x in the definition of the function.
I have a program I am trying to make which will either show all the factors of a number or say it is prime. It's a simple program but I have one main issue. Once it prints all of the factors of an inputted number, it always returns none. I have tried multiple ways to get rid of it but nothing works without screwing something else up. The code is below.
def mys(x):
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
print(mys(x))
That code is just for printing the factors but that is where the problem lies. The results I get after entering a number, in this case 20, are as follows:
2
4
5
10
None
No matter what I do, I can't get the None to not print.
So if you don't want the return value of mys (None) not printed, then don't print it:
mys(x)
In python, a function that has no return statement always returns None.
I guess what you are trying to do is calling the mys function, and not printing it.
Note that you should remove x parameter, because it is asked inside of the function.
def mys():
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
mys()
It would be better not to include user input and printing in your function. It would make it easier to test and to reuse:
def mys(x):
result = []
for i in range(2,x):
r = x % i
if r == 0:
result.append(i)
return result
x = input("Enter a number: ")
print(mys(x))
The task:
Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval(), and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated.
My code:
import math
def eval_loop(m,n,i):
n = raw_input('I am the calculator and please type: ')
m = raw_input('enter done if you would like to quit! ')
i = 0
while (m!='done' and i>=0):
print eval(n)
eval_loop(m,n,i)
i += 1
break;
eval_loop('','1+2',0)
My code cannot return the value of the last expression it evaluated!
Three comments:
Using recursion for this means that you will eventually hit the system recursion limit, iteration is probably a better approach (and the one you were asked to take!);
If you want to return the result of eval, you will need to assign it; and
I have no idea what i is for in your code, but it doesn't seem to be helping anything.
With those in mind, a brief outline:
def eval_loop():
result = None
while True:
ui = raw_input("Enter a command (or 'done' to quit): ")
if ui.lower() == "done":
break
result = eval(ui)
print result
return result
For a more robust function, consider wrapping eval in a try and dealing with any errors stemming from it sensibly.
import math
def eval_loop():
while True:
x=input('Enter the expression to evaluate: ')
if x=='done':
break
else:
y=eval(x)
print(y)
print(y)
eval_loop()
This is the code I came up with. As a start wrote it using the If,else conditionals to understand the flow of code. Then wrote it using the while loop
import math
#using the eval function
"""eval("") takes a string as a variable and evaluates it
Using (If,else) Conditionals"""
def eval_(n):
m=int(n)
print("\nInput n = ",m)
x=eval('\nmath.pow(m,2)')
print("\nEvaluated value is = ", x)
def run():
n= input("\nEnter the value of n = ")
if n=='done' or n=='Done':
print("\nexiting program")
return
else:
eval_(n)
run() # recalling the function to create a loop
run()
Now Performing the same using a While Loop
"using eval("") function using while loop"
def eval_1():
while True:
n=input("\nenter the value of n = ") #takes a str as input
if n=="done" or n=="Done": #using string to break the loop
break
m=int(n) # Since we're using eval to peform a math function.
print("\n\nInput n = ",m)
x=eval('\nmath.pow(m,2)') #Using m to perform the math
print("\nEvaluated value is " ,x)
eval_1()
This method will run the eval on what a user input first, then adds that input to a new variable called b.
When the word "done" is input by the user, then it will print the newly created variable b - exactly as requested by the exercise.
def eval_loop():
while True:
a = input("enter a:\n")
if a == "done":
print(eval(b)) # if "done" is entered, this line will print variable "b" (see comment below)
break
print(eval(a))
b = a # this adds the last evaluated to a new variable "b"
eval_loop()
import math
b = []
def eval_loop():
a = input('Enter something to eval:')
if a != 'done':
print(eval(a))
b.append(eval(a))
eval_loop()
elif a == 'done':
print(*b)
eval_loop()
Here is the directions for what I need to do:
You are to write a complete program that obtains three pieces of data and then process them. The three pieces of information are a Boolean value, a string, and an integer. The logic of the program is this: if the Boolean value is True, print out the string twice, once with double quotes and once without - otherwise print out twice the number.
Here is what I have so far:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
Can anybody help me out?
On stackoverflow, we're here to help people solve problems, not to do your homework, as your question very likely sounds… That said, here is what you want:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
if Boolean == "True":
print('"{s}"\n{s}'.format(s=String))
try:
print('{}\n{}'.format(int(Number)))
except ValueError as err:
print('Error you did not give a number: {}'.format(err))
if __name__ == "__main__":
main()
A few explanations:
Boolean is "True" checks whether the contained string is actually the word True, and returns True, False otherwise.
then the print(''.format()) builds the double string (separated by \n) using the string format.
finally, when converting the string Integer into an int using int(Integer), it will raise a ValueError exception that gets caught to display a nice message on error.
the if __name__ == "__main__": part is to enable your code to be only executed when ran as a script, not when imported as a library. That's the pythonic way of defining the program's entry point.
I like to add a bit of logic to ensure proper values when I do input.
My standard way is like this:
import ast
def GetInput(user_message, var_type = str):
while 1:
# ask the user for an input
str_input = input(user_message + ": ")
# you dont need to cast a string!
if var_type == str:
return str_input
else:
input_type = type(ast.literal_eval(str_input))
if var_type == input_type:
return ast.literal_eval(str_input)
else:
print("Invalid type! Try again!")
Then in your main you can do something like this!
def main():
my_bool = False
my_str = ""
my_num = 0
my_bool = GetInput("Give me a Boolean", type(my_bool))
my_str = GetInput("Give me a String", type(my_str))
my_num = GetInput("Give me a Integer", type(my_num))
if my_bool:
print('"{}"'.format(my_str))
print(my_str)
else:
print(my_num * 2)
I made a calculator in python but when I run it and do for example 123 and 321 I get 123321 instead of 444, What am I doing wrong?
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
input() returns string not number . That's why instead of addition , String concatenation is performed.
you need to use int(x) and int(y) for conversion.
use this statement answear = int(x) + int(y)
input returns a string, and when you combine two strings the result is what you are seeing.
>>> x = '123'
>>> y = '321'
>>> x+y
'123321'
So you need to convert them to an integer, like this:
answear = int(x) + int(y)
you can use this :
y=int(input())
This is because you are declaring it as a string. Use a = int(input()). This will cast it into an integer. If you want to insert a decimal number use the float data type.
input() accepts and returns a string object and you need to typecast this into an integer (or float) if you want to perform arithmetic operations on it. Performing a + operation on two strings merely concatenates them.
Instead of input(), use int(input()). This will tell Python that the user is about to enter an integer.
def main():
def add(x,y):
return x + y
def sub(x,y):
return x - y
def mult(x,y):
return x * y
def div(x,y):
return x / y
def remainder(x,y):
return x % y
repeat=True
while repeat:
select=int(input("please select any operation:-\n 1.ADD\n2.SUBTRACT\n3.MULTIPLY\n4.DIVIDE\n5.REMAINDER\nselect here:-"))
num1=int(input("Enter the first number"))
num2=int(input("Enter the second number"))
if select==1:
print(num1,"+",num2,"=",add(num1,num2))
elif select==2:
print(num1,"-",num2,"=",sub(num1,num2))
elif select==3:
print(num1,"*",num2,"=",mult(num1,num2))
elif select==4:
print(num1,"/",num2,"=",div(num1,num2))
elif select==5:
print(num1,"%",num2,"=",remainder(num1,num2))
else:
print("invalid input")
print("Do you want to calculate further?\n press y for continue.\n press any other key to terminate.")
repeat="y" in str(input())
if repeat=="y":
print("Ooo yeh! you want to continue")
else:
print("Tnakyou")
main()
This is a simple problem to fix. When adding to integers or doing any other operation including an input and an int you need to do this:
y = int(input())
x = int(input())
a = y+x
so this put into your code looks like this:
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = int(input())
print("Number 2")
y = int(input())
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)