Entering Values, and adding specific types - python

Trying to figure out how to work a list of user input integers into separate categories and adding those categories together, and I'm stuck. This is what I have so far:
def main():
again = 'y'
while again == 'y':
pos_values = []
neg_values = []
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
elif value < 0:
neg_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
else:
print(sum.pos_values)
print(sum.neg_values)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
total = 0
all_values = neg_values + pos_values
print[all_values]
print(total + pos_values)
print(total + neg_values)
main()
I'm just a first year student with no prior experience, so please be gentle!

Once you fix the logic error pointed out by Mike Scotty, the other problems are really just syntax errors. sum.pos_values will give you AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values' (because sum is a built-in function and so needs () not .); and print[all_values] will give you a syntax error (because print is also a built-in function and so needs () not []). Your original code doesn't store zeroes in either list: I haven't changed that. And the output format is a guess on my part.
def main():
again = 'y'
pos_values = []
neg_values = []
while again == 'y':
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
elif value < 0:
neg_values.append(value)
else: #edit: terminate also on 0 input
break
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
all_values = neg_values + pos_values
print(sum(all_values),all_values)
print(sum(pos_values),pos_values)
print(sum(neg_values),neg_values)

Related

Slot Machine generator in python , two functions are'nt working ( def get_slot_,machine_spin , def print_slot_machine )

import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns

Python how to check if input is a letter or character

How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.

Incorrect code is being called in 'if/elif/else' statement

I'm making an interest calculator that does compound and simple interest. However, the if statement always runs the simple interest script regardless of input.
I have tried changing variables to strings, integers, and floats. I have tried changing variable names, I have tried removing the first block of code entirely. What the heck is wrong with it???
start = input("simple or compound: ")
if start == "simple" or "Simple":
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or "Compound":
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
If I input Starting balance as 5000, rate as 5, and years as six into simple it gives 6500. But the same result occurs when I call compound.
This expression is not correct:
start == "simple" or "Simple"
should be
start == "simple" or start "Simple"
code below worked:
start = input("simple or compound: ")
if start == "simple" or start == "Simple":
# print("simple")
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or start == "Compound":
# print("compound")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
# print("unknown")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
Because of operator precedence
if start == "simple" or "Simple"
is evaluated as
if (start == "simple") or "Simple"
The (...) part is True if the user entered "simple", but the "Simple" part is always True.

My program for getting the average doesn't quite work

def opdracht3()
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst += n
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
I want to get the average of the list that is being created, but when I add numbers like 11, the len(waslijst) gets set to 2 instead of 1. Is there another way to get the average, or am I using the len function wrong?
You need use .append method to store all elements in a list.
def opdracht3():
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst.append(n)
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()

determinating if the input is even or odd numbers

Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description

Categories

Resources