I made this list with a for loop that points errors when yoy choose a name. I'd like to know how can I make it so that the last line finishes with '.' and the others finish with ';'.
while True:
if len(errors_list) != 0:
print("Your name has thesse errors::")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type a name like '--- ':
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- The last letter is a space.
Try again.
My name is
I'd like to make it so that 1 and 2 finish with ';' and 3 with '.'. Thanks!
All the existing solutions so far seem pretty poor, this is as print is expensive to call.
errors_list.index(i) runs in O(n) time making your solution run in O(n^2) time. You can improve this, to O(n) time, by using enumerate.
You can also think of what you're doing simply as concatenating values of a list and adding a period.
I would use:
errors = [f' {i}- {error}' for i, error in enumerate(errors_list, 1)]
print(';\n'.join(errors) + '.')
Extending Roman Perekhrest's answer, enumerate has an optional parameter start:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print("\t{}- {}{}".format(i, err, ';' if i < len(errors_list) else '.'))
additionaly with Python 3.6+ you can use f-strings instead of format:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print(f"\t{i}- {err}{';' if i < len(errors_list) else '.'}")
Instead of:
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
do
s = len(errors_list)
for e, i in enumerate(errors_list):
ending = ";" if e + 1 < s else "."
print(" " + str(errors_list.index(i) + 1) + "- " + i + ending)
EDIT:
to those jumping to the gun - OP did write in a title comma, but he used semicolon (;) twice (!) in a question itself.
Simply with enumerate function:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
...
for i, err in enumerate(errors_list):
print(" {}- {}{}".format(i+1, err, ';' if i+1 != len(errors_list) else '.'))
The crucial loop will output:
1- It has no letters;
2- It has symbols;
3- The last letter is a space.
I am trying to write a code for myself that will give me an answer for simple interest, I will use same concept and later make compound interest. I am having trouble with my rate. when I do it as a percentage like
r = int(input("rate %: ")
and I type 5.4 it does not work so I tried it in a decimal form like this
r = int(input("Rate 0."))
i get the same answer at end if i do 0.045 and 0.45
so how do i fix this problem
here is my entire code
while True:
while True:
print('Working out for SIMPLE INTEREST')
p = int(input("Principl:"))
r = int(input("Rate 0."))
t = int(input("Time yrs:"))
i = p*r
i = i*t
a = p + i
print("Interest = " + str(i))
print("Accumalated = " + str(a))
print(str(p) + ' x ' + str(r) + ' x ' + str(t) + ' = ' + str(i) + ' | ' + str(p) + ' + ' + str(i) + ' = ' + str(a))
int converts the input string to an integer, which is a whole number like 4 or 5. For 5.4, you want a floating point number, which you can make using the float function:
r = float(input("rate %: "))
(For professional usage, you might even consider the arbitrary-precision decimal package, but it's probably overkill in your situation.)
It is because int does not support decimal numbers
So change int(input('something...')) to input('sonething...')
I am only three weeks into my Intro to Programming course, so bear with me!
I am writing a code as follows:
number1 = input('Enter the first number: ')
number1 = int(number1)
number2 = input('Enter the second number: ')
number2 = int(number2)
number3 = input('Enter the third number: ')
number3 = int(number3)
ratio12 = int(number1 / number2)
ratio13 = int(number1 / number3)
ratio23 = int(number2 / number3)
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.')
print('The ratio of', + number1, '+', + number3,'is', + ratio13, '.')
print('The ratio of', + number2, '+', + number3,'is', + ratio23, '.')
The code is functional (finally), but I can't seem to get rid of the space before the period on the print statements. Is there a way that I can do that?
The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')
This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you.
Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')
This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example, print('i = ', i, sep='')
Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.
Some string formating makes your live easier:
number1 = 1
number2 = 2
ratio12 = number1 / number2
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
Output:
The ratio of 1 + 2 is 0.5.
You can control the "separator" using the sep argument to print:
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.', sep='')
Note that this will change the spacing between the other items as well.
Also -- You don't need the extra + operators in there. Here's a version without the spaces and with explicit spaces added where I think you want them:
print('The ratio of ', number1, ' + ', number2, ' is ', ratio12, '.', sep='')
You're confused about the concatenation function and print fields. If you're going to concatenate all those strings, just use concatenation. The comma includes the default separator.
print('The ratio of', number1, '+', number2,'is', str(ratio12) + '.')
Try to write to it this way:
print('The ratio of %d + %d is %d.' %(number1, number2, ratio12))
print('The ratio of %d + %d is %d.' %(number1, number3, ratio13))
print('The ratio of %d + %d is %d.' %(number2, number3, ratio23))
That's the way print works when you give it multiple comma separated arguments. The logic behind that is that when you quickly want to print a bunch of variables, it's a pain to manually add widespace.
Well, one thing to try: Get rid of all the , in the print statement. You can just chain strings using the + sign.
So,
print('The ratio of ' + str(number1) + ' ' + str(number2) + ' is ' + str(ratio12) + '.')
If you need even greater control over formatting, you'd want to look into the format function.
print("The ratio of {} + {} is {}.".format(number1, number2, ratio12))
I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python shell when I try to runs it. I re-looked over and over however I cannot find the error. I used input for input of integers therefore I do not think that the problem might lie with the input or raw_input. Please help me ! Below are my codes and the error on the python shell.
options()
choice = input ("Enter your choice: ")
print
while choice != -1:
if choice == 1:
print("Choice 1")
for key in toto_book:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
elif choice == 2:
print("Choice 2")
draw = raw_input("Enter draw date(dd/mm/yy): ")
if draw in toto_book:
print (draw + "\t" + "Day: " + toto_book[draw][0] + "\t" + "Winning Numbers: " + str(toto_book[draw][1]) + 'Additional Number: ' + toto_book[draw][2])
else:
print draw + ' cannot be found.'
There is a syntax error at the elif choice == 2: line.
Updated
As pointed out by #cricket_007, this answer is based on the false assumption that Python 3 is being used. Actually, Python 2 is being used and the only serious problem is that the call to str is missing a closing parenthesis.
You are using Python 3 in which print is a function, not a statement (as it is in Python 2).
This is the line causing the problem:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
Add parentheses to make print a function call, i.e. print(...):
print(key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1]) + 'Additional Number: ' + toto_book[key][2])
Also, the call to str() was missing the closing parenthesis.
There is a similar problem on line 15.
Other problems:
input() returns a string, not an integer so your if choice ==
statements will never be true. Either convert choice to an integer
with choice = int(choice) after the input(), or use a string in
the if statements, e.g. if choice == '1'.
The while loop is infinte, and unnecessary for the code shown (perhaps it is a work in progress?).
I'm trying to apply the math.floor function to a some variables that use the str() function... what is the proper way to do this?
Here's my code:
import math
x = str(10.3)
y = str(22)
z = str(2020)
print "x equals " + x
print "y equals " + y
print "z equals " + z
#playing around with the math module here. The confusion begins...
#how do I turn my str() functions back into integers and apply the floor function of the math module?
xfloor = math.floor(x)
zsqrt = math.sqrt(z)
print "When we print the variable \"xfloor\" it rounds " + x + "down into " + xfloor + "."
print "When we print the variable \"zsqrt\" it finds the sqareroot of " + z + "which is " + zsqrt + "."
raw_input("Press the enter key to continue.")
Any and all assistance is welcome.
Cast them back :
xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))
But this is not a recommended practice as you are converting it to str unnecessarily. To print use str.format
print "x equals {}".format(x)
For this you do not need to cast to str.