Using if statements - python

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)

Related

The result is not what I expected, python console problem

new to coding, when enter an equation of 1 * 5, I get "You are ...lazy". But I need to get "You are ...very lazy". Can you help me finding the problem?
Expected:
You are ... lazy ... very lazy
5.0
Do you want to store the result? (y / n):
Found:
You are ... lazy
5.0
Do you want to store the result? (y / n):
msg_0 = "Enter an equation"
msg_1 = "Do you even know what numbers are? Stay focused!"
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = "Yeah... division by zero. Smart move..."
msg_4 = "Do you want to store the result? (y / n):"
msg_5 = "Do you want to continue calculations? (y / n):"
msg_6 = " ... lazy"
msg_7 = " ... very lazy"
msg_8 = " ... very, very lazy"
msg_9 = "You are"
memory = 0
def is_one_digit(v):
v = float(v)
if -10 < v < 10 and v.is_integer():
return True
else:
return False
def check(v1, v2, v3):
msg = ""
if is_one_digit(v1) and is_one_digit(v2):
msg = msg + msg_6
if (v1 == 1 or v2 == 1) and v3 == "*":
msg = msg + msg_7
if (v1 == 0 or v2 == 0) and (v3 == "*" or v3 == "+" or v3 == "-"):
msg = msg + msg_8
if msg != "":
msg = msg_9 + msg
print(msg)
while True:
calc = input(msg_0)
try:
x = calc.split()[0]
oper = calc.split()[1]
y = calc.split()[2]
if x == "M":
x = memory
if y == "M":
y = memory
float(x)
float(y)
if oper in ["+", "-", "*", "/"]:
check(x, y, oper)
if oper == "+":
result = float(x) + float(y)
print(result)
elif oper == "-":
result = float(x) - float(y)
print(result)
elif oper == "*":
result = float(x) * float(y)
print(result)
elif oper == "/":
if float(y) != 0:
result = float(x) / float(y)
print(result)
else:
print(msg_3)
continue
user_input = input(msg_4)
if user_input == "y":
memory = result
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
elif user_input == "n":
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
else:
user_input = input(msg_5)
else:
print(msg_2)
except ValueError:
print(msg_1)
continue
You call float(x) and float(y), but this is not saved anywhere, so v1 and v2 will be '1' and '5', instead of 1 and 5.
If you set
x = float(x)
y = float(y)
, it should work.

Doesn't store entered value when runs second time

I made a rock, paper, scissors game.
It works fine, as I wanted to, but it doesn't store entered value when runs second time, how do I fix that.
See the while loop below where the program goes again if the user enters y.
import random
tools =["Rock","Scissors","Paper"]
r = "".join(tools[0])
s = "".join(tools[1])
p = "".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
computer = computer_predicion()
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion == "R" or my_predicion == "r":
my_predicion = r
return my_predicion
elif my_predicion == "S" or my_predicion == "s":
my_predicion = s
return my_predicion
elif my_predicion == "P" or my_predicion == "p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
human=my_predicion()
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer, human)
if computer == r and human == r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human == p:
print(message+'\n'+message_win)
elif computer == p and human == r:
print(message+'\n'+message_lose)
elif computer == r and human == s:
print(message+'\n'+message_lose)
elif computer == s and human == r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human == p:
print(message+'\n'+message_lose)
else:
pass
c = True
while c: //Here code runs second time if user inputs Y or y.
game()
h = input("Continue?(Y/N):")
if h == "Y" or h == "y":
my_predicion()
computer_predicion()
pass
elif h == "N" or h == "n":
c = False
else:
print("Wrong symbol!")
The value is not being stored in the second loop because
computer = computer_predicion()
human = my_predicion()
are displayed outside of the while loop
Here is your working code, I migrated the two variable assignment inside the while loop
import random
tools =["Rock","Scissors","Paper"]
r="".join(tools[0])
s="".join(tools[1])
p="".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion=="R" or my_predicion =="r":
my_predicion = r
return my_predicion
elif my_predicion=="S" or my_predicion =="s":
my_predicion = s
return my_predicion
elif my_predicion=="P" or my_predicion =="p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer,human)
if computer ==r and human==r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human==p:
print(message+'\n'+message_win)
elif computer == p and human==r:
print(message+'\n'+message_lose)
elif computer == r and human==s:
print(message+'\n'+message_lose)
elif computer == s and human==r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human==p:
print(message+'\n'+message_lose)
else:
pass
c=True
while c : #Here code runs second time if user inputs Y or y.
computer = computer_predicion()
human = my_predicion()
game()
h = input("Continue?(Y/N):")
if h=="Y" or h=="y":
pass
elif h=="N" or h=="n":
c=False
else:
print("Wrong symbol!")

Getting wrong result when adding random values in string format

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))

invalid syntax with elif and else

Whenever I try to use elif and else after if, it says invalid syntax. For example:
if number == "1"
print("123213")
elif number == "2"
print("23423")
else number == "3"
print("324234")
There are three mistakes
: is missing
Indent is missing
else cannot have a conditional
The code can be re-written as
if number == "1":
print("123213")
elif number == "2":
print("23423")
elif number == "3":
print("324234")
Complete working code
number = input("Enter a number - ")
if number == "1":
print("123213")
elif number == "2":
print("23423")
elif number == "3":
print("324234")
Output
Enter a number - 1
123213

why do i get "Attribute Error: 'int' object has no attribute 'lower'"?

i need x to be an integer so my next part of code works, but as soon as i remove quotation marks around 0,1 or 2 where it says "making input readable for computer" i get this error message.
from random import randint
# Input
print("Rock: R Paper: P Scissors: S")
x = input("Please pick your choice: ")
y = randint(0,2)
#Making input readable for computer
if x.lower() == "r":
x = 0;
if x.lower() == "p":
x = "1";
if x.lower() == "s":
x = "2";
print("value entered ", x, "value generated ", y)
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 0 and y == 1:
print("Computer wins!")
if x == 0 and y == 2:
print("You won!")
if x == 1 and y == 0:
print("You won!")
if x == 1 and y == 2:
print("Computer wins!")
if x == 2 and y == 0:
print("Computer wins!")
if x == 2 and y == 1:
print("You won!")
You should be using elif here:
if x.lower() == "r":
x = 0
elif x.lower() == "p":
x = 1
elif x.lower() == "s":
x = 2
Otherwise, all three conditions are evaluated with every run. Meaning, if the first passes, then x will be an integer for the second.
Also, you should write your code like this:
x = x.lower() # Put this up here
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
That way, you don't call str.lower multiple times.
Lastly, Python does not use semicolons.
You are calling x.lower() after you assign x to an integer.
Also, you should probably not use the same variable for the integer and the input string.
With a couple of dictionaries this code will be short and concise:
x_conversion = {'r':0, 'p':1, 's': 2}
x = x_conversion[x.lower()]
or list(in this particular case)
x_conversion=['r', 'p', 's]
x = x_conversion.index(x.lower())
And for winner
winner_choice = {(0,1): 'Computer', (1, 2): 'You', ...}
winner = winner_choice[(x, y)]
Don't forget try/except and you'll have your results in much shorter and more readable code
iCodez answer is the one, but you should just use the strings, like the following, if you are not using the number conversion to factor your print statement, not both.
Edit: Had to change what y was, oops
x = raw_input("Please pick your choice: ").lower()
y = choice(['r','p','s'])
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 'r' and y == 'p':
print("Computer wins!")
elif x == 'r' and y == 's':
print("You won!")
elif x == 'p' and y == 'r':
print("You won!")
elif x == 'p' and y == 's':
print("Computer wins!")
elif x == 's' and y == 'r':
print("Computer wins!")
elif x == 's' and y == 'p':
print("You won!")
Now if you want to go with the convertion to integer then you could just use this:
y = randint(0,2)
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
print ['tie', 'you win', 'they win'][x-y]
And semicolons are not needed in Python, but you can still use them if it makes you comfortable.
Edit: Just for fun.
import random
pick = ['r', 'p', 's']
x = ""
while x not in pick:
x = str(raw_input("r, p, or s? ")).lower()
print ['tie', 'y win', 'y win', 'x win', 'x win'][ord(x)-ord(random.choice(pick))]
Use raw_input() instead of input.
Also this should be:
if x.lower() == "r":
x = "0"

Categories