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()
Related
I'm solving this problem.
My code works when I test it but it is failing the provided check with the error:
:( Little Professor accepts valid level // timed out while waiting for program to exit
It passes the three previous checks for invalid levels. Any insight to why this might be happening would help.
Here is my code:
def main():
level = get_level()
q=1
s=0
while q<=10:
try:
x = generate_integer(level)
y = generate_integer(level)
ans = x + y
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
pass
elif ans != eq:
c = 1
while c <= 2:
print('EEE')
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
break
else:
c += 1
if c == 3:
print('EEE')
print(f'{x} + {y} = {ans}')
q += 1
except EOFError:
pass
print(f'Score: {s}')
def get_level():
valid_inputs = (1,2,3)
while True:
try:
level = int(input('Level: '))
if level in valid_inputs:
return level
else:
pass
except ValueError:
pass
def generate_integer(level):
max = 10**level-1
min = 10**(level-1)
if level == 1:
min == 0
num = random.randint(min,max)
return num
main()
I ran your program (as-is) and found at least 1 problem. I'm not sure if it's why check50 flags that error, but you will need to fix it before it will pass. I entered Level: 1, then got a duplicate equation (4 + 5 = ). This violates a requirement buried under How to Test: "Your program should output 10 distinct problems" (emphasis mine). It's easy to miss - I didn't see it until someone mentioned it on the CS50P ED Forum.
Also, the last 2 lines of your program are supposed to be:
if __name__ == "__main__":
main()
Instead, only you have:
main()
Finally, this is an observation on your code structure. You have a lot of if statements for the 3 attempts to answer the question. It's overly complicated and kind of hard to follow. Hint: It can be simplified with another loop to prompt and check answers.
I'm relatively new to python and I'm looking for a way to make this code more efficient. Thank you!
import random
import string
import time
ques = []
anss = []
nums = string.digits
def que():
for i in range(10):
num0 = random.choice(nums)
num1 = random.choice(nums)
ans = num0 + '+' + num1
ques.append(ans)
ans = int(num0) + int(num1)
anss.append(ans)
global length
length = len(ques)
def main():
global counter
counter = 0
for i in range(10):
global answer
answer = int(input('What is ' + ques[i] + '?\n>>'))
if answer == anss[i]:
print('Correct!')
counter += 1
else:
print('Wrong!')
def score():
x = str((counter / length*100))
x = 'You got ' + x + '%'
return x
if __name__ == '__main__':
que()
main()
time.sleep(0.5)
print('Please wait while we calculate your score.')
time.sleep(1)
print(score())
Before, I tried just having the answers and questions in a single list - but after one loop it'd add one to the index something like this.
for i in range(10):
if answer == questions[i+1]:
print('correct')
i += 1 #This is meant to skip the answer part of the list and goto the next question but i couldnt get it to work.
Well... I just change your score method like
def score():
return 'You got ' + str((counter / length*100)) + '%'
In order to return the full string and avoid the x variable.
It is a little longer but what I think cleaner.
You can test each part without main.
main contains the algorithm.
from random import choice
from string import digits
def main() -> None:
score = 0
questions_limit = 10
for i in range(questions_limit):
first_operand = get_random_operand()
second_operand = get_random_operand()
expected_answer = first_operand + second_operand
question = get_question(first_operand, second_operand)
actual_answer = get_actual_answer(question)
correct = is_correct(expected_answer, actual_answer)
print_result(correct)
score = get_score(score, correct)
score_percentage = get_score_percentage(score, questions_limit)
print_score(score_percentage)
def get_random_operand() -> int:
return int(choice(digits))
def get_question(first_operand: int, second_operand: int) -> str:
return 'What is ' + str(first_operand) + ' + ' + str(second_operand) + ' ?\n>>'
def get_actual_answer(question: str) -> int:
return int(input(question))
def is_correct(expected_answer: int, actual_answer: int) -> bool:
return expected_answer == actual_answer
def print_result(correct: bool) -> None:
message = "Correct!" if correct else "Wrong!"
print(message)
def get_score(score: int, correct: bool) -> int:
if correct:
score +=1
return score
def get_score_percentage(score, questions_limit) -> str:
return str(score / questions_limit * 100)
def print_score(score: str) -> None:
print('You got ' + score + '%')
if __name__ == '__main__':
main()
If you were wanting to have the questions and answers in the same array then I would suggest doing something like:
for i in range(0,10,2):
if answer == questions[i+1]:
print("correct")
However the length of the array should be made to match having a question for each answer. The 2 at the end of range will mean the iterator(i) goes up by 2 each loop
It does not directly answer your question, but I'd suggest that you use the global keyword much less:
For answer you don't need it at all, because you use answer nowhere outside of main.
For length I would instead suggest you define length = 10 below nums at the top of your code and then replace all occurrences of 10 by length (which I would rather call n_questions).
That way you can easily change the number of questions with one single change of your code, and as you know that the loop in que will run up to length, there is no need to count length up.
Having counter global in main in okayish, although many would argue that it'd be better practice to return counter in main and define score to accept counter (better n_correct, for example) as argument like this (reusing Alfa Rojos answer):
def score(counter):
return 'You got ' + str((counter / length*100)) + '%'
I didn't completely rewrite it, but I would move everything to one loop, much cleaner for changes that way and have a counter that counts the number the user gets correct.
Here is a partial rewrite of your function que
def que():
for i in range(10):
num0,num1 = int(random.choice(nums)), int(random.choice(nums))
ans = num0 + num1
ques.append(ans)
anss.append(ans)
length = len(ques)
return length
I have to read the input and check if the number is actually a float or the string STOP. When I execute my program without the two commented out lines, the result is like this:
1.1
g=nan r=nan% s=nan
2.2
g=nan r=nan% s=nan
The code:
def CheckFloat(number):
try:
float(number)
return True
except ValueError:
return False
def read_input(period):
i = 0
info = []
nbr = []
diff = []
while True:
try:
# if not CheckFloat(input()) and input() != "STOP":
# exit(84)
info.append(input())
if info[i] == "STOP":
fnc_tendency(period, nbr)
else:
nbr.append(float(info[i]))
if i >= 0:
diff.append(nbr[i] - nbr[i - 1])
print_res(nbr, period, diff, i)
i += 1
except(EOFError, StopIteration):
exit(84)
But when I uncomment the two lines
# if not CheckFloat(input()) and input() != "STOP":
# exit(84)
the result looks like this:
1.1
2.2
g=nan r=nan% s=nan
I lose one line of printing, and I don't know why. Could someone help me through this please?
Your float function can be simplified quite a bit
def CheckFloat(n):
return type(n) == float
Otherwise, it looks like you're checking for input twice?
if not CheckFloat(input()) and input() != "STOP":
exit(84)
info.append(input())
# I think you intended to do something more like this:
val = input()
if CheckFloat(val) and val != "STOP":
# do something
else:
# do something
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'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.