When I input my number or anything else, it just skips the if statement and goes to the else. I can't figure out what's wrong; I've tried every way to change it. Still a total noob here.
arv = input("Sisestage arv: ")
arv1 = 0
kordus = 1
while kordus <= 10:
arv = input("Sisestage arv: ")
if arv == arv.isnumeric():
arv1 + arv
print (arv1)
kordus += 1
else:
print (arv)
break
You do not need to check if arv == arv.isnumeric(). arv.numeric() returns a boolean (True or False). To add a number to a variable you need += not just +. Here is your fixed code:
arv = input("Sisestage arv: ")
arv1 = 0
kordus = 1
while kordus <= 10:
arv = input("Sisestage arv: ")
if arv.isnumeric():
arv1 += int(arv)
print (arv1)
kordus += 1
else:
print (arv)
break
You can use the isinstance() function to check if the input is an int or not
arv1 = 0
kordus = 1
while kordus <= 10:
arv = eval(input("Sisestage arv: "))
if isinstance(arv, int):
arv1 += arv
print(arv1)
kordus += 1
else:
print(arv)
print(arv1)
break
Related
new in python here,
I have a code which guesses number and it works fine. but what I want to add to it is when my guess is correct count down to 0,
I have this code :
num = 3
my_guess = ""
while my_guess != num:
my_guess = int(input("enter:"))
print ("great job")
where and how to I do it (with comment line if possible please )
thanks
Hopefully this isn't too much new information at once but import random if/else continue try/raise and formatted strings are certainly worth understanding.
import random # random module for PRNG
num = random.randint(0,9) # get int 0<=i<=9
count_wins = 0 # start counter for wins at 0
count_losses = 0 # start counter for wins at 1
while count_wins <= 3: # while count_wins is less than 3
try: # If an error occurs in this try block the except will be executed
my_guess = int(input("enter:")) # cast input to int and set to my_guess
if my_guess < 0 or my_guess > 9: # raise Value Error for ints out of range
raise ValueError # Raise Value Error
continue # go back to the top of the loop
except ValueError: # specify this except block is for ValueErrors
print("invalid input") # print invalid input
if(my_guess == num): # if you guessed correctly
print("great job") # print "great job"
num = random.randint(0, 9) # pick a new number
count_wins += 1 # increment counter
else: # if you guessed incorrectly
count_losses += 1 # increment counter
print(f"Wins: {count_wins}") # print wins
print(f"Losses: {count_losses}") # print losses
this is what I was looking for , in case someone else has a similar question
num = 3
my_guess = ""
while my_guess != num:
my_guess = int(input("enter:"))
print ("great job")
while num >=0:
print (num)
num = num -1
As a computer science student we were given an assignment to do binary search in python. I don't know what's wrong with my code everything seems just fine
when the searched item is in the middle everything works just fine but whenever I enter a different index position it gets stuck in the while loop.
def binary_search():
ordered_list = [0,1,2,3,4,5,6,7,8,9]
lower_bound = 0
upper_bound = 10
index = int((lower_bound + upper_bound) / 2)
item_f = int(input("please enter the number you want to find (1-10): "))
t = True
while t:
if ordered_list[index] == item_f:
print(f"number {item_f} is found at index position {index}")
t = False
elif item_f > ordered_list[index]:
lower_bound = index + 1
elif item_f < ordered_list[index]:
lower_bound = index - 1
if t == False:
print("number found")
else:
pass
binary_search()
I have added 1 line of code, please check it should working
def binary_search()
ordered_list = [0,1,2,3,4,5,6,7,8,9]
lower_bound = 0
upper_bound = 10
index = int((lower_bound + upper_bound) / 2)
item_f = int(input("please enter the number you want to find (1-10): "))
t = True
while t:
if ordered_list[index] == item_f:
print(f"number {item_f} is found at index position {index}")
t = False
elif item_f > ordered_list[index]:
lower_bound = index + 1
elif item_f < ordered_list[index]:
upper_bound = index - 1#Edit line
index = int((lower_bound + upper_bound) / 2) #Added line
if t == False:
print("number found")
else:
pass
binary_search()
inp = raw_input("Input a EAN-13 number.")
aaa = False
bbb = False
if len(inp) == 13:
bbb = True
else:
print "Error input"
exit
ean_number = int(inp)
def ean13(value_1):
mult_of_ten = 0
sum_of_digits = 0
done = False
for z in len(value_1):
if not z == 0:
if z % 2 == 0:
value_1[z] *= 3
elif not z % 2 == 0:
value_1[z] *= 1
for a in len(value_1):
sum_of_digits += value_1[a]
if sum_of_digits % 10 == 0:
result = 0
elif not sum_of_digits % 10 == 0:
while done == False:
mult_of_ten = sum_of_digits
for d in True:
mult_of_ten += d
if sum_of_digits % 10 == 0:
done == True
result = mult_of_ten - sum_of_digits
if result == value_1[12]:
print "True"
if bbb == True:
ean13(ean_number)
I really don't see why teacher can't help either.
I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work. Can anyone help?
I have made an EAN 13 Number Validity Checker in Python2.
Hope it helps you out.
# ean = '9780201379624'
ean = raw_input("Input a EAN-13 number:\n")
err = 0
even = 0
odd = 0
check_bit = ean[len(ean)-1]#get check bit(last bit)
check_val = ean[:-1]#Get all vals except check bit
if len(ean) != 13:#Check the input length
print "Invalid EAN 13"
else:
for index,num in enumerate(check_val):#Gather Odd and Even Bits
if index%2 == 0:
even += int(num)
else:
odd += int(num)
if ((3*odd)+even+int(check_bit)) % 10 == 0:# Check if the algorithm 3 * odd parity + even parity + check bit matches
print "Valid EAN 13"
else:
print "Invalid EAN 13"
I have a problem with this code, this program should keep allowing you enter students until the number of passes reaches 8 or the total number of students reaches 10. However currently it just keeps asking for input and hence there is an infinite loop. How do I go about fixing this?
total_students=0
student_passes=0
student_failures=0
while (total_students <= 10) or (student_passes != 8):
result=int(input("Input the exam result: "))
if result>=50:
student_passes = student_passes + 1
else:
student_failures = student_failures + 1
total_students = total_students + 1
print (student_passes)
print (student_failures)
if student_passes >= 8:
print ("Well done")
Change or to and. While both are true you continue:
total_students=0
student_passes=0
student_failures=0
while (total_students != 10) and (student_passes != 8): # != or <
result=int(input("Input the exam result: "))
if result>=50:
student_passes += 1
else:
student_failures += 1
total_students +=1
print (student_passes)
print (student_failures)
you might have to revisit your code. I m not python expert, however I believe you should modify the condition for while loop.
such as while (total_students <= 10) or (student_passes <= 8):
this will resolve your problem.
total_students=0
student_passes=0
student_failures=0
while (total_students <= 10) or (student_passes <= 8):
result=int(input("Input the exam result: "))
if result>=50:
student_passes = student_passes + 1
else:
student_failures = student_failures + 1
total_students = total_students + 1
print (student_passes)
print (student_failures)
if student_passes >= 8:
print ("Well done")
You should use and instead of or to meet your requirement.
total_students=0
student_passes=0
student_failures=0
while (total_students <= 10 and student_passes < 8):
result=int(input("Input the exam result: "))
if result>=50:
student_passes = student_passes + 1
else:
student_failures = student_failures + 1
total_students = total_students + 1
print (student_passes)
print (student_failures)
if student_passes >= 8:
print ("Well done")
MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1