Quit while len(int) < 1 - python

I'm new in python, and I'm trying to make a simple quit, if the Input is empty or less then One int.
I'm getting an error which says - ValueError: invalid literal for int() with base 10: '', when entering nothing, just a enter on launch.
import sys
import os
import getpass
def clear(): return os.system('clear')
ballance = 500.00
# Garage Stockas
Wood_InStock = 600
Weed_InStock = 300
Gun_InStock = 15
Gun_Ammo_InStock = 500 * 30 # X30 Total 15000
# Kainos
Gun_Ammo_Price = 15.50
Wood_Price = 3.50
Weed_Price = 9.50
Gun_Price = 250.50
# Produktai
medis = '~ Elemental Wood ~'
weed = '~ Indoor Kush ~'
gun = '~ Shotgun ~'
gun_ammo = '~ Shotgun ammo 30x ~'
# Inventory
Wood_Inventory = 0
Weed_Inventory = 0
Gun_Inventory = 0
Gun_Ammo_Inventory = 0
# No Money
Not_Enough_Money = '~ Sorry you dont have enough money'
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break

Let's look at only this part of the code:
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
The empty user input will be passed to int(), but an empty string cannot be converted to an int! So an error is raised.
What you should instead is to not convert the input to int first, and treat it as a string:
while True:
Shop_Pasirinkimas = input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif int(Shop_Pasirinkimas) == 1: # convert to int here
clear()
...

int(x,base) function will return the integer object from any number or string. Base defaults to 10. If x is the string, its respective numbers should be within possible values with respect to that base.
As, nothing is entered, it's considered as invalid literal.
Hence, Please use the input as string which can solve the issue easily.

If user doesn't input an integer you will encounter an exception in Shop_Pasirinkimas = int(input(...)). Besides int has no len() so this will also cause error len(Shop_Pasirinkimas). You can do the following to accomplish what you are trying
while True:
try:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if Shop_Pasirinkimas < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
except ValueError:
sys.exit("SOrry")

Related

python vending machine program- I have two questions

I'm creating a vending machine program that simulates the action through a loop that ends when the user enters 0 but it doesn't print "0 to cancel" in the output. I tried putting it at the top before the if statements but, I want to be able to enter an input after the if statements are printed. So how could I fix that?
It says that user_val is undefined when I equal it to 0 but I did define it at the bottom.
If someone could help please!
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
# Currency deposit [tag:tag-name]
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
currency = [num_5Dollars, num_Dollars, num_Quarters, num_Dimes, num_Nickels, num_Pennies]
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
if int(float(user_val)) == 0:
print("0 to cancel")
user_val = float(input())
Your user_val defined under the line if int(float(user_val)) == 0.
And if you want to say to user 0 to cancel, you don't need to check int(float(user_val)) == 0, because while this doesn't happened, it won't print this instruction.
So basically, you need to remove if int(float(user_val)) == 0: line

python itertools not printing multiples of 10

In my current python program which shows all possible combinations, it does not show the multiples of 10 (10,20,30,40,etc.) and I don't understand why, I am using the itertools library don't know if there is something that does this? I have looked online and I haven't found anything like it so maybe it has something to do with my installation of it? Anyway, here is the code.
import itertools
from pynput.keyboard import Controller
import time
keyboard = Controller()
loop = True
a = 1
input("Welcome to the Password Possibilities Test")
input("This test will tell you how many possible")
input("combinations a password can have")
input("*all answers must start with an uppercase*")
num_length = 0
alpha_length = 0
sym_length = 0
num = input("So lets start does your password have numbers?\n")
alpha = input("Does it have letters?\n")
sym = input("Does it have symbols?\n")
long = input("Do you know how long the password is?\n")
possibilities = []
if long == "Yes":
length = input("How long is the password?\n")
elif long == "No":
print("Then we will go off of the average password length which is 8\n")
length = 8
if num == "Yes":
num_length = 10
possibilities.append(0)
possibilities.append(1)
possibilities.append(2)
possibilities.append(3)
possibilities.append(4)
possibilities.append(5)
possibilities.append(6)
possibilities.append(7)
possibilities.append(8)
possibilities.append(9)
else:
num_length = 0
if alpha == "Yes":
alpha_length = 52
possibilities.append("a")
possibilities.append("b")
possibilities.append("c")
possibilities.append("d")
possibilities.append("e")
possibilities.append("f")
possibilities.append("g")
possibilities.append("h")
possibilities.append("i")
possibilities.append("j")
possibilities.append("k")
possibilities.append("l")
possibilities.append("m")
possibilities.append("n")
possibilities.append("o")
possibilities.append("p")
possibilities.append("q")
possibilities.append("r")
possibilities.append("s")
possibilities.append("t")
possibilities.append("u")
possibilities.append("v")
possibilities.append("w")
possibilities.append("x")
possibilities.append("y")
possibilities.append("z")
possibilities.append("A")
possibilities.append("B")
possibilities.append("C")
possibilities.append("D")
possibilities.append("E")
possibilities.append("F")
possibilities.append("G")
possibilities.append("H")
possibilities.append("I")
possibilities.append("J")
possibilities.append("K")
possibilities.append("L")
possibilities.append("M")
possibilities.append("N")
possibilities.append("O")
possibilities.append("P")
possibilities.append("Q")
possibilities.append("R")
possibilities.append("S")
possibilities.append("T")
possibilities.append("U")
possibilities.append("V")
possibilities.append("W")
possibilities.append("X")
possibilities.append("Y")
possibilities.append("Z")
else:
alpha_length = 0
if sym == "Yes":
sym_length = 32
possibilities.append("!")
possibilities.append("#")
possibilities.append("#")
possibilities.append("$")
possibilities.append("%")
possibilities.append("^")
possibilities.append("&")
possibilities.append("*")
possibilities.append("(")
possibilities.append(")")
possibilities.append("_")
possibilities.append("+")
possibilities.append("{")
possibilities.append("}")
possibilities.append("|")
possibilities.append(":")
possibilities.append("\\")
possibilities.append("?")
possibilities.append(">")
possibilities.append("<")
possibilities.append("~")
possibilities.append("`")
possibilities.append("[")
possibilities.append("]")
possibilities.append("\"")
possibilities.append(";")
possibilities.append("'")
possibilities.append("/")
possibilities.append(".")
possibilities.append(",")
possibilities.append("`")
else:
sym_length = 0
num_length = int(num_length)
alpha_length = int(alpha_length)
sym_length = int(sym_length)
length = int(length)
calc = num_length + alpha_length + sym_length
final = pow(calc,length)
print("This password has ",final, "possibilities")
input("Click the ENTER key to view all of the combonations")
time.sleep(2)
for i in itertools.combinations_with_replacement(possibilities,length):
print(*i, sep='')
print("This password has ",final, "possibilities")
exit = input("Would you like to exit?\n")
if exit == "Yes":
pass
elif exit == "No":
while loop == True:
a = 1
When you would like to show all possible combinations you mean about the mathematical concept of the permutation with the repetitions. In python in the itertools library there is only permutations that it is like in mathematics the permutation without the repetitions. In python you can use in exchange for it the itertools.product. The full functioning code I enclose below:
import itertools
from pynput.keyboard import Controller
import time
keyboard = Controller()
loop = True
a = 1
input("Welcome to the Password Possibilities Test")
input("This test will tell you how many possible")
input("combinations a password can have")
input("*all answers must start with an uppercase*")
num_length = 0
alpha_length = 0
sym_length = 0
num = input("So lets start does your password have numbers?\n")
alpha = input("Does it have letters?\n")
sym = input("Does it have symbols?\n")
long = input("Do you know how long the password is?\n")
possibilities = []
if long == "Yes":
length = input("How long is the password?\n")
elif long == "No":
print("Then we will go off of the average password length which is 8\n")
length = 8
if num == "Yes":
num_length = 10
possibilities.append("0")
possibilities.append("1")
possibilities.append("2")
possibilities.append("3")
possibilities.append("4")
possibilities.append("5")
possibilities.append("6")
possibilities.append("7")
possibilities.append("8")
possibilities.append("9")
else:
num_length = 0
if alpha == "Yes":
alpha_length = 52
possibilities.append("a")
possibilities.append("b")
possibilities.append("c")
possibilities.append("d")
possibilities.append("e")
possibilities.append("f")
possibilities.append("g")
possibilities.append("h")
possibilities.append("i")
possibilities.append("j")
possibilities.append("k")
possibilities.append("l")
possibilities.append("m")
possibilities.append("n")
possibilities.append("o")
possibilities.append("p")
possibilities.append("q")
possibilities.append("r")
possibilities.append("s")
possibilities.append("t")
possibilities.append("u")
possibilities.append("v")
possibilities.append("w")
possibilities.append("x")
possibilities.append("y")
possibilities.append("z")
possibilities.append("A")
possibilities.append("B")
possibilities.append("C")
possibilities.append("D")
possibilities.append("E")
possibilities.append("F")
possibilities.append("G")
possibilities.append("H")
possibilities.append("I")
possibilities.append("J")
possibilities.append("K")
possibilities.append("L")
possibilities.append("M")
possibilities.append("N")
possibilities.append("O")
possibilities.append("P")
possibilities.append("Q")
possibilities.append("R")
possibilities.append("S")
possibilities.append("T")
possibilities.append("U")
possibilities.append("V")
possibilities.append("W")
possibilities.append("X")
possibilities.append("Y")
possibilities.append("Z")
else:
alpha_length = 0
if sym == "Yes":
sym_length = 32
possibilities.append("!")
possibilities.append("#")
possibilities.append("#")
possibilities.append("$")
possibilities.append("%")
possibilities.append("^")
possibilities.append("&")
possibilities.append("*")
possibilities.append("(")
possibilities.append(")")
possibilities.append("_")
possibilities.append("+")
possibilities.append("{")
possibilities.append("}")
possibilities.append("|")
possibilities.append(":")
possibilities.append("\\")
possibilities.append("?")
possibilities.append(">")
possibilities.append("<")
possibilities.append("~")
possibilities.append("`")
possibilities.append("[")
possibilities.append("]")
possibilities.append("\"")
possibilities.append(";")
possibilities.append("'")
possibilities.append("/")
possibilities.append(".")
possibilities.append(",")
possibilities.append("`")
else:
sym_length = 0
num_length = int(num_length)
alpha_length = int(alpha_length)
sym_length = int(sym_length)
length = int(length)
calc = num_length + alpha_length + sym_length
print(calc)
final = pow(calc,length)
print("This password has ",final, "possibilities")
input("Click the ENTER key to view all of the combonations")
time.sleep(2)
for i in itertools.product(possibilities, repeat = length):
print(*i, sep='')
print("This password has ",final, "possibilities")
exit = input("Would you like to exit?\n")
if exit == "Yes":
pass
elif exit == "No":
while loop == True:
a = 1

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.

Having Trouble With: Tuple and Int?

So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)

Mastermind Python coding

Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)

Categories

Resources