I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far:
x = 0
y = 0
sign = '+'
def getnum(prompt, number):
number = input(prompt)
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
def calc(string, number1, number2, sign):
print string
print " "
if sign == '+' or 'plus':
a = x + y
elif sign == 'x' or '*' or 'times':
a = x * y
elif sign == '/' or 'divided by':
a = x / y
elif sign == '-' or 'minus':
a = x - y
print string, a
getnum("Enter first number: ", x)
getnum("Enter second number: ", y)
getsign("Enter sign: ", sign)
calc("The answer is: ", x, y, sign)
print x
print y
print sign
The problem with the functions. At the end, I get this:
The answer is: 0
0
0
+
I can't seem to get the two numbers at the end to change.
I give you few suggestions at the places where you have to change your code, these will certainly make your program work given you know how functions work in python (in genral any language)
def getnum(prompt, number):
number = input(prompt)
The variable 'number' is local to that function. So every time you call the function "getnum" you assign a value to the number but what else do you do with that.
**Hint 1: A mechanism where as soon as you get the number, try throwin this number to a variable which can use it. Try using return.
**Hint 2: When you use input, by default the value entered will be converted into a string. So think of a method where the value will be changed from string to int. "casting"?
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
print sign
Directly prints the sign to the console, just think of a situation where your program can use the sign. I will give the same hint.
**Hint: Try using return.
Python does not have "call by name". C does. Python does not.
A function evaluation like this:
getnum("Enter first number: ", x)
Will never assign a new value to x in Python. In C, a new value can be assigned. In Python a new value cannot be assigned this way.
[A value can be mutated, but that's not relevant to this question.]
There are a number of issues.
Let's look at them in the interactive Python interpreter, which is an invaluable tool when you're experimenting with Python.
Firstly, getnum() doesn't do what you think it does...
>>> def getnum(prompt, number):
... number = input(prompt)
...
>>> x = 0
>>> getnum("Enter first number: ", x)
Enter first number: 6
>>> print x
0
Here you should return the value and capture it in a variable.
>>> def getnum(prompt):
... return input(prompt)
...
>>> x = 0
>>> x = getnum("Enter first number: ")
Enter first number: 6
>>> print x
6
getsign() has a similar issue.
Moving onto calc(). Here or isn't doing what you expect:
>>> sign = '*'
>>> if sign == '+' or 'plus':
... print 'plus'
...
plus
This needs to look more like:
>>> sign = '*'
>>> if sign == '+' or sign == 'plus':
... print 'plus'
... else:
... print 'not plus'
...
not plus
Or better still:
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
not plus
>>> sign = '+'
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
plus
The other conditions in this function have the same issue.
I'm inclined to treat this like a "homework" problem and tell you what you're doing wrong rather than show you the exact solution. When you take your inputs using input(prompt), you are getting a string. If you want to treat it as a number, you need to tell Python that explicitly.
I asume this is for the school, so this maybe can help you.
#!/usr/bin/env python
import re
#put the logic in an object like enviroment
class CalculatorProto(object):
def __init__(self, numberone, numbertwo):
"""
initialize the data
"""
self.firsn = numberone
self.twon = numbertwo
def Verifynumber(self):
"""
verify is you pass abs numbers
"""
numbers = re.compile("^[0-9]+$")
if numbers.search(self.firsn) and numbers.search(self.twon):
self.firsn = int(self.firsn)
self.twon = int(self.twon)
return True
else:
return False
def sum(self):
"""
manage sum
"""
rsum = self.firsn + self.twon
return rsum
def rest(self):
"""
manage rest
"""
if self.firsn > self.twon:
rrest = self.firsn - self.twon
return rrest
else:
rrest = self.twon - self.firsn
return rrest
def div(self):
"""
manage div
"""
if int(self.firsn) > int(self.twon):
if self.twon != 0:
rdiv = self.firsn / self.twon
return rdiv
return "Is not good idea div a number by 0"
else:
if self.firsn != 0:
rdiv = self.twon / self.firsn
return rdiv
return "Is not good idea div a number by 0"
def mul(self):
rmul = self.firsn * self.twon
return rmul
if __name__ == "__main__":
#here you cant write you small interface
print "Enter two numbers, and a operation please"
o = raw_input("One: ")
t = raw_input("Two: ")
operation = raw_input("Operation: ")
while operation not in ("sum", "div", "rest", "mul"):
print "WTF?? Enter a valid operation"
print "sum\ndiv\nrest\nor mul"
operation = raw_input("Operation: ")
cal = CalculatorProto(o, t)
if cal.Verifynumber():
exec("print cal.%s()" % operation)
else:
print "Please insert absolute numbers"
You cant modify this, for a more complex manage.
Related
How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.
I know this seems like it should be very simple, but at this point I'm at my wit's end trying to figure this out. I've coded up a calculator in python, but for some reason the ending if-else statement is only firing the else segment.
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x / y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
When I run this code, I get two different problems:
If I enter a valid input (ie: 2 + 2), then my output is
"2 + 2 = 4.0"
"2 + 2 = 4.0"
"2 + 2 = 4.0"
repeating forever.
If I enter an invalid input, I get the "Play again? " Prompt, but
no matter what I enter, the else statement fires.
(for instance, in the case that I enter "yes" into "Play again? ", it will print:
"yes" (<-- this is from "print again" line )
"no'd" (<-- this is from "else: print "no'd" )
I dont know how to solve either of these problems at this point, so any help would be greatly appreciated.
Edit: Thank you everyone, I wish I could check mark all of you for helping me understand different things about what I did wrong.
In while valid == True:, you never change the value of valid, so it's always True and the loop is infinite. I don't see why it's even a loop - change it to if like the blocks above it and it will behave as expected.
Also, in if again == ("yes", "y", "YES", "Yes","yes"):, change == to in and it will behave as expected.
Perhaps you should replace this code:
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
With this...
if valid:
Or...
while valid == True:
# Insert your previous code here.
break
You could also just simply set valid to false at the bottom of your loop too. That would work.
I think valid is constantly true in this case. You have also written while valid is true, which means it will keep iterating over the loop until valid is equalled to false. It appears that within this block of code in the while loop, valid isn't switched to false.
while valid == True: should probably be if valid == True
and for your second problem:
if again == ("yes", "y", "YES", "Yes","yes"): should probably be:
again = again.lower();
if again == "yes" or again == "y":
Your answer is looping because of
while valid == True:
Replace the loop with the if statement
You get "no'd" because of
if again == ("yes", "y", "YES", "Yes", "yes"):
Here you are equating string with a tuple, instead of checking whether the string is contained within a tuple. Try this instead:
if again in ("yes", "y", "YES", "Yes""):
I am using python 3 and need to print the final result from within the function(this is not optional). Instead it is printing every time it goes through the function.
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
print(result)
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplay(number)
main()
If you enter 12345 it prints out
21
321
4321
54321
I want it to print out 54321
The following worked for me (after I found a Python 3 interpreter online):
def reverseDisplay(n):
tmp = n % 10 # Determine the rightmost digit,
print(tmp, end="") # and print it with no space or newline.
if n == tmp: # If the current n and the rightmost digit are the same...
print() # we can finally print the newline and stop recursing.
else: # Otherwise...
reverseDisplay(n // 10) # lop off the rightmost digit and recurse.
If you need to return the reversed value in addition to printing it:
def reverseDisplay(n):
tmp = n % 10
print(tmp, end="")
if n == tmp:
print()
return tmp
else:
return int(str(tmp) + str(reverseDisplay(n // 10)))
You just need to move your print statement out of the reverseDisplay and into main:
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return result
def main():
number = 12345
print reverseDisplay(number)
main()
If you really need to print it in the recursive function, you'll have to add a parameter (called first in this example) to make sure you only print the first time:
def reverseDisplay(number, first=True):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10, False)))
if first:
print(result)
return result
Try this:
def reverseDisplayPrinter(number):
print reverseDisplay(number)
def reverseDisplay(number):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplayPrinter(number)
main()
There was no problem until I tried to make an input go through validity check and if invalid ask again for input
i'm counting on you for ideas thanks in advance :)
a=0
def reinp(a,b):
while True:
if a in [1,2,3,4,5,6]: #checking for valid input
return int(a)
break
a=input(b)
else:
return print("error")
tried, not working either
def reinp(a,b):
for c in [1,2,3,4,5,6]:
if int(c)==int(a):
return int(a)
break
else:
a=input(b)
a=reinp(a,'Test: ')
This one is the first to make a problem
def reinp2(a,b): #trying to check if it's a number and can be turned to float if not ask again
while check(a):
a=input(b)
return float(a)
def check(a):
try:
float(a)
return False
except ValueError:
return True
Right now the problem is after the check it never breaks free from any while loop
i tried in place of while True:if...break,
while correct:
if... correct=False
didn't work
and it just asks again and again even a condition is met...
there is no raw_input in python 3.2 so i can't use that either
reinp2() is there so if there a solution found for reinp() the same could apply for reinp2() as well a and b are just variables ans[n]=reinp2(ans[n],"Input n: ") the same with reinp() just for another type of variable (one that can be float as well)
The code as it is now show no syntax errors
P.S. i'm using Python 3.2
[EDIT: Deleted original answer, since no longer relevant with fixed formatting on question]
The problem with reinp is that a will be a string, and you're checking it against integers.
...so change:
if a in [1,2,3,4,5,6]: #checking for valid input
to:
if a in ['1','2','3','4','5','6']: #checking for valid input
If you still have a problem with reinp2, perhaps you can show some code that demonstrates the issue. It looks fine to me.
P.S. It's complete i just wanted all of you who helped to know it's running without is any glitches i even customized it so it could receive initial data :) if someone need a permutation solver you know where to find it :)
If someone wants the script:
from math import *
ans=['n','k','choice',0,0,0,0,0]
n,k=0,1
a=['''1 For Permutations P (from n) = n
2 For Variations V (k emelments from n-th class) = n!/(n-k)!
3 For Combinations C (k emelments from n-th class) = n!/(k!(n-k)!) = ( n )
4 Use last answer. ( k )
5 Second Memory
6 Clear memory
Your choice is : ''',
'''+ to add
- to substract
* to multiply
/ to divide
You will undertake?: ''',
"The answer is: "]
def perm():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
if ans[5]==0:
ans[3]=factorial(ans[n])
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def var():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def comb():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def ent():
global ans,a
ans[2]=reinp(ans[2],a[0])
if ans[2]==5:
if ans[3]!=0:
ans[7]=ans[3]
print(ans[7])
ent()
if ans[2]==6:
clear()
print("Done!")
ent()
if ans[3]==0 and ans[2]==4:
print('The memory is empty...')
ent()
elif ans[3]!=0 and ans[2]==4:
ans[3]=ans[3]
ans[5]=reinp1(ans[5],a[1])
if ans[5] == '+' :
ans[5]='add'
print("Adding")
elif ans[5] == '-' :
ans[5]='sub'
print("Substracting")
elif ans[5] == '*' :
ans[5]='mul'
print("Multiplication")
elif ans[5] == '/' :
ans[5]='div'
print("Dividing")
ans[2]='choice'
ent()
if ans[2]==1:
perm()
elif ans[2]==2:
var()
elif ans[2]==3:
comb()
clear1()
ent()
def ops(a,b,c):
if c=='add':
return a+b
if c=='sub':
return a-b
if c=='mul':
return a*b
if c=='div':
return a/b
def reinp(a,b):
while True:
a=input(b)
if str(a) in ['1','2','3','4','5','6']:
return int(a)
break
else:
print('There was an error please try again:')
def reinp1(a,b):
while True:
a=input(b)
if a in ["+", "-", "*", "/"]:
return a
break
def reinp2(a,b):
while check2(a):
a=input(b)
return float(a)
def check2(a):
try:
float(a)
return False
except ValueError:
return True
def clear():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ans[3]=0
ans[4]=0
ans[5]=0
ans[7]=ans[6]
ans[6]=0
def clear1():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ent()
Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description