Variable not storing the correct value in Python - python

So I have written a program in python to try and convert a number typed into the letter version of that number. Ex: 323 -> three hundred twenty-three
The problem I am having is that the one of the variables is not displaying the correct value when the process is complete and the output is displayed. The desired output would look something like this:
Enter a number under 999: 323
323 -> three hundred twenty-three
but instead looks like this:
Enter a number under 999: 323
23 -> three hundred twenty-three
If anyone can help me figure this out, I would greatly appreciate it. Here is my code:
from __future__ import print_function, division
import sys
input = raw_input
n = int(input("Enter a number under 999: "))
if n >= 999:
print("Well, you didn't follow directions.")
sys.exit(1)
word = ""
hundred = n//100
if hundred == 1:
word += "one hundred"
elif hundred == 2:
word += "two hundred"
elif hundred == 3:
word += "three hundred"
elif hundred == 4:
word += "four hundred"
elif hundred == 5:
word += "five hundred"
elif hundred == 6:
word += "six hundred"
elif hundred == 7:
word += "seven hundred"
elif hundred == 8:
word += "eight hundred"
elif hundred == 9:
word += "nine hundred"
if hundred > 0:
word += " "
n = n%100
if n == 10:
word += ' ten'
elif n == 11:
word += ' eleven'
elif n == 12:
word += ' twelve'
elif n == 13:
word += ' thirteen'
elif n == 14:
word += ' fourteen'
elif n == 15:
word += ' fifteen'
elif n == 16:
word += ' sixteen'
elif n == 17:
word += ' seventeen'
elif n == 18:
word += ' eighteen'
elif n == 19:
word += ' nineteen'
else:
ones = n%10
tens = n//10
if tens == 2:
word += "twenty"
elif tens == 3:
word += "thirty"
elif tens == 4:
word += "fourty"
elif tens == 5:
word += "fifty"
elif tens == 6:
word += "sixty"
elif tens == 7:
word += "seventy"
elif tens == 8:
word += "eighty"
elif tens == 9:
word += "ninety"
if tens > 0 and ones > 0:
word += '-'
if ones == 1:
word += 'one'
elif ones == 2:
word += 'two'
elif ones == 3:
word += 'three'
elif ones == 4:
word += 'four'
elif ones == 5:
word += 'five'
elif ones == 6:
word += 'six'
elif ones == 7:
word += 'seven'
elif ones == 8:
word += 'eight'
elif ones == 9:
word += 'nine'
print("{} -> {}".format(n, word))
Oh and btw, My class is learning python 3 while using a python 2 interpreter so that's why the code has some weird aspects to it.

since
n = n%100
mutates "n", you need to "save" the value of "n" first. the most simple method would be:
after declaring
n = int(input("Enter a number under 999: "))
set another variable to n
n = int(input("Enter a number under 999: "))
num = n
then replace
print("{} -> {}".format(n, word))
with
print("{} -> {}".format(num, word))

Change your code to
n = int(input("Enter a number under 999: "))
user_number = n
(...)
print("{} -> {}".format(user_number, word))
Every time you do operations on n you modify it:
n = n%100
So just save it in another variable before modifying it (user_number) and print it at the end.

Related

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

python blackjack ace problem which breaks my code

I currently am making a blackjack python minigame, where a player plays until he gets a blackjack or stands and returns the value of his deck. This game does not play against a dealer and instead just uses his hands as a score. My problem is, I cannot figure out a way to make aces go from 11 to 1 without looping and breaking the program. Here is my code:
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
while len(player) != 2:
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1:
total -= 10
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()
if "A" in player will always be True once there's an ace in the deck, and so you never get to the else where you print "BUST!" and return, so the loop just continues. You can do something like incremeting count for every ace in the deck and then change the ace part to be:
if total > 21:
player_aces = player.count("A") # How many aces the player has
if player_aces != count: # Meaning there are aces that weren't checked
for _ in range(player_aces - count):
total -= 10 # Could also be simplified to: total -= 10 * (player_aces - count)
count = player_aces
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
Also, if action_taken != "hit" or "stand" doesn't check that action_taken is not "hit" and not "stand". An or treats both its inputs as bool values and returns whether at least one is True. The != operator has precedence over or, so the line is actually if (action_taken != "hit") or "stand". The left part of that does what it's supposed to do, but then the right part evaluates "stand" as a bool, and in python every non-empty string is evaluated as True. So the right expression is always True, and so is the or - and the program will always enter the if statement.
You probably want: if action_taken != "hit" and action_taken != "stand".
There were a coupe of issues that I have fixed. I have created a counter for the number of Aces, this allows us to count how many times we can reduced the total by - otherwise we just keep removing 10.
Also the indentation of the last else statement needed moving out.
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
reducedA = 0
while len(player) != 2:
card = 1
#card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
reducedA+=1
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
reducedA += 1
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1 and reducedA:
total -= 10
reducedA -= 1
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or action_taken != "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()

How to have 2 outputs from 2 different functions in one line?

So the program should take a number and then should print this number using text.
print("Enter your number")
Number = int(input())
def number_to_text_ones(ones):
if ones == 1:
print("one")
elif ones == 2:
print("two")
elif ones == 3:
print("three")
elif ones == 4:
print("four")
elif ones == 5:
print("five")
elif ones == 6:
print("six")
elif ones == 7:
print("seven")
elif ones == 8:
print("eight")
elif ones == 9:
print("nine")
def number_to_text_tens(tens):
if tens == 2:
print("twenty ")
elif tens == 3:
print("thirty ")
elif tens == 4:
print("fourry ")
elif tens == 5:
print("fifty ")
elif tens == 6:
print("sixty ")
elif tens == 7:
print("seventy ")
elif tens == 8:
print("eighty ")
elif tens == 9:
print("ninety ")
def number_to_text_hundreds(hundreds):
if hundreds == 1:
print("one hundred")
elif hundreds == 2:
print("two hundreds")
elif hundreds == 3:
print("three hundreds")
elif hundreds == 4:
print("four hundreds")
elif hundreds == 5:
print("five hundreds")
elif hundreds == 6:
print("six hundreds")
elif hundreds == 7:
print("seven hundreds")
elif hundreds == 8:
print("eight hundreds")
elif hundreds == 9:
print("nine hundreds")
if Number == 0:
print("zero")
elif Number == 10:
print("ten")
elif Number == 11:
print("eleven")
elif Number == 12:
print("twelve")
elif Number == 13:
print("thirteen")
elif Number == 14:
print("fourteen")
elif Number == 15:
print("fifteen")
elif Number == 16:
print("sixteen")
elif Number == 17:
print("seventeen")
elif Number == 18:
print("eighteen")
elif Number == 19:
print("nineteen")
if Number < 10:
Result = Number % 10
number_to_text_ones(Result)
elif (Number >= 20 and Number < 100):
First = Number // 10
Second = (Number - (First * 10)) % 10
Result = First * 10 + Second
number_to_text_tens(First)
number_to_text_ones(Second)
elif (Number >= 100 and Number < 1000):
First = Number // 100
Second = (Number - (First * 100)) // 10
Third = (Number - (First * 100) - (Second * 10)) % 10
Result = First * 100 + Second * 10 + Third
number_to_text_hundreds(First)
number_to_text_tens(Second)
number_to_text_ones(Third)
The problem is when I input, say, 895 my output will be:
eight hundreds
ninety
five
Few questions I have:
How to make my output look better?
Is there any way to get rid of those if statements and use something more efficient? Something like switch/case
Here are the answers:
print function has an optional parameter end which specifies what will be written at the end of the string you are printing. Default is new line ('\n'). You would like to use
print('something', end=' ')
Nicer than that would be to first build a string with the name of entire number and the use print only once at the end.
A nice way to solve this is with dictionary, e.g.:
name = {1: "one hundred",
2: "two hundreds",
3: "three hundreds"}[hundreds]
I suspect there is a library for this but I'd refactor to use the following pattern
ones_text = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
def number_to_text_ones(number):
return ones_text[number - 1]
You should use dictionaries as it will reduce the lines of code (if-else conditions will no more be there just a return statement would be sufficient ) and will give your code a better look also execution time will decrease because using if-else condition the program checks each every condition specified, So dictionaries will make help u alot
And for printing your output in one line this one is a better
print(number_to_text_hundreds(First) + number_to_text_tens(Second) + number_to_text_ones(Third))
number_to_text_hundereds , number_to_text_tens and number_to_text_ones returns a value corresponding to value passed to function
I suggest you using lists of strings as follows:
print("Enter your number")
Number = int(input())
units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ['', '', "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
h = Number // 100
t = (Number % 100) // 10
u = (Number % 10)
result = []
if h == 0:
pass
elif h == 1:
result.append('one hundred')
else:
result.append(units[h] + ' hundreds')
if (t == 0):
if (u != 0):
result.append(units[u])
elif (h == 0):
result = ['zero']
elif (t == 1):
result.append(teens[u])
else:
result.append(tens[t])
if (u != 0):
result.append(units[u])
result = ' '.join(result)
print(result)
# input = 895 : result = 'eight hundreds ninety five'
# input = 507 : result = 'five hundreds seven'
# input = 120 : result = 'one hundred twenty'
# input = 071 : result = 'seventy one'
# input = 16 : result = 'sixteen'
# input = 0 : result = 'zero'

Appending specific values to a list while iterating from a string using a for loop

Basically I need help creating a function to read a given parameter which is a list, go through each digit of the list, checking them and adding their binary value to a different list. I am trying this code, but it's not working the way I think it should. Any help is welcome: The side parameter is there to help sort the binary. I have two sets and depending on which 'side' the digits in the list are on, they have a different binary code.
def bin_convert(upc, side):
bin_list = []
if side == 0:
for digit in upc:
if digit == 0:
bin_list.append(0001101)
elif digit == 1:
bin_list.append(0011001)
elif digit == 2:
bin_list.append(0010011)
elif digit == 3:
bin_list.append(0111101)
elif digit == 4:
bin_list.append(0100011)
elif digit == 5:
bin_list.append(0110001)
elif digit == 6:
bin_list.append(0101111)
elif digit == 7:
bin_list.append(0111011)
elif digit == 8:
bin_list.append(0110111)
elif digit == 9:
bin_list.append(0001011)
print bin_list
return bin_list
else:
for digit in upc:
if digit == 0:
bin_list.append(1110010)
elif digit == 1:
bin_list.append(1100110)
elif digit == 2:
bin_list.append(1101100)
elif digit == 3:
bin_list.append(1000010)
elif digit == 4:
bin_list.append(1011100)
elif digit == 5:
bin_list.append(1001110)
elif digit == 6:
bin_list.append(1010000)
elif digit == 7:
bin_list.append(1000100)
elif digit == 8:
bin_list.append(1001000)
elif digit == 9:
bin_list.append(1110100)
print bin_list
return bin_list

How can I simplify this code

I'm a beginner, and I wanted to know if there was a simpler way of write this out in Python. I'm assuming some type of dictionary, but I do not understand how to write it out.
I was on a cruise a couple of days ago, and I play craps. I wanted to know if the odds are somewhat correct. So, I wrote this, but I know there is a simpler way.
import random
dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0
for i in range(100000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
number = dice1 + dice2
#print(dice1)
if number == 2:
dice2 +=1
elif number == 3:
dice3 += 1
elif number == 4:
dice4 += 1
elif number == 5:
dice5 += 1
elif number == 6:
dice6 += 1
elif number == 7:
dice7 += 1
elif number == 8:
dice8 += 1
elif number == 9:
dice9 += 1
elif number == 10:
dice10 += 1
elif number == 11:
dice11 += 1
elif number == 12:
dice12 += 1
total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12
At the end of this, it just prints out the percentage of hits on numbers from 2-12.
I'd use Counter, as that's what it was made for:
from random import randint
from collections import Counter
counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]
from random import randint
dice = [0]*11
for i in range(100000):
dice[randint(1,6)+randint(1,6)-2] += 1
total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
print('{0}: {1}%'.format(i, v*100.0/total))
import random
def roll(n=6):
return random.randint(1, n)
dice = dict.fromkeys(range(2, 13), 0)
for i in range(100000):
number = roll() + roll()
dice[number] += 1
total = float(sum(dice.values()))
for k,v in dice.items():
print "{}, {:.2%}".format(k, v/total)

Categories

Resources