Condition "and", "or" - python

I have a problem with my condition. I would like the variable tabPoint to be between 10 and 100.
Here is my code:
def demand(nb):
tabName = [];
tabPoint = [];
for i in range(nb):
tabName.append(raw_input("Name of the jumper " + str(i+1) + " : "))
tabPoint.append(input("1st jump " + tabName [i] + " The number must be between 10 and 100: " ));
if int (tabPoint[i] < 5 ) and int (tabPoint[i] > 100):
tabPoint.append(input("The number must be between 10 and 100 " ));
return tabName, tabPoint;
name, point = demand(3)
print(name, point)

You have misplaced your parentheses. What you want as an int is tabPoint[i], not tabPoint[i] < 5.
So the correct form is
if int(tabPoint[i]) > 5 and int(tabPoint[i]) < 100:
tabPoint.append(input("The number must be between 10 and 100 " ))
You can also use the short version that accomplishes the same:
if 5 < int(tabPoint[i]) < 100:
tabPoint.append(input("The number must be between 10 and 100 "))

Try this:
def demand(nb):
tabName = []
tabPoint = []
for i in range(nb):
tabName.append(input("Name of the jumper "+str(i+1)+": "))
tabPoint.append(0)
# Until a valid entry is made, this prompt will occur
while tabPoint[i] < 10 or tabPoint[i] > 100:
tabPoint[i] = (int(
input("1st jump "+tabName[i]+" The number must be between 10 "
"and 100: ")))
return dict(zip(tabName, tabPoint)) # Returning a dictionary mapping name to point
Say you wanted to print each name and point after this, you could implement something like:
info = demand(3)
for name, point in info.items():
print(f"Name: {name} Point: {point}")

Related

BinarySearch missing required positional arguments

Sorry - still new to Python, but having trouble with my code working. I can't really figure out where to move the declared variables and getting it to work. However, if I put them outside the function, the other functions are ignored and go straight to n's input request. Any way to fix this?
EDIT: Added the entire code and also the errors I am getting at the bottom, I don't know if this is a simple indentation error.
# menu selector
from tkinter.tix import Select
select = 0
def DisplayMenu() :
print ("enter your choice")
print ("1 for a Linear Search")
print ("2 for a Binary Search")
print ("3 for a Bubble Sort")
print ("4 for a Selection Sort")
print ("5 for a Insertion Sort")
def SelectRoutine() :
global select
DisplayMenu()
select = int(input())
if (select == 1) :
print ("Call the Linear Search Routine")
LinearSearch()
elif (select == 2) :
print ("Call the Binary Search Routine")
BinarySearch()
elif (select == 3) :
print ("Call the Bubble Sort Routine")
BubbleSort()
elif (select == 4) :
print ("Call the Selection Sort")
SelectionSort()
elif (select == 5):
print ("Call the Insertion Sort")
InsertionSort()
else :
print("invalid selection")
def LinearSearch() :
elements = [10, 20, 80, 70, 60, 50]
x = int(input("please enter the number to search: "))
found = False
for i in range(len(elements)) :
if(elements[i] == x) :
found = True
print("%d found at %dth position" % (x, i))
break
if (found == False) :
print("%d is not in list" % x)
def BinarySearch(n, sortedlist, x) :
start = 0
end = n - 1
for i in range(n) :
sortedlist.append(int(input("Enter %dth element: " % i)))
while(start <= end) :
mid = int((start + end) / 2)
if (x == sortedlist[mid]) :
return mid
elif(x < sortedlist[mid]) :
end = mid - 1
else :
start = mid + 1
return -1
n = int(input("Enter the size of the list: "))
sortedlist = []
x = int(input("Enter the number to search: "))
position = BinarySearch(n, sortedlist, x)
if (position != -1) :
print("element number %d is present at position: %d" % (x,position))
else :
print("element number %d is not present in the list" % x)
SelectRoutine()
enter your choice
1 for a Linear Search
2 for a Binary Search
3 for a Bubble Sort
4 for a Selection Sort
5 for a Insertion Sort
2
Call the Binary Search Routine
Traceback (most recent call last):
File "/Users/uglycode.py", line 68, in <module>
SelectRoutine()
File "/Users/uglycode.py", line 22, in SelectRoutine
BinarySearch()
TypeError: BinarySearch() missing 3 required positional arguments: 'n', 'sortedlist', and 'x'
Actual
You should pass n, sortedlist, position variables when you run BinarySearch function.
You should define variables n, sortedlist, position from out of the BinarySearch function.
Your indent under while loop is wrong. You should run binary search logic under your while function.
If you want to run BinarySearch function when you want, make it all to one function as run_binary_search()
If 1. and 2. are not modified, the code will fall into an infinite loop.
If you apply it to SelectRoutine() then, you should define def BinarySearch() function like it.
def BinarySearch():
def _binary_serach(n, sortedlist, x):
start = 0
end = n - 1
while (start <= end) :
mid = int((start + end) / 2)
if (x == sortedlist[mid]):
position = mid
break
elif(x < sortedlist[mid]):
end = mid - 1
else:
start = mid + 1
position = -1
if (position != -1) :
print("element number %d is present at position: %d" % (x,position))
else :
print("element number %d is not present in the list" % x)
return position
n = int(input("Enter the size of the list: "))
sortedlist = []
for i in range(n):
sortedlist.append(int(input("Enter %dth element: " % i)))
x = int(input("Enter the number to search: "))
position = _binary_serach(n, sortedlist, x)
return position

How to solve Luhn algoritm

there is a lot of information about how to write Luhn algortim. I'm trying it too and I think that I'am very close to succes but I have some mistake in my code and dont know where. The test card is VALID card but my algorithm says otherwise. Don't you know why? Thx for help
test = "5573497266530355"
kazde_druhe = []
ostatni = []
for i in test:
if int(i) % 2 == 0:
double_digit = int(i) * 2
if double_digit > 9:
p = double_digit - 9
kazde_druhe.append(p)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(i))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k
if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
Finally! Thank you all for your help. Now it is working :-)
test = "5573497266530355" kazde_druhe = [] ostatni = []
for index, digit in enumerate(test):
if index % 2 == 0:
double_digit = int(digit) * 2
print(double_digit)
if double_digit > 9:
double_digit = double_digit - 9
kazde_druhe.append(double_digit)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(digit))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
From this description
2. With the payload, start from the rightmost digit. Moving left, double the value of every second digit (including the rightmost digit).
You have to check the digit position, not the number itself.
Change to this:
for i in range(len(test)):
if i % 2 == 0:
This code works. :)
I fixed you code as much as i could.
test = "5573497266530355"
#test = "3379513561108795"
nums = []
for i in range(len(test)):
if (i % 2) == 0:
num = int(test[i]) * 2
if num > 9:
num -= 9
nums.append(num)
else:
nums.append(int(test[i]))
print(nums)
print((sum(nums) % 10) == 0)
I found where your code went wrong.
On the line:
for i in test:
if int(i) % 2 == 0:
It should be:
for i in range(len(test)):
if i % 2 == 0:
You should not be using the element of the string you should be using the index of the element.

How do I name a list while generating numbers on the fly?

I use this code in python37 and it generates numbers in the list, but I would also like it to create this name along with it for the list name.
The code just does this:
[1,2,3,4]
This is the name I hoping for to add it to it on the fly:
lst1z
Here is the result for what I hope someone can edit the code to make it do this:
lst1z = [1,2,3,4]
So here is my code Thanks:
composites=[]
n = int(input("Enter any number : "))
positive_n = abs(n)
for num in range(positive_n+1):
if num > 1:
for i in range(1, num,1):
if (num % i) == 0:
if n > 0:
composites.append(num)
else:
composites.append(-num)
break
print ("\ncomposites from", int(positive_n / n), " to ", n, "\n", composites)
composites=[]
n = int(input("Enter any number : "))
positive_n = abs(n)
for i,num in enumerate(range(positive_n+1)):
if num > 1:
for i in range(1, num,1):
if (num % i) == 0:
if n > 0:
composites.append(num)
else:
composites.append(-num)
break
#If all you need is to create vairalble and print, you can simply do it as follows:
list1z = composites
print("\ncomposites from {} to {} \n list1z = {}".format(int(positive_n/n), n, list1z))
print ("\ncomposites from", int(positive_n / n), " to ", n, "\n", composites)

How to call a function within a class wit .self in Pyton3

So i've been trying to create a calculator with more complex structure. The problem that am facing is that i'm trying to create a function that calls another function, i know it seems unneccesary but it will be needed in the future. I have a problem calling the function.
class Calculator:
class Variables:
# Start by defining the variables that you are going to use. I created a subclass because I think is better and
# easier for the code-reader to understand the code. For the early stages all variables are going to mainly
# assigned to 0.
n = 0 # n is the number that is going to be used as the main number before making the math calculation
n_for_add = 0 # n_for_add is the number that is going to added to "n" in addition
n_from_add = 0 # n_from_add is the result from the addition
self = 0
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
except ValueError: # if the value is not an integer it will raise an error
print("you must enter an integer!") # and print you this. This will automatically kill the program
self.n = n
self.n_for_add = n_for_add
n_from_add = n + n_for_add # this is actually the main calculation adding n and n_for_add
self.n_from_add = n_from_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add)) # this will print a nice output
def subtraction():
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
# this is the same as addition but it subtracts instead of adding
def division():
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
# same as others but with division this time
def multiplication():
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
# its the same as others but with multiplication function
def choice(self):
x = self.addition()
self.x = x
return x
choice(self)
Hope it will help you.
Code modified:
class Variables:
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
return n + n_for_add
except ValueError:
# if the value is not an integer it will raise an error
pass
def choice(self):
x = self.addition()
self.x = x
return x
objectVariables = Variables()
print objectVariables.choice()
I hope this it may serve as its starting point:
def div(x, y):
return x / y
def add(x, y):
return x + y
def subs(x, y):
return x - y
def do(operation, x, y):
return operation(x, y)
print do(add, 4, 2)
print do(subs, 4, 2)
print do(div, 4, 2)

Trouble with Python Code. Objective is to code suffix during input

Objective: Write a function that takes an integer as its only parameter and returns the ordinal abbreviation for that integer as its only result. For example, if your function is passed the integer 1 then it should return the string "1st". If it is passed the integer 12 then it should return the string "12th". If it is passed 2003 then it should return the string "2003rd". Your function must not print anything on the screen.
def convert (n):
self.num = num
n = int(self.num)
if 4 <= n <= 20:
suffix = 'th'
elif n == 1 or (n % 10) == 1:
suffix = 'st'
elif n == 2 or (n % 10) == 2:
suffix = 'nd'
elif n == 3 or (n % 10) == 3:
suffix = 'rd'
elif n < 100:
suffix = 'th'
ord_num = str(n) + suffix
return ord_num
def main ():
day = int(input("Enter the day:"))
month = int(input("Enter the month:"))
year = int(input("Enter the year:"))
print("on the %n" %n, convert(day), "day of the %n" %month,
convert(month), "month of the %n" %year, convert(year),",
something amazing happened!")
main()
This is my code however it keeps saying I haven't defined n when I run it. But above I've already defined it so not sure what the problem is.
This is probably closer to what you want:
def convert(n):
n = int(n)
suffix = ''
if 4 <= n <= 20:
suffix = 'th'
elif n == 1 or (n % 10) == 1:
suffix = 'st'
elif n == 2 or (n % 10) == 2:
suffix = 'nd'
elif n == 3 or (n % 10) == 3:
suffix = 'rd'
elif n < 100:
suffix = 'th'
return str(n) + suffix
def main ():
day = int(input("Enter the day: "))
month = int(input("Enter the month: "))
year = int(input("Enter the year: "))
print("on the %s day of the %s month of the %s, something amazing happened!" %
(convert(day), convert(month), convert(year)))
main()
There are few issues. You cannot use n in main() when you define it in convert(). Also %n is not a valid format character. You need to define suffix = '' when also want run the year through the conversion function as the year can be larger than 100. Also, you probably copied the code from within a class definition. I removed the self.

Categories

Resources