moving between indexes in a list in python - python-3.x

In Python, I populate info from a file to a list and then print the first index in the list, now I want to print the next index from the list without multiple my code.
How can I promote the index i'm printing?
question = open("questions.txt", "r")
print(question.readlines()[0])
tanswer = open("answers.txt", "r")
correct_answer = float(tanswer.readlines()[0])
uanswer = float(input("Write the answer: "))
if correct_answer==uanswer:
print("Amazing " + str(correct_answer) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")

As far as I understood, you are trying to split the lines.
let's say
line = '1000 2000 3000'
line = line.split(' ')
then you will get line[0]
Try this I hope this helps.

Use zip:
with open("questions.txt") as ques, open("answers.txt") as ans:
for q, a in zip(ques, ans):
print(q)
uanswer = input("Write the answer: ")
if float(a) == float(uanswer):
print("Amazing " + str(a) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")

Related

Improving in function clarity and efficiency in python

I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())

How to convert my loop into a function that I can call anytime

Good day. I have this snippet as a part of my script. I wanted to convert this into a function as this snippet is called a few times.
query = string-to-search-variable
for j in search(query, tld="co.in", num=5, stop=5, pause=2):
res = get_tld(j, as_object=True)
print(" " + "\t" + res.fld, end=" ")
You mean something like this so you can just call res_function(query)?
def res_function(query):
for j in search(query, tld="co.in", num=5, stop=5, pause=2):
res = get_tld(j, as_object=True)
print(" " + "\t" + res.fld, end=" ")

Python 3.7: How do I check if a user input is in a specific format, like "XdY", then if invalid ask again for input?

I'm trying to write a dice roller as practice. I've tried to look into try, except, while, but neither works as I intend it - before asking if the user wants to continue, I'd want to check if the user input is valid, and if not, return to user_number1. Am I looking at this from the wrong angle? What can I do with this?
Sorry for the possibly stupid question, I'm pretty new to this.
import random
print("Welcome to the dice roller!")
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
if num1 == 1:
result1 = random.randint(num1, num1*num2)
print("Your roll is: " + str(result1) + " (" + str(num1) + "d" + str(num2) + ")" )
else:
dice_number = 1
list_of_results = []
while dice_number <= num1:
result2 = random.randint(num1, num2)
list_of_results.append(result2)
dice_number += 1
print("Your roll is: " + str(sum(list_of_results)) + " (" + str(num1) + "d" + str(num2) + ", " + str(list_of_results)+ ")")
def shouldi():
roller()
usercont = input("Do you want to continue? y/n > ")
while usercont in ["Y", "y"]:
roller()
usercont = input("Do you want to continue? y/n > ")
if usercont in ["N", "n"]:
print("Thank you for using the dice roller. Bye!")
quit()
else:
print("That is not a valid input.")
usercont
Something like below is an alternate approach to using regex. If you're comfortable with regex then I would prefer using that instead of this. This is only an alternate approach.
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
if("d" in user_number1):
if(len(user_number1) == 3):
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
else:
print("Your input not in valid format. Use the format XdX")
You can use regular expressions and write a function that does exactly what you need then you can use it within your roller() function:
import re
def get_number():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = re.match("^(\\d*)d(\\d+)$",user_number1,re.I)
if not user_number_fin: get_number()
if user_number_fin.group(1) =='': num1 = 1
else: num1 = int(user_number_fin.group(1))
num2 = int(user_number_fin.group(2))
if num1>num2:
print("\n\tSorry--side to roll must be less than the number of sides!!")
get_number()
return {'num1':num1,'num2':num2}
This can accept d4 ie taking the default side if not given to be 1, and cannot accept 4d3 ie the side to be rolled must be less than the number of sides present in the dice.

Getting the Error Despite Correct Output

getting this error meassage despite having exactly same output as expected output.
* ERROR: Expected to find a number in the line Available Letters: abcdefghijklmnopqrstuvwxyz.
Check to be sure your lines match up with the expected output!!! *
MY CODE:
def hangman(secretWord):
print ("Welcome to the game, Hangman!")
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
lettersGuessed=[]
guesses = 8
p = " "
while guesses > 0:
print ("You have " + str(guesses) + " guesses left")
print ("Available Letters: " + str(getAvailableLetters(lettersGuessed))),
user_input = input("Please guess a letter: ")
user_input = str(user_input)
user_input = user_input.lower()
if user_input in lettersGuessed:
print ("Oops! You've already guessed that letter: " + str(getGuessedWord(secretWord, lettersGuessed)))
else:
lettersGuessed.append(user_input)
if user_input in secretWord:
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
if isWordGuessed(secretWord, lettersGuessed):
break
else: continue
else:
print("Oops! That letter is not in my word: " + str(getGuessedWord(secretWord, lettersGuessed)))
guesses = guesses - 1
p = str(getGuessedWord(secretWord, lettersGuessed))
p = p.split(" ")
p = "".join(p)
p = str(p)
if p == secretWord:
print ("Congratulations, you won!")
return
else:
print ("Sorry, you ran out of guesses. The word was " + secretWord + ".")
return
Check each line and "be sure your lines match up with the expected output".
It's possible the automated system that is checking the output requires the lines of output must exactly match their "correct output" including the ----------- lines, and you're code doesn't print those lines.
Easy as:
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print ("-----------") ### <---- Add this one line
lettersGuessed=[]
and
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
print ("-----------") ### <---- Add this one line
if isWordGuessed(secretWord, lettersGuessed):
It's possible that you'll need to add that one line in other conditions within the code, as in the else: conditions.
And as always to make debugging easier, less repetition and cleaner code, you could assign that output to a variable and print it when needed:
def hangman(secretWord):
line_break = "-----------"
...
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print (line_break)
, etc.
Hope this helps.

How do I make my python code so that only text can be entered?

import random
def diceRoll(number):
roll = random.randint(1,number)
print("Rolling a ",number," sided die.")
return roll
def newAccount(playername):
print("Greetings ", playername,"! We'll generate your charecter's attributes by rolling some die")
skillroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
strengthroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
print("You have ",skillroll," skillpoints and ",strengthroll," strength!")
class newplayer:
name = playername
skill = skillroll
strength = strengthroll
save(newplayer)
def save(newplayer):
"""Saves all details"""
file = open("accounts.txt","a")
file.write("CharacterName = '" + newplayer.name + "'\n")
file.write("Strength = " + str(newplayer.strength) + '\n')
file.write("Skill = " + str(newplayer.skill) + '\n')
file.write("\n")
print("Saved account")
def newPlayer():
try:
player1 = input("What is your 1st player's name? ")
newAccount(player1)
except:
print("Please only enter letters for your character name ")
newPlayer()
newPlayer()
print(" ")
player2 = input("What is your 2nd player's name? ")
newAccount(player2)
The part in bold is the part of the code I have attempted to alter to add some sort of error handling. Someone help me out here please, I know it's probably simple but I can't find an answer to this question anywhere.
Pythons RegEx would be a quite easy solution:
import re
if not re.match("[a-z]+$",inputString):
#your exception handling

Resources