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.
Related
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
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.
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)
Hello I'm asking about the conversion issue with strings and integers.
I have a piece code that requires the conversion between strings and integers but I just can't get it to work, I wonder if anyone could help me. I receive String index out of range error.
Here is the code
def ISBN(bc):
total = 0
up = 0
down = 11
for x in range(10):
sbc = str(bc)
ibc = int(sbc[up])
total += (ibc * down)
#total += (int(sbc[up])*down)
up += 1
down -+ 1
mod = (total % 12)
if mod == 10:
total = "x"
print ("The ISBN book code is: " + bc + total)
w = 0
while w == 0:
a = int(input("Please input the 10 digit book number:\n"))
b = str(a)
if len(b) == 9:
ISBN(a)
else:
print ("Sorry book code not 10 digits long")
restart = input("Would you like to use the book code changer again?\n")
restart = restart.lower
if restart == "yes" or restart == "y":
print ("--------------------------------------------------\n")
elif restart == "no" or restart == "n":
print ("Thank you for using the ISBN book code changer\n")
w = 1
if len(b) == 9:
This should be 10.
mod = (total % 12)
This should be 11.
So, I'm quite nooby at python. I decided to make a program that makes prime numbers. I know there's probably a function built in that does this but I decided to do it myself.
number = 1
numlist = list()
for x in range (0, 1000):
numlist.append("")
print "Created list entry " + str(x)
while True:
number = number + 1
if number % 2 != 0:
numscrollerA = 1
numscrollerB = 1
while numscrollerA <= number:
if float(number) / float(numscrollerA) == float(int(number)):
numlist[numscrollerA] = "true"
if float(number) / float(numscrollerA) != float(int(number)):
numlist[numscrollerA] = "false"
numscrollerA = numscrollerA + 1
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
if primestatus == "true":
print number
I get "Created list entry x" 1000 times as I should. Then the program just hangs.
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
You don't increase numscrollerB in this loop, so it runs infinitedly. Anyway, You should rather use 'for loop':
for numscrollerB in range(1, number+1):
pass # do something
Your code is very unpythonic. Typical of a newcomer experienced in a different style of coding.
Your list is uneccessary.
In python you could create the list like this
def check_even(val):
#this contains your logic
return val % 2 == 0
evenslist = [check_even(i) for i in xrange(1, 1001)]
print numlist