Incrementing a variable by condition - python

What am I doing wrong? I would like to use count as a global variable.
count = 0
card = low
def running_count ():
if card == low:
count = count+1
elif card == mid:
count = count
elif card == high:
count = count-1
print(count)
I get 0 as the result

count = 0
card = 'low'
def running_count(card):
global count
if card == 'low':
count = count+1
elif card == 'mid':
count = count
elif card == 'high':
count = count-1
running_count(card)
print(count)
#1
running_count(card)
print(count)
#2
But it safer to not use global if you don't have to.

You should try to avoid using global variables where possible.
card should be a string, which you compare to a string inside your function.
You need to call the function you have defined so it gets exectued.
This is an example of how you could do it.
count = 0
card = 'low'
def running_count(count, card):
if card == 'low':
count = count+1
elif card == 'mid':
count = count
elif card == 'high':
count = count-1
return count
count = running_count(count, card)
print(count)
Also you don't really need
elif card == 'mid':
count = count
since you don't change the value of count, you could simply skip this step, because all value besides 'low' and 'high' don't change count.
I hope this helps

Related

Luhn's algorithm works for all credit cards except for AMEX cards (Python3) (cs50/pset6/credit)

I'm trying to create a program that checks whether the credit card number the user inputed is either invalid, or from AMEX, MASTERCARD, or VISA. I'm using Luhn's formula. Here is a site that contains the explanation to the formula I'm using: https://www.geeksforgeeks.org/luhn-algorithm/
It works with all credit card numbers, except credit cards from AMEX. Could someone help me?
Here is my code:
number = input("Number: ")
valid = False
sumOfOdd = 0
sumOfEven = 0
def validation(credit_num):
global sumOfOdd
global sumOfEven
position = 0
for i in credit_num:
if position % 2 != 0:
sumOfOdd += int(i)
else:
product_greater = str(int(i) * 2)
if len(product_greater) > 1:
sumOfEven += (int(product_greater[0]) + int(product_greater[1]))
else:
sumOfEven += int(product_greater)
position += 1
def main():
if (sumOfOdd + sumOfEven) % 10 == 0:
if number[0] == "3":
print("AMEX")
elif number[0] == "5":
print("MASTERCARD")
else:
print("VISA")
else:
print("INVALID")
print(f"{sumOfOdd + sumOfEven}")
validation(number)
main()
Here are some credit card numbers:
VISA: 4111111111111111
MASTERCARD: 5555555555554444
AMEX: 371449635398431
I've found many different ways to calculate this formula, but I'm not sure if mine is correct.

Hangman prints word multiple times if a letter occurs multiple times

I am building a Hangman game. The code that I wrote prints the 'updated target word' multiple times if a letter occurs multiple times.
Example: the target word is 'celebrate'. If I guess e then it prints
*e******
*e*e****
*e*e***e
I would like to avoid printing the first two printouts and only print the third and most updated version.
import random
import re
word_list = ["fireboard", "identical", "chocolate", "christmas", "beautiful", "happiness", "wednesday", "challenge", "celebrate"]
random_pick = random.choice(word_list)
random_pick_a = re.sub("[a-z]","*", random_pick)
random_pick_list_a = list(random_pick_a)
print(random_pick)
count = 0
def main_function():
global count
while count <= 9:
user_input = str(input("type a letter:"))
for i, c in enumerate(random_pick):
if c == user_input.casefold():
random_pick_list_a[i] = user_input.casefold()
random_pick_list_b = ''.join(random_pick_list_a)
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
else:
continue
else:
if user_input.casefold() not in random_pick:
count = count+1
print(count)
if count == 10:
print("sorry")
exit()
main_function()
Disclaimer: I am in my first weeks of coding!
No need to str() the input(), it's already a string. So strip str(input("type a letter:")) to input("type a letter:").
No need in
else:
continue
it will continue even without it. Don't use globals, just move your count into main_function().
Don't do if count == 10, you're already doing it in while count <= 9.
As for your question - move the block
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
out of the for-loop. So the whole thing would look like this:
def main_function():
count = 0
while count <= 4:
user_input = input("type a letter:")
for i, c in enumerate(random_pick):
if c == user_input.casefold():
random_pick_list_a[i] = user_input.casefold()
random_pick_list_b = ''.join(random_pick_list_a)
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
else:
if user_input.casefold() not in random_pick:
count = count+1
print(count)
print("sorry")
You have:
print(random_pick_list_b)
Inside the for loop that is checking each character for the chosen letter. So, it prints out random_pick_list_b every time it finds a match.
Move it to right after the for loop if you want to do it one time when the checking is complete.
I would do this check once before the for loop.

Forwarding variables between functions

I'm trying to do a calculation in the following code:
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
if traffic_intensity(level) == "Moderate" or "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))
What I'm trying to achieve is to use the traffic_intensity function to calculate the number of busy days - a busy day is defined as having more than the "Moderate" amount of traffic given in the traffic_intensity function. I've tried a lot of different ways but I'm running out of ideas at this point.
The problem I'm encountering is that it doesn't find the level variable form the first function. I get the following error:
if traffic_intensity(level) == "Moderate" or "High":
NameError: name 'level' is not defined
Is anyone able to help me? Thanks! ^_^
You were passing in a variable level that doesn't exist into the function traffic_intensity. I presume you meant to pass in the variable count.
Likewise, having or "High" as a condition will always result in true since non-empty strings are convertible true in python
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
state = traffic_intensity(count)
if state == "Moderate" or state == "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))

Beginner in Python, can't get this for loop to stop

Bit_128 = 0
Bit_64 = 0
Bit_32 = 0
Bit_64 = 0
Bit_32 = 0
Bit_16 = 0
Bit_8 = 0
Bit_4 = 0
Bit_2 = 0
Bit_1 = 0
Number = int(input("Enter number to be converted: "))
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
if place_value == 128:
Bit_128 = 1
elif place_value == 64:
Bit_64 = 1
elif place_value == 32:
Bit_32 = 1
elif place_value == 16:
Bit_16 = 1
elif place_value == 8:
Bit_8 = 1
elif place_value == 4:
Bit_4 = 1
elif place_value == 2:
Bit_2 = 1
elif place_value ==1:
Bit_1 = 1
Number = Number - (place_value)
if Number == 0:
print ("Binary form of"),Number,("is"),Bit_128,Bit_64,Bit_32,Bit_16,Bit_8,Bit_4,Bit_2,Bit_1
I want this loop to move to the next 'power' value when it fails the first if condition, but when I run it in an interpreter, the program keeps on running despite the first condition not being true. I only want it to move on the next conditions if the first condition turns out to be true.
How can I do this? This is my first "big" program in python, and I'm having a hard time figuring this out. Any tips would be appreciated. Btw, the program is meant to convert any number from 1-255 to binary form.
If you want a loop to go to the next value, all you need to do is use the continue keyword:
...
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
continue
...
Just using "break" statement , to break the current loop when the condition is satisfied.

How to ask user for a series of number and return the sum of all numbers excluding the max number?

So I need to create a function in python that asks the user to input numbers and enter end when done. After that I need to compute the sum of the numbers enter excluding the max number. (i.e if the user entered 20, 50, and 100 the sum would be 70)
So for I have this which loops input until user inputs the word end:
def excludeMax():
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
This looks like what you are looking for.
def excludeMax():
numbers = []
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
else:
numbers.append(result)
# notice this is after the loop
numbers.remove(max(numbers))
return sum(numbers)
Simply sort it and then add up a slice:
def exclude_max():
return sum(sorted(map(int, iter(lambda: input('Enter next number or end: '), 'end')))[:-1])
Result:
>>> exclude_max()
Enter next number or end: 20
Enter next number or end: 50
Enter next number or end: 100
Enter next number or end: end
70
Place all numerical input into a list. If you see an end, break from the while loop. Once you've exited the while loop, remove the max element from the list (e.g., lst.remove(max(list))). Finally, get the sum via sum(lst).
Approach 1: No temp lists and sort needed in this approach. Excludes just one of the max numbers(doesn't deal with duplicates)
def excludeMax():
biggest_sof_far = None
sum_of_inputs = 0
while True:
result = input('Enter next number or end:')
if result == 'end':
break
if biggest_sof_far == None:
biggest_sof_far = result
elif result > biggest_sof_far:
sum_of_inputs += biggest_sof_far
biggest_sof_far = result
else:
sum_of_inputs += result
return sum_of_inputs
if __name__ == "__main__":
print excludeMax()
Approach 2: Using a temp list (increases space complexity) and sort and sum on list(increases time complexity). This to excludes just one max numbers(doesn't deal with duplicates)
def excludeMax():
input_numbers = []
while True:
result = input('Enter next number or end:')
if result == 'end':
break
input_numbers.append(result)
input_numbers.sort()
return sum(input_numbers[:-1])
if __name__ == "__main__":
print excludeMax()
Both the approaches assume that you want to exclude just one max element. If you want to exclude all max elements(in case of duplicate max numbers):
Approach 1: Excludes even the duplicate max numbers
def excludeMax():
biggest_sof_far = None
sum_of_inputs = 0
while True:
result = input('Enter next number or end:')
if result == 'end':
break
if biggest_sof_far == None:
biggest_sof_far = result
elif result == biggest_sof_far:
pass
elif result > biggest_sof_far:
sum_of_inputs += biggest_sof_far
biggest_sof_far = result
else:
sum_of_inputs += result
return sum_of_inputs
if __name__ == "__main__":
print excludeMax()
Approach 2: Excludes even the duplicate max numbers
def excludeMax():
input_numbers = []
while True:
result = input('Enter next number or end:')
if result == 'end':
break
input_numbers.append(result)
input_numbers.sort()
omit_till_index = -1
input_len = len(input_numbers)
while input_len > -omit_till_index and \
input_numbers[omit_till_index] == input_numbers[omit_till_index-1]:
omit_till_index = omit_till_index-1
return sum(input_numbers[:omit_till_index])
if __name__ == "__main__":
print excludeMax()
In your loop append all input values to a list (if not 'end'). After that sort list in place and compute sum for list[:-1] (gives you the list without the last element).
In code:
numbers = []
def excludeMax():
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
else:
numbers.append(result)
numbers.sort()
sum_numbers = sum(numbers[:-1])

Categories

Resources