So i'm making a Wordle clone and i keep getting a "indexerror: string is out of range" and i dont know what to do and every time i do the second guess it will say indexerrror string is out off range
at line 30
import random
def Wordle():
position = 0
clue = ""
print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
user_name = input("Enter your name:")
valid_words = ['sweet','shark','about','maybe','tweet','shard','pleat','elder','table','birds','among','share','label','frame','water','earth','winds','empty','audio','pilot','radio','steel','words','chair','drips','mouse','moose','beach','cloud','yours','house','holes','short','small','large','glass','ruler','boxes','charm','tools']
TheAnswer = random.choice(valid_words)
print(TheAnswer)
number_of_guesses = 1
guessed_correct = False
while number_of_guesses < 7 and not guessed_correct:
print(' ')
TheGuess = input('Enter your guess (it have to be a 5-letter word and not captalied letters):')
if len(TheGuess) > 5:
print('word is not acceptable')
else:
print(' ')
for letter in TheGuess:
if letter == TheAnswer[position]:
clue += ' V'
elif letter in TheAnswer:
clue += ' O'
else:
clue += ' F'
position += 1
print(clue)
if TheGuess == TheAnswer:
guessed_correct = True
else:
guessed_correct = False
number_of_guesses += 1
clue = ""
if guessed_correct:
print('Congradulations', user_name,', you won and only used', number_of_guesses,'guesses, :D')
else:
print(user_name,'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
You are indexing TheAnswer[position] which basically means if TheAnswer is x length long, then the position should be,
But since the position variable is a local variable of the function, it continuously increases on each guess. Does not get reset on each guess.
Try moving the
position = 0
Into top of the while loop.
Code,
import random
def Wordle():
clue = ""
print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
user_name = input("Enter your name:")
valid_words = ['sweet', 'shark', 'about', 'maybe', 'tweet', 'shard', 'pleat', 'elder', 'table', 'birds', 'among', 'share', 'label', 'frame', 'water', 'earth', 'winds', 'empty', 'audio',
'pilot', 'radio', 'steel', 'words', 'chair', 'drips', 'mouse', 'moose', 'beach', 'cloud', 'yours', 'house', 'holes', 'short', 'small', 'large', 'glass', 'ruler', 'boxes', 'charm', 'tools']
TheAnswer = random.choice(valid_words)
print(TheAnswer)
number_of_guesses = 1
guessed_correct = False
while number_of_guesses < 7 and not guessed_correct:
position = 0
print(' ')
TheGuess = input(
'Enter your guess (it have to be a 5-letter word and not captalied letters):')
if len(TheGuess) > 5:
print('word is not acceptable')
else:
print(' ')
for letter in TheGuess:
if letter == TheAnswer[position]:
clue += ' V'
elif letter in TheAnswer:
clue += ' O'
else:
clue += ' F'
position += 1
print(clue)
if TheGuess == TheAnswer:
guessed_correct = True
else:
guessed_correct = False
number_of_guesses += 1
clue = ""
if guessed_correct:
print('Congradulations', user_name, ', you won and only used',
number_of_guesses, 'guesses, :D')
else:
print(
user_name, 'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
Thanks!
My problem is the script ends immediately after I enter an input.
def add(var1, var2):
print(var1 + var2)
def times(var1, var2):
print(var1*var2)
x = input("press 1 to add, press 2 to multiply: ")
if x == 1:
print("what two number do you want to add?")
a = input("input first number: ")
b = input("input second number: ")
add(a, b)
elif x == 2:
print("what two number do you want to multiply?")
a = input("input first number: ")
b = input("input second number: ")
times(a, b)
I want the script to run the if-elif statement which is dependent on the entered input.
The input function returns a string. You should therefore either compare its returning value to a string instead of an integer:
if x == '1':
...
if x == '2':
or convert the returning value to an integer first:
x = int(input("press 1 to add, press 2 to multiply: "))
The input will be a string not a number, and 2 != '2'. You need to convert the input to an integer before trying to use it.
input() will return str, you need to convert it to int before calculating.
x = input("press 1 to add, press 2 to multiply: ")
Program: Input a name and Print the Initials and with surname.
Input:- Ted Vivian Mosby
Output:- T V Mosby
Using Python 3 online compiler:-
https://repl.it/languages/python3
user = input('Please Enter your name \n')
length = len(user)
value=0
for a in range(0,length-1):
if a==" ":
value=a
for b in range(0,value):
if b==0:
print(user[0])
elif user[b]==" ":
print(user[b+1])
for c in range(value+1,length):
print(user[c])
The output I have is:-
Please Enter your name
Ted Vivian Mosby
e
d
V
i
v
i
a
n
M
o
s
b
y
Here's a pythonic way to do it. Notice it takes into account all names, no matter how many middle names.
name = input("Please enter a name: ")
names = name.split()
initials = [x[0] for x in names[:-1]]
print(*initials, names[-1])
"""
Broken down:
name.split() = ['Ted', 'David', 'Vivican', 'Mosby'] Note ive added an extra name for show
name.split()[:-1] = ['Ted', 'David', 'Vivican']
[x[0] for name in ['Ted', 'David', 'Vivican']] = ['T', 'D', 'V']
print(*initials) unpacks each value in the list to the function eg
print(*['T', 'D', 'V']) == print('T', 'D', 'V')
"""
Use split() to separate out the names. Then print the first char of each name, but the entire last name.
user = input('Please Enter your name \n')
names = user.split()
for i in range(0, len(names)):
if i < len(names) - 1:
# print first char only, no newline at the end
print(names[i][0], end=" ")
else:
# print entire last name
print(names[i]) # print entire name
user = input('Please Enter your name \n')
length = len(user.split(" "))
value=0
print(length)
for a in user.split(" "):
if(value==length-1):
print(a)
else:
print(a[0],end=' ')
value+=1
I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.
For an intro comp sci lab I'm trying to build a recursive function that counts the number of occurrences of a given letter in a string without using built in methods or loops. I'm pretty stumped without the use of myStr.count. Can anyone offer a tip? should I try something that checks the identity of myStr[0] and returns 0 if letter != myStr[0]?
def count(letter, myStr, theLen):
#Code for def count
def main():
print ("The count of letter a is: ", count("a", "abacdadaad", 10))
print ("The count of letter b is: ", count("b", "abacdadaad", 10))
print ("The count of letter c is: ", count("c", "abacdadaad", 10))
print ("The count of letter d is: ", count("d", "abacdadaad", 10))
main()
Usually, when writing something recursively, the main problem is to determine what is the condition for return. Obviously, when counting letters in a string, it is the moment when you are testing the last character of the string.
You could try:
def recursive(string, letter):
if len(string) == 1 and string == letter:
return 1;
elif len(string) == 1:
return 0;
if string[0] == letter:
count = 1 + recursive(string[1:], letter)
else:
count = recursive(string[1:], letter)
return count