This is a blackjack program. When stand function is false, main function is not supposed to append getCard() to myCards but for some reason it still does and it counts backwards. I don't know what I am doing wrong.
import random
import sys
def get_card():
return random.randint(1, 13)
def score(cards):
soft_ace_count = 0
total = 0
Ace = False
To check if an Ace exists in hand and to set face cards to correct value
for card in cards:
if card == 1:
Ace = True
total+=11
soft_ace_count+=1
elif card == 11 or card == 12 or card == 13:
total+=10
else:
total+=card
To convert Ace
for x in cards:
if Ace and total > 21:
total-=10
soft_ace_count-=1
return (total, soft_ace_count)
def stand(stand_on_value, stand_on_soft, cards):
total, soft_ace_count = score(cards)
print(f"In stand: {total}")
if total > 17 and total < 22:
return True
if total == stand_on_value:
return True
elif soft_ace_count == 0 and total == 17:
return True
elif stand_on_soft == True and total == 17:
return True
else:
return False
def numBusts(s):
total, soft_ace_count = s
busted_count = 0
if total > 21:
busted_count+=1
return busted_count
def main():
numSims = int(sys.argv[1])-1
standVal = int(sys.argv[2])
strategy = sys.argv[3]
strategy.upper()
for sims in range(numSims+1):
percent_bust = 0.0
myCards = [get_card(), get_card()]
print(f"in main: first two cards: {myCards}")
stand(standVal, strategy, myCards)
while not stand(standVal, strategy, myCards):
myCards.append(get_card())
percent_bust = (numBusts(score(myCards))/(numSims+1)) * 100
print(f"in main: percent bust: {percent_bust}")
if __name__ == "__main__":
[The image shows how it runs correctly until the while not stand function returns False.][1]main()
I have tried running for loops, not running loops, and other things.
Please help.
while not stand will append to the result of get_card() to myCards when stand is False.
But in your question, you say you don't want it to append when stand() is False.
Also, you seem to be calling the stand function twice consecutively, is this intended? The conditional actually calls the function in order to check its result.
Perhaps this will do what you expect?:
for sims in range(numSims+1):
percent_bust = 0.0
myCards = [get_card(), get_card()]
print(f"in main: first two cards: {myCards}")
if stand(standVal, strategy, myCards) is True:
myCards.append(get_card())
This conditional will append to myCards if and only if stand() returns True, but not when it returns False, 0, or None.
Related
My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.
I have 3 different functions in a class if the command in any of the function returns false, I want the program to begin all over again the way it started if the function that returns false was the last command among the function. Also, I want the program to return to the last successful function command if the failed command is not the last among the functions
When I run the program and last function command fails, the program returned to the starting point but ignore certain and crucial part of what I want to achieve, rather it full execute the second function command
class Test():
def greeting(self):
user_input = input("Greeting: ")
print("This is the greeting function")
list1 = ["hello", "Hi"]
if user_input in list1:
print("Thats good")
Test.cities(self)
elif user_input not in list1:
print("Mtchewwww")
Test.greeting(self)
else:
print("be serious")
def cities(self):
print("U re now inside the city function")
list2 = ["Otukpo", "Gboko"]
user_input = input("Cities: ")
if user_input in list2:
print("Nice one")
Test.num(self)
else:
print("that's not a city")
Test.cities(self)
def num(self):
user_input = input("Numbers: ")
list3 = [1, 2, 3, 4]
if int(user_input) in list3:
print("good number")
elif user_input not in list3:
print("That was bad")
Test.greeting(self)
else:
print("Can not compute")
calling = Test()
cal = calling.greeting
cal()
I want the program to behave like this:
if item is in list1 move to the next function but if not in list, try the current function again 3 times and after the the 3 chances and it's still not in the list return to the previous function
def greeting():
user_input = input("Greeting: ")
# It is not good to name your variables like `list1`, `str2`...
# plus, if your list is immutable, use a tuple instead.
options = ('hello', 'Hi')
if user_input in options:
print("That's good")
return True
else:
return False
def cities():
user_input = input("Cities: ")
options = ("Otukpo", "Gboko")
if user_input in options:
print("Nice one")
return True
else:
print("That's not a city")
return False
def num():
user_input = input("Numbers: ")
options = (1, 2, 3, 4)
try:
if int(user_input) in options:
print("Good number")
return True
else:
return False
except ValueError:
# In case that the input is not a number
return False
def main():
fns = (greeting, cities, num)
ptr = 0
cnt = 0
# Just for your information, you don't have to use `ptr >= 0 and ptr <3` in python
while 0 <= ptr < 3:
# print(ptr, cnt)
if cnt >= 3:
# if failed for 3 times, move `ptr` to the previous function, and reset `cnt` to 0
ptr -= 1
cnt = 0
continue
# Get the current function, as `fn`
fn = fns[ptr]
if fn():
# if the current function is a success, move to next, and reset `cnt`
ptr += 1
cnt = 0
else:
# if the current function is a failure, it will be tried again in next while loop
cnt += 1
main()
Use a pointer ptr to iterate over your three functions, and use a variable cnt to limit the failure times. Just try it.
Have fun with python!
Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.
def leapyear(year):
if year/400 == int :
return False
if year/100 == int :
return False
if year/4 == int :
return True
hello I would like to know why my code doesn't work with it == to int because essentially its the same thing as using modulo and == to 0 this is just a question that came to me.
def check(n): if n > 200: return "large"
x = n/2 if x !=int: return "odd"
elif x==0 and n< 100: return "small"
elif x==0 and n>100: return "medium"
also how come the int works here
Your issue is that int is a type. If you try to compare a number to a type of object, which is what you are doing when you write if year/400 == int :, it will always return False, because these can never be the same.
A better way to check if year/400 is an integer would be:
if year%400 == 0:
return False
This is saying:
If the remainder of year/400 is equal to 0, return False, which is what you wanted.
Some other things are:
You should use elif instead of if in most cases. In this one, it doesn't matter, since the return statement terminates the execution of the function early, but you should still use it anyways. Otherwise, even when you have your final result, it will go through the rest of the if statements.
The other thing isn't related to your code, but your leap year criteria are incorrect. If the year is divisible by 4, then it's a leap year.
Unless the year is divisible by 100, then it's not.
Unless it's divisible by 400, then it is.
Improved code:
def leapyear(year):
if year%400 == 0:
return True
elif year%100 == 0:
return False
elif year%4 == 0:
return True
return False
In Python int is considered as Class. You can use type() function on a variable to get it's datatype in Python. So, to use your logic you have to rewrite your code as below:
def leapyear(year):
if type(year/400) == int :
return False
if type(year/100) == int :
return False
if type(year/4) == int :
return True
Note: I have just replicated your code by adding the type() function wherever necessary but it would be suggested to use if, elif and else rather than just if, as it will optimize your code.
You are checking direct number not its type. You should use....
if type(year/400) == int :
Then here is the conditional block.
elif type(year/100) == int:
Another Conditional check
elif type(year/4) == int:
Another conditional block.
And you also have a logical error please see the complete code given below.
So your function can be re-written with corrected logic as...
def leap_year(year):
if type(year/400) == int :
return False
elif type(year/100) == int:
return False
elif type(year/4) == int:
return False
else:
return True
This is the Complete code.
You should know output is FLOAT if use '/' .
e.g.
2020/400 -> 5.05
2020/100 -> 20.2
2020/4 -> 505
You have to change type like using int()
e.g.
2020/400 -> 5.05 int(2020/400) -> 5
2020/100 -> 20.2 int(2020/100) -> 20
2020/4 -> 505 int(2020/4) -> 505
from __future__ import division
import sys
time_year = int(sys.argv[1])
def leapyear(year):
if (year/400) == int(year/400) :
result = False
elif (year/100) == int(year/100) :
result = False
elif (year/4) == int(year/4) :
result = True
else :
result = 'something worg'
return result
a=leapyear(time_year)
print a
Hope can help you :)
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
You can check a year whether it is leap year or not by returning True or False
without using any libraries.
(lambda year : (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0))(2020)
I am doing this little exercise that consists of adding a bonus to salary based on performance and determining how employees performed base on the qualification:
unacceptable = 0
acceptable = 0.4
top performance = 0.6
This is what I have so far:
value_number = float(input('write down the person qualification'))
def salary_and_performance(value):
salary = 2400 + 2400 * value_number
if value_number == 0:
return salary
print('unacceptable')
elif value_number == 0.4:
return salary
print('acceptable')
elif value_number == 0.6:
return salary
print('top performance')
else:
print('invalid value')
salary_and_performance(value_number)
When I run my code it doesn't return any data. Only a black space displays.
print('inaceptable') ,print('acceptable') etc. will never run besause they are located after return statement. First print and then return. Or you might want not to return anything in that case, I don't know the purpose of your function.
Replace all instances of value_number within your function with value because that is the name of your argument
value_number = float(input('write down the person calification'))
def salary_and_performance(value):
salary = 2400 + 2400 * value
if value == 0:
print('inaceptable')
return salary
elif value == 0.4:
print('acceptable')
return salary
elif value == 0.6:
print('top performance')
return salary
else:
print('invalid value')
salary_and_performance(value_number)