Python while/if statements not working - python-3.x

I am currently learning Python and I am trying to get this game to work. Basically I assigned a word to be guessed and then sliced the word and assigned it to several other variables. Basically, each variable assigned as "letterx" is a letter which makes up part of the string variable word. The problem is getting the while statement with nested if statements to work. For some reason I can't get the guess input to equal letterx. All I get when I run the code is "No." and then the amount of turns left. However, I can't get the elif statement to work. Pretty much everything else works. I'm used to programming in Java and I am fairly new to Python so any tips or help would be greatly appreciated. Thank you for your time and help! Here's the code:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
Here's the program running in the Python shell:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word

Let's say guess equals letter1. Then even though
guess == letter1, the first condition is still True since guess != letter2. And similarly, no matter what guess is, there is some letter (amongst letter1, letter2, etc.) which it is not equal.
So the first if condition is always True.
Instead, you could use
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
By the way, it should be entirely possible to code the game without defining letter1, letter2, etc. All this code should be deleted:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
Just use word[0] in place of letter1, and word[1] in place of letter2, etc.
And note you may not even need word[0], word[1]. For example,
with Python you can use
guess in word
instead of
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
It's not only a lot less typing, it is more general, since guess in word does the right thing with words of any length.

Related

I can't make multiple statement to check two statement

I am making a code in python to make password and save in the text file, if the user enters the same password in the file, the error code will appear. The problem is that although I made a two statement to check the password is valid and there is no same password in the text file, the statement of the one that will check text file to find same file. Can you tell me where I get mistake?
def InputString():
String = str(input("Enter your password. :"))
return String
def CheckPassword(Password):
##I declared "Index","Upper","Lower","Digit" and "Other" as Integer.
##In python, there is no data type for
##"char", so We use string instead.
##I use "variable" as boolean for checking password.
Upper = 0
Lower = 0
Digit = 0
Other = 0
variable = False
for index in range(len(Password)):
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z":
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1
if Upper > 1 and Lower >= 5 and (Digit - Other) > 0:
variable = True
else :
variable = False
return variable
def CheckThrough (Password):
FileP = open("Password.txt","r")
if FileP.mode == 'r':
contents = FileP.read()
if contents == Password:
usable = False
else :
usable = True
FileP.close()
return usable
###The main programs starts here###
print("Enter the password.")
print("You must add at least 1 upper character.")
print("5 lower character")
print("and the difference between numeric character and symbols must be more than 1.")
variable = False
usable = False
while variable == False and usable == False:
Password = InputString()
variable = CheckPassword(Password)
if variable == True:
usable = CheckThrough(Password)
if usable == True:
print("You can use the password.")
elif usable ==False :
print("The password you entered is already used.")
else :
print("The error is ocuured.")
else :
print("You can't use this password, try again.")
print("Your password is",Password)
FileP = open("Password.txt","a+")
FileP.write(Password)
FileP.write("\n")
FileP.close()
you need to add .strip() so it has no spaces e.g String = str(input("Enter your password. :").strip()). When you enter in the password there's a space but that doesn't get saved to the file thus it always reads it as a new password.
my input = Enter your password. :Kingdom1hearTs
The input into the program = " Kingdom1hearTs"
(used print to see what was being entered into the system)
and the if contents == Password: needs to be if Password in contents:otherwise your seeing if Password is the same as the whole txt file.
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z": #had the wrong indentation
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1

I want to be able to restart my program after a user input error

I am making a program using the python module pypokedex, to make a program that will ask for a pokemon's name, and the generation, and pull up a https://www.serebii.net/ page about it. But, if the user spells a pokemon incorrectly, it just errors and shuts down the program. I want it to restart the program.
I also have it so that if the code succeeded, it will still loop, the problem is when it fails, (again, this is only a problem if the user spells a name wrong)
the reason this:Asking the user for input until they give a valid response doesn't work is because I need to have it be certain words, not a range of numbers.
import pypokedex
import webbrowser
while 1==1:
name = input("What pokemon are you searching for? ")
p = pypokedex.get(name = name)
zero = 3-len(str(p.dex))
if(zero == 2):
num = "00" + str(p.dex)
if(zero == 1):
num = "0" +str(p.dex)
if(zero == 0):
num = str(p.dex)
ngen = input("What generation number are you looking for? ")
if(ngen == str(1)):
gen = "pokedex"
if(ngen == str(2)):
gen ="pokedex-gs"
if(ngen == str(3)):
gen = "pokedex-rs"
if(ngen == str(4)):
gen = "pokedex-dp"
if(ngen == str(5)):
gen = "pokedex-bw"
if(ngen == str(6)):
gen = "pokedex-xy"
if(ngen == str(7)):
gen = "pokedex-sm"
url = "https://www.serebii.net/" + str(gen) + "/" + str(num) + ".shtml"\
webbrowser.open(url , 2)

Python 3: How to exit loop without stopping function

I am a complete newbie and have tried solving this problem (with my own head and with online research) for the last 5 hours.
Below is a snippet of a function we have written to simulate a game. We want to offer the ooportunity to start a new round - meaning if a player hits "b", the game should start again at the beginning of the range (0, players). But right now it just goes onto the next player in the range (if player 1 enters "b", the program calls player 2)
players = input(4)
if players in range(3, 9):
for player in range(0, players):
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
if roll_dice == "b":
player = 0
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")
I have tried return and break, also tried to put it all in another while-loop... failed. Break and return just ended the function.
Any hints highly appreciated!
you could change the for loop to a while loop. instead of using a range, make player a counter
players = 4
if 3 <= players < 9:
player = 0 # here's where you make your counter
while player < players:
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
player += 1 # increment it
if roll_dice == "b":
player = 0 # now your reset should work
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")

character counter in Python 3 without built in functions

So I have to create a program that reads a paragraph from Romeo & Juliet and returns the number of characters, number of spaces, number of words, and the top 3 most common characters without the use of built in functions such as counter. I made this program to use parallel lists to count unique characters and add a tally into the second list. My problem lies in being able to pick out the top three and print the two lists (i.e. "A 3").
This is the txt file the program reads:
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
This is the program I have so far:
charCount = []
uniqueChar = []
char_count = 0
word_Count = 0
space_count = 0
Open_File = open("romeo.txt")
for romeo in Open_File:
for char in romeo:
if (char == ' ' or char == '.'):
word_Count += 1
if (char == ' '):
space_count += 1
if (char != ' ' and char != '\n'):
char_count += 1
if (char not in uniqueChar):
uniqueChar.append(char)
charCount.append(1)
else:
for j in range(len(uniqueChar)):
if (uniqueChar[j] == char):
charCount[j] += 1
print("Spaces: ", space_count)
print("Char: ", char_count)
print("Words: ", word_Count)

1 + 1 = 0 ? What am I missing! Have been coding for too long today? :(

Using VS2008 C++, console application (empty, made from scratch), placing this in the code :
printf("\n\n%d + %d = %d !!!\n\n",(unsigned __int32)(19L / 17L),((19L % 17L) == 0L)?0L:1L,(unsigned __int32)(19L / 17L) + ((19L % 17L) == 0L)?0L:1L);
And when I run the program, I get :
1 + 1 = 0 !!!
What am I missing?????? :'~(
You are missing 'precedence'. In the last argument to printf(), the addition is higher precedence than the conditional. The sum is evaluated as
(__int32)1 + (2L == 0) which is 1 + 0, or 1 (which is then promoted to long)
Therefore the conditional resolves to
1L ? 0L : 1L
which is 0L since the 'condition' is non-false (non-zero).
printf("\n\n%d + %d = %d !!!\n\n",(unsigned __int32)(19L / 17L),((19L % 17L) == 0L)?0L:1L,((unsigned __int32)(19L / 17L)) + (((19L % 17L) == 0L)?0L:1L));
it seems to be a simple issue of operator precedence. I definitely have been programming for too long today :)

Resources