What is wrong with this cycle, please that the output is
0
One
1
One
2
One
3
One
4
One
5
One
for i in range(6):
print(i)
if i == 0 or 2 or 4:
print('One')
else:
print('Two')
I would expect alternate printing of One and Two. Many thanks.
Make the below changes in your if statement:
for i in range(6):
print(i)
if i == 0 or i == 2 or i == 4:
print('One')
else:
print('Two')
Your if i == 0 or 2 or 4: is equivalent to if (i == 0) or 2 or 4: and hence will compute as always true.
Related
I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.
I need to find the discount of an order
I used the following code to make the string input of order numbers to a dictionary and thenused sum() to find the total of the order
However I wish to have an offer discount if there is one-1 and one-3 and (one-4 or one-5 or one-6)
But then after the conditional block when I want to multiply it I receive an Unbound Error
def compute_cost(order):
"""
Function 2: compute_cost(order)
Parameters: order (String)
Return: Final cost of order
"""
numcount = {}
orderlist = map(int, order)
for i in orderlist:
if numcount.get(i):
numcount[i] += 1
else:
numcount[i] = 1
for i in numcount:
if i == 1:
numcount[i] = numcount[i]*4.25
elif i == 2:
numcount[i] = numcount[i]*2.50
elif i == 3:
numcount[i] = numcount[i]*2.00
elif i == 4:
numcount[i] = numcount[i]*1.25
elif i == 5:
numcount[i] = numcount[i]*1.50
elif i == 6:
numcount[i] = numcount[i]*1.75
elif i == 7:
numcount[i] = numcount[i]*3.75
else:
return print("Your order has a number outside of the range (1:7)")
order_total = sum(numcount.values())
if(numcount[1] == 1 and
numcount[3] == 1 and
(numcount[4] == 1 or
numcount[5] == 1 or
numcount[6] == 1)):
discount1 = 0.20
order_total1 = order_total*discount1
return order_total1
Please help me
Thank you for your time and effort
EDIT
If you have a better way for me to find the values and save them in a dictionary I am open to constructive criticism too
Depending on the input, the numcount-dict may or may not have all the keys.
Case 1: UnboundLocalError
When calling the function with compute_cost('12323123'), the numcount-dict becomes:
{1: 2, 2: 3, 3: 3}
The if-statement first checks if numcount[1] == 1, which evaluates to False. Therefore the whole expression is False and Python doesn't even (need to) check the rest. (This is called short-circuit evaluation.)
Because the if-statement evaluates to False, discount1 is not set at all, so you get UnboundLocalError: local variable 'discount1' referenced before assignment.
Solution:
Add an else-clause that sets discount1 to 1 (= no discount) when the condition is False:
if (numcount[1] == 1 and numcount[3] == 1 and (numcount[4] == 1 or
numcount[5] == 1 or numcount[6] == 1)):
discount1 = 0.20
else:
discount1 = 1
Case 2: KeyError
Now, when calling the function with compute_cost('32235664'), the numcount-dict becomes:
{3: 2, 2: 2, 5: 1, 6: 2, 4: 1}
The if-statement first checks if numcount[1] == 1, but that key does not exist so Python raises a KeyError. Depending on your input and how far Python needs to evaluate the if-statement, you may get that KeyError or not.
Solution:
Make sure that the numcount-dict contains all keys from the beginning. You already know how many items the dict must have because you limit your input to the range (1:7). Therefore you can initalize the dict as:
numcount = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
EDIT: is there a better way?
Sure there is, there almost always is a better way:
prices = {'1':4.25, '2':2.50, '3':2.00, '4':1.25, '5':1.50, '6':1.75, '7':3.75}
orders = '12323456'
total = sum(prices[order] for order in orders)
if (all(orders.count(type) >= 1 for type in '13') and # multiple ANDs with 'all'
any(True for type in '456' if orders.count(type) >=1)): # multiple ORs with 'any'
discount = 0.2
else:
discount = 1
print('Order value: {}\nDiscount: {}\nOffer: {:.2f}'.format(total, discount, discount * total))
You now can easily extend your prices dictionary or the conditions for a discount. I assumed that the condition for a discount is that at least one item was ordered, not exactly one. Therefore I used >=1 which you can change into ==1 if it needs to be exactly one.
I am writing a function fizzbuzz and what I want to do is input value and return it as fizz, buzz or fizzbuzz. However, there is a problem with my code. Whenever I run this, I just only get the first condition and it does not continue. Here is the code below for you:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0:
return ('Fizz')
elif a % 5 == 0:
return ( 'Buzz' )
elif a % 15 == 0:
return ('Fizzbuzz')
else:
return a
print(fizzbuzz(a))
The problem is in the ordering of your if conditionals.
Consider that if a is divisible by 15 then it is also divisible by 3 and 5 and so your code will just enter the first conditional and not the one you want.
Arrange the conditionals in descending order of 15, 5, 3 etc. and you should see what you want.
def fizzBuzz(n):
for n in range(1,n+1):
if n % 3 == 0 and n % 5 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
if __name__ == '__main__':
n = int(input().strip())
fizzBuzz(n)
Be sure that your conditions are checked in the right order.
A Fizzbuzz number is also a Fizz (divisible by 3) and a Buzz (divisible by 5), just to be clear.
In the code you wrote if you ask the function if 15 is a Buzz, since it is the 1st check, you will get a positive result.
The condition you want to test here is not if a number is divisible by 15 but if a number is divisible by 3 and 5 at the same time.
Given this explanation you need to write conditions a bit differently:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0 and a % 5 == 0:
return('Fizzbuzz')
elif a % 3 == 0:
return('Fizz')
elif a % 5 == 0:
return('Buzz')
else:
return a
print(fizzbuzz(a))
I am able to get the code work good when the compound statement is changed to
if a % 2 == 0 and b % 2 == 0:
But as I am in learning phase could someone please guide me in explaining the error in the original code.
exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
if a and b % 2 == 0:
print(f'{a,b} are the even numbers')
else:
print(f'one of {a,b} is the odd number')
enter image description here
The issue is that you are not asking anything for the condition for 'a'. What you should state is the following:
exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
if a % 2 == 0 and b % 2 == 0:
print(f'{a,b} are the even numbers')
else:
print(f'one of {a,b} is the odd number')
Let me know.
In you case
if a and b % 2 == 0:
is equivalent to
if bool(a) and bool(b % 2 == 0):
a is an integer so bool(a) is True if a is not 0
I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo”
instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.
i = 0
while I < 100:
i += 1
print(i)
if i == 3:
print("Foo")
You will have to use mod (%) to check the remainder of a division.
See if i % 3 is equal to 0. If this is true, then print FOO.
If i % 5 equal 0, print Bar; and so on.
I would recommend using an if else statement in your while loop after the index counter. Something like...
i = 0
while i <= 100:
i += 1
if i % 15 == 0:
print("foobar")
elif i % 3 == 0;
print("foo")
elif i % 5 == 0:
print("bar")
else:
print(i)
Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.
i = 0
while i < 100:
i += 1
if i%15 == 0:
print('FooBar')
elif i%3 == 0:
print('Foo')
elif i%5 == 0:
print('Bar')
else:
print(i)
Apply if and else statement to decide which is the situation during the while loop.
Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.