Getting wrong result when adding random values in string format - python

I'm trying to make a script that receives a number of desired random numbers as input, and then generates and prints them.
However, my script adds the numbers instead of joining the strings. I would like for the strings to join so it would generate the pins like:
Enter the amount of lunch pins to generate:
10
26141
128111
937502
2436
56516
83623
246317
My code:
import random
PTG = int(input("Enter the amount of pins to generate: \n"))
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
if RN1 == 0:
PS += "0"
elif RN1 == 1:
PS += "1"
elif RN1 == 2:
PS += "2"
elif RN1 == 3:
PS += "3"
elif RN1 == 4:
PS += "4"
elif RN1 == 5:
PS += "5"
elif RN1 == 6:
PS += "6"
elif RN1 == 7:
PS += "7"
elif RN1 == 8:
PS += "8"
elif RN1 == 9:
PS += "9"
elif RN2 == 0:
PS += "0"
elif RN2 == 1:
PS += "1"
elif RN2 == 2:
PS += "2"
elif RN2 == 3:
PS += "3"
elif RN2 == 4:
PS += "4"
elif RN2 == 5:
PS += "5"
elif RN2 == 6:
PS += "6"
elif RN2 == 7:
PS += "7"
elif RN2 == 8:
PS += "8"
elif RN2 == 9:
PS += "9"
if RN3 == 0:
PS += "0"
elif RN3 == 1:
PS += "1"
elif RN3 == 2:
PS += "2"
elif RN3 == 3:
PS += "3"
elif RN3 == 4:
PS += "4"
elif RN3 == 5:
PS += "5"
elif RN3 == 6:
PS += "6"
elif RN3 == 7:
PS += "7"
elif RN3 == 8:
PS += "8"
elif RN3 == 9:
PS += "9"
elif RN4 == 0:
PS += "0"
elif RN4 == 1:
PS += "1"
elif RN4 == 2:
PS += "2"
elif RN4 == 3:
PS += "3"
elif RN4 == 4:
PS += "4"
elif RN4 == 5:
PS += "5"
elif RN4 == 6:
PS += "6"
elif RN4 == 7:
PS += "7"
elif RN4 == 8:
PS += "8"
elif RN4 == 9:
PS += "9"
elif RN5 == 0:
PS += "0"
elif RN5 == 1:
PS += "1"
elif RN5 == 2:
PS += "2"
elif RN5 == 3:
PS += "3"
elif RN5 == 4:
PS += "4"
elif RN5 == 5:
PS += "5"
elif RN5 == 6:
PS += "6"
elif RN5 == 7:
PS += "7"
elif RN5 == 8:
PS += "8"
elif RN5 == 9:
PS += "9"
elif RN5 == 10:
PS += ""
elif RN6 == 0:
PS += "0"
elif RN6 == 1:
PS += "1"
elif RN6 == 2:
PS += "2"
elif RN6 == 3:
PS += "3"
elif RN6 == 4:
PS += "4"
elif RN6 == 5:
PS += "5"
elif RN6 == 6:
PS += "6"
elif RN6 == 7:
PS += "7"
elif RN6 == 8:
PS += "8"
elif RN6 == 9:
PS += "9"
print(PS)
PG += 1
PS = ""
Python version: 3.7.4

import random
# PTG = int(input("Enter the amount of pins to generate: \n"))
PTG = 10
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
PS = str(RN1) + str(RN2) + str(RN3) + str(RN4) + str(RN5) + str(RN6)
print(int(PS))
PG += 1

When I understand your code right, you want to generate n pins with 6 digits. You can do that a lot easier than you want to:
number_of_pins = int(input("Enter the amount of pins to generate: \n"))
pins = []
for i in range(number_of_pins):
pins.append(str(random.randint(100_000, 999_999)))
print(" ".join(pins))
Explaination:
pins = [] makes a new empty list to store the pins
for i in range(n): executes the following indented block n times.
pins.append(random.randint(100_000, 999_999)) generates a random number and adds it to the list. 100000 is the first number with 6 digits and 999999 is the last. (The _ is just for readability). str() converts it to a string.
print(" ".join(pins)) joins all the pins and puts a space between.

Let's go through your code step by step:
First, notice that random.randint returns an int. Therefore you need to convert it to a String.
You can use the str() function in order to convert it to a string, for example:
str(random.randint(0, 9))+"9"
will return a string like 59 (for example).
Therefore, when initializing each random number, you need to do it the following way, for example:
RN1 = str(random.randint(0, 9))
Then, instead of checking the value of each random variable, you can just add them up:
PS = RN1 + RN2 + RN3 + RN4 + RN5 + RN6
Furthermore, instead of using six different variables to handle the random values, you can use a for loop for the first four which are from 0 to 9:
for x in range(4):
RN = str(random.randint(0, 9))
PS += RN
And then add the remaining two that are between 0 and 10:
PS += str(random.randint(0, 10))
PS += str(random.randint(0, 10))

Related

Python print day name of week from number

I'm creating a program which I have to put a number and when I run the program, the solution should be the day for that number. But I don't know how to do. The program I did was this:
num = 4
if(num = 1)
print('Monday')
elif(num = 2)
print('Tuesday')
elif(num = 3)
print('Wednesday')
elif(num = 4)
print('Thursday')
elif(num = 5)
print('Friday')
elif(num = 6)
print('Sunday')
elif(num = 7)
print('Saturday')
elif(num < 1)
print('Put a number between 1 and 7')
else(num > 7)
print('Put a number between 1 and 7')
In python, for statements like if, for, etc. You have to add : at the end of it.
And for comparing (for equal) you have to use == and not =
num = 4
if(num == 1):
print('Monday')
elif num == 2:
print('Tuesday')
.....
You can compare without parenthesis and it will work too.
num = 0
while num <= 7:
num += 1
if num == 1:
print('Monday')
elif num == 2:
print('Tuesday')
elif num == 3:
print('Wednesday')
elif num == 4:
print('Thursday')
elif num == 5:
print('Friday')
elif num == 6:
print('Saturday')
elif num == 7:
print('Sunday')

Python Code for Rock, Paper & Scissor Gave Wrong Output

Essence of this code is to depict Rock, Paper and Scissors game using Python language basically with for loop and if...else statements. I used PyScripter to run the code on Python 3.7.2 as engine. The def main() and if __name__ == '__main__' are PyScripter codes for running the machine
import random
def main():
pass
if __name__ == '__main__':
main()
tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')
for i in range(5):
tie_sum += tie_sum
comp_sum += comp_sum
human_sum += human_sum
comp_guess = random.randint(1, 3)
print(f'The computer guess option is {comp_guess}')
human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))
if comp_guess == 1 and human_guess == 3:
comp_sum += 1
elif comp_guess == 1 and human_guess is 2:
human_sum += 1
elif comp_guess == 2 and human_guess == 3:
human_sum += 1
elif comp_guess == 3 and human_guess == 1:
human_sum += 1
elif comp_guess == 3 and human_guess == 2:
comp_sum += 1
elif comp_guess == 2 and human_guess == 1:
comp_sum += 1
else:
tie_sum += 1
print(f'The number of tie in this game is {tie_sum}')
if comp_sum > human_sum:
print('The winner of this game is the Computer.')
print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
print(f'The winner of this game is {name}.')
print(f'The human sum is {human_sum}')
else:
print('This game ends in tie.')
print(f'The tie sum is {tie_sum}')
The reason for that is the first three lines in the for loop. You are increasing the sum of computer, human and tie while checking the condition and when you the loop iterates again, it sums up again. Here's the modified code:
import random
def main():
pass
if __name__ == '__main__':
main()
tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')
for i in range(5):
comp_guess = random.randint(1, 3)
human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))
print(f'The computer guess option is {comp_guess}')
if comp_guess == 1 and human_guess == 3:
comp_sum += 1
elif comp_guess == 1 and human_guess == 2:
human_sum += 1
elif comp_guess == 2 and human_guess == 3:
human_sum += 1
elif comp_guess == 3 and human_guess == 1:
human_sum += 1
elif comp_guess == 3 and human_guess == 2:
comp_sum += 1
elif comp_guess == 2 and human_guess == 1:
comp_sum += 1
else:
tie_sum += 1
print(f'The number of tie in this game is {tie_sum}')
if comp_sum > human_sum:
print('The winner of this game is the Computer.')
print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
print(f'The winner of this game is {name}.')
print(f'The human sum is {human_sum}')
else:
print('This game ends in tie.')
print(f'The tie sum is {tie_sum}')
Also, there was another modification, the computer guess is supposed to be printed after human's guess. I fixed that too. Hope that helps.

Using if statements

I am attempting to make a simple Python code that replaces numbers with roman numerals. In order to do this, I need to get the position of each number to replace it with the roman numeral equivalent. However, my code doesn't seem to work.
number = range(1,21)
number = list(number)
number = str(number)
for i in number:
for x in i:
if i.index(x) == 0:
if x == "1":
x.replace(x, "X")
elif x == "2":
x.replace(x, "XX")
else:
if x == 1:
x.replace(x, "I")
elif x == 2:
x.replace(x, "II")
elif x == 3:
x.replace(x, "III")
elif x == 4:
x.replace(x, "IV")
elif x == "5":
x.replace(x, "V")
elif x == "6":
x.replace(x, "VI")
elif x == "7":
x.replace(x, "VII")
elif x == "8":
x.replace(x, "VIII")
elif x == "9":
x.replace(x, "IX")
else:
x.replace(x, "")
print number
I suspect that it has to do with the way that my if statements work, but I'm not sure. Any advice would be appreciated.
A long sequence of if and elif clauses is usually a sign that one should be using one or more dicts.
numstrings = [str(i) for i in range(1, 100)]
d0 = {'0':'', '1':'I', '2':'II', '3':'III', '4':'IV',
'5':'V', '6':'VI', '7':'VII', '8':'VIII', '9':'IX'}
d10 = {'0':'', '1':'X', '2':'XX', '3':'XXX', '4':'XL',
'5':'L', '6':'LX', '7':'LXXX', '8':'LXXX', '9':'XC'}
for s in numstrings:
if len(s) == 1:
r = d0[s]
elif len(s) == 2:
r = d10[s[0]] + d0[s[1]]
else:
r = '??'
print(r)

Having trouble with an index Error

I am doing an assignment for my first computer programming course, and I am running into a problem. Basically this program is supposed to take a phonetically Hawaiian word, and produce a string that shows how to prounce it. However when I run the program, this happens:
stopProgram = 1
while stopProgram == 1:
validWord = 0
while validWord == 0:
#this while loop is has the user enter a word until it means Hawaiian syntax.
userWord = input("Please enter a valid hawaiian word.")
userWordEval = userWord.lower()
#changed the case for easier comparisons
validInput = 0
for j in range (len(userWordEval)):
#Test every character in the word to see if it meets the requirements. If it does, valid word is added 1.
if userWordEval[j] == "a" or userWordEval[j] == "e" or userWordEval[j] == "i" or userWordEval[j] == "o" or userWordEval[j] == "u" or userWordEval[j] == "p" or userWordEval[j] == "k" or userWordEval[j] == "h" or userWordEval[j] == "l" or userWordEval[j] == "m" or userWordEval[j] == "n" or userWordEval[j] == "w" or userWordEval[j] == "'" or userWordEval[j] == " ":
validInput += 1
if validInput == len(userWordEval):
#if the number in validWord is equal to the length of the word the user put in, that means that all the charaters were accepted. Otherwise, that means that something wasn't allowed, and will have to be reentered.
validWord = 1
else:
print("Invalid input. The accepted characters are: a, e, i, o, u, p, k, h, l, m, n, w, and '")
proWord = "" #Using this for the pronunciation string.
q = 0
while q <= len(userWordEval):
if userWordEval[q] == "a":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "e":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "o":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ah"
q += 2
else:
proWord += "-ah"
q += 1
else:
proWord += "-ah"
q += 1
elif userWordEval[q] == "e":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-eh"
q += 2
else:
proWord += "-eh"
q += 1
else:
proWord += "-eh"
q += 1
elif userWordEval[q] == "i":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "u":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ee"
q += 2
else:
proWord += "-ee"
q += 1
else:
proWord += "-ee"
q += 1
elif userWordEval[q] == "o":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-oy"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oh"
q += 2
else:
proWord += "-oh"
q += 1
else:
proWord += "-oh"
q += 1
elif userWordEval[q] == "u":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ooey"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oo"
q += 2
else:
proWord += "-oo"
q += 1
else:
proWord += "-oo"
q += 1
else:
q + 1
print(proWord)
stopProgram = 0
Output:
Please enter a valid hawaiian word.aeae Traceback (most recent call last):
File "C:/Users/Kristopher/Documents/Programming HW/Program
3.py", line 26, in <module>
if userWordEval[q] == "a": IndexError: string index out of range
string's index is from 0 to length-1. So change the while loop condition in line 24 to:
while q < len(userWordEval):
Your problem is that you are looping while q <= len(userWordEval). First of all, it is important to know that in python lists use zero-based indexing (see description on Wikipedia). This means that if there are 5 elements in a list, the last element will have index 4. The function len returns the number of elements in a list, so if you use that number as an index it will be too large. You can easily fix this by changing to q < len(userWordEval).
Remember list, string, tuple or other types which support indexing will raise IndexError if you try to access element past the index.
>>> a = 'apple'
>>> a[0]
'a'
>>> a[4]
'e'
>>> a[5]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a[5]
IndexError: string index out of range
So always use len(s)-1
>>> a[len(a)-1]
'e'
>>>
One nice bit of gotcha here. However during slicing you won't get that error. It will simple return an empty string/list.
>>> a[5:]
''
>>> a[:11]
'apple'

number to cardinal python euler

I am doing euler problems to practice python, I can't seem to get the right answer for problem 17. The problem is to find the number of letters in all numbers 1-1000 without spaces or hyphens.
Any comment would be useful.
Python code:
def numberToString(number):
""" Writes a cardinal number to a string. """
numberString=""
c = str(number)
l = len(c)
while l>0:
if l == 1: #unit digit
if int(c[-1]) == 1:
numberString += 'one'
elif int(c[-1]) == 2:
numberString += 'two'
elif int(c[-1]) == 3:
numberString += 'three'
elif int(c[-1]) == 4:
numberString += 'four'
elif int(c[-1]) == 5:
numberString += 'five'
elif int(c[-1]) == 6:
numberString += 'six'
elif int(c[-1]) == 7:
numberString += 'seven'
elif int(c[-1]) == 8:
numberString += 'eight'
elif int(c[-1]) == 9:
numberString += 'nine'
l = l-1
elif l == 2 and int(c[-2])==1 and int(c[-1]) != 0: #teens
if int(c[-1]) == 1:
numberString += 'eleven'
elif int(c[-1]) == 2:
numberString += 'twelve'
elif int(c[-1]) == 3:
numberString += 'thirteen'
elif int(c[-1]) == 4:
numberString += 'fourteen'
elif int(c[-1]) == 5:
numberString += 'fifteen'
elif int(c[-1]) == 6:
numberString += 'sixteen'
elif int(c[-1]) == 7:
numberString += 'seventeen'
elif int(c[-1]) == 8:
numberString += 'eighteen'
elif int(c[-1]) == 9:
numberString += 'nineteen'
l = l-2
elif l == 2: #tens
if int(c[-2]) == 1:
numberString += 'ten'
elif int(c[-2]) == 2:
numberString += 'twenty'
elif int(c[-2]) == 3:
numberString += 'thirty'
elif int(c[-2]) == 4:
numberString += 'fourty'
elif int(c[-2]) == 5:
numberString += 'fifty'
elif int(c[-2]) == 6:
numberString += 'sixty'
elif int(c[-2]) == 7:
numberString += 'seventy'
elif int(c[-2]) == 8:
numberString += 'eighty'
elif int(c[-2]) == 9:
numberString += 'ninety'
if int(c[-1]) != 0 and int(c[-2]) > 1:
numberString += '-'
l = l-1
elif l == 3: #hundreds
if int(c[-3]) == 1:
numberString += 'one'
elif int(c[-3]) == 2:
numberString += 'two'
elif int(c[-3]) == 3:
numberString += 'three'
elif int(c[-3]) == 4:
numberString += 'four'
elif int(c[-3]) == 5:
numberString += 'five'
elif int(c[-3]) == 6:
numberString += 'six'
elif int(c[-3]) == 7:
numberString += 'seven'
elif int(c[-3]) == 8:
numberString += 'eight'
elif int(c[-3]) == 9:
numberString += 'nine'
if int(c[-3]) != 0:
numberString += ' hundred'
if int(c[-1])+int(c[-2]) != 0:
numberString += ' and '
l = l-1
elif l == 4: #thousands
if int(c[-4]) == 1:
numberString += 'one'
elif int(c[-4]) == 2:
numberString += 'two'
elif int(c[-4]) == 3:
numberString += 'three'
elif int(c[-4]) == 4:
numberString += 'four'
elif int(c[-4]) == 5:
numberString += 'five'
elif int(c[-4]) == 6:
numberString += 'six'
elif int(c[-4]) == 7:
numberString += 'seven'
elif int(c[-4]) == 8:
numberString += 'eight'
elif int(c[-4]) == 9:
numberString += 'nine'
if int(c[-4]) != 0:
numberString += ' thousand'
if int(c[-3]) != 0:
numberString += ' '
l = l-1
return numberString
def NumbersInString(min, max):
""" Writes all cardinal numbers on a seperate line on a string, from min to max. """
allNumberString=""
for i in range (min,max+1):
allNumberString += numberToString(i)
allNumberString += '\n'
return allNumberString
def stringNumberCount(numberString):
""" Returns the ammount of letters without spaces, hyphens or newlines. """
numberString=numberString.replace(' ', '')
numberString=numberString.replace('-', '')
numberString=numberString.replace('\n', '')
return len(numberString)
def run(filename, min=1, max=1000):
s=NumbersInString(min, max)
string='Number of letters without spaces or hyphens: '+str(stringNumberCount(s))+'\n'+'List of cardinal numbers:\n'
string += s
f=open(filename, 'w')
f.write(string)
f.close
run('output.txt')
first you change fourty to forty (as written in problem statement)
and second
in elif l==3: block
why r you writing if int(c[-3]!=0):
since we have already covered those cases just before (i mean c[-3]==1,2,3... are not equal to zero )
correct me if i'm wrong and try to put some comment in your code.
http://ideone.com/egeX0k
def countLetter(n):
p=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
q=['','Ten','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']
r=['','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']
c=str(n)
l=len(c)
a=""
if l==1:
a+=p[int(c[0])]
elif l==2:
if c[1]=='0':
a+=q[int(c[0])]
elif c[0]=='1':
a+=r[int(c[1])]
else:
a+=q[int(c[0])]+p[int(c[1])]
elif n==100:
a+="OneHundred"
elif l==3:
a+=p[int(c[0])]+"Hundred"
if c[1]=='0' and c[2]=='0':
a+=""
elif c[2]=='0' and c[1]!='0':
a+="And"+q[int(c[1])]
elif c[1]=='1':
a+="And"+r[int(c[2])]
else:
a+="And"+q[int(c[1])]+p[int(c[2])]
else:
a+="OneThousand"
#print a,len(a)
return len(a)
def main():
sum=0
for i in range(1,1001):
sum+=countLetter(i)
print sum
main()

Categories